Skip to content
pi-c Documentation
Login

Documentation

/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This file is automatically generated. Edit at your own risk. */
#if !defined(ORG_FOSSIL_SCM_LIBFOSSIL_AMAL_H_INCLUDED)
#define ORG_FOSSIL_SCM_LIBFOSSIL_AMAL_H_INCLUDED
#undef FSL_AMALGAMATION_BUILD
#define FSL_AMALGAMATION_BUILD 1
#define FSL_PACKAGE_NAME "libfossil"
#define FSL_LIBRARY_VERSION "0.6.1"
#define FSL_LIB_VERSION_HASH "b176dffe8cfe36843b87d961a7afb7115c17f9271ccdcdef8efe42685ff5ac6f"
#define FSL_LIB_VERSION_TIMESTAMP "2026-11-20 03:54:30.421 UTC"
#define FSL_LIB_CONFIG_TIMESTAMP "2026-11-20 11:36 GMT"
#define FSL_AUX_SCHEMA "2015-01-24"
#define FSL_CONTENT_SCHEMA "2"
#define FOSSIL_RELEASE_VERSION_NUMBER 22700
#define FOSSIL_MANIFEST_NUMERIC_DATE 20250727
#define FOSSIL_MANIFEST_NUMERIC_TIME 110738

#if defined(HAVE_CONFIG_H)
#  include "config.h"
#endif
#if defined(HAVE_LIBFOSSIL_CONFIG_H)
#  include "libfossil-config.h"
#endif
#include "sqlite3.h"
/* start of file include/fossil-scm/config.h */
#if !defined (ORG_FOSSIL_SCM_FSL_CONFIG_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_CONFIG_H_INCLUDED
/*
  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-FileType: Code

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

*/


#if !defined(_ISOC99_SOURCE)
/* glibc apparently guards snprintf() on this #define, even though
   snprintf() is part of C99 and we're building in C99 mode. */
#  define _ISOC99_SOURCE
#endif
#if !defined(_C99_SOURCE)
/* Some Mac enviorments guard snprintf() on this #define but do not
   #define it when building in C99 mode. */
#  define _C99_SOURCE
#endif

#if !defined(FSL_AUX_SCHEMA)
#  error "Expecting FSL_AUX_SCHEMA to be defined by the configuration bits."
#endif
#if !defined(FSL_LIBRARY_VERSION)
#  error "Expecting FSL_LIBRARY_VERSION to be defined by the configuration bits."
#endif

/**
   FSL_API_ARMOR is a not-yet-widely-implemented feature adopted from
   SQLite, in which many APIs will perform more argument validation
   against NULL pointers or values which might, if unchecked, lead to
   illegal memory access. Without this flag, such APIs have undefined
   behavior with such illegal arguments but use fewer CPU cycles.
*/
#if !defined(FSL_API_ARMOR)
#  define FSL_API_ARMOR 1
#endif


#ifdef _WIN32
# if defined(BUILD_libfossil_static) || defined(FSL_AMALGAMATION_BUILD)
#  define FSL_EXPORT extern
# elif defined(BUILD_libfossil)
#  define FSL_EXPORT extern __declspec(dllexport)
# else
#  define FSL_EXPORT extern __declspec(dllimport)
# endif
#else
# define FSL_EXPORT extern
#endif

#if !defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L)
#  if defined(__cplusplus) && !defined(__STDC_FORMAT_MACROS)
/* inttypes.h needs this for the PRI* and SCN* macros in C++ mode. */
#    define __STDC_FORMAT_MACROS
#  else
#    error "This tree requires a standards-compliant C99-capable compiler."
#  endif
#endif

#if defined(_MSC_VER)
#  define FSL_PLATFORM_IS_WINDOWS 1
#  define FSL_PLATFORM_IS_UNIX 0
#  define FSL_PLATFORM_PLATFORM "windows"
/* define a __func__ compatibility macro */
#  if _MSC_VER < 1500    /* (vc9.0; dev studio 2008) */
/* sorry; cant do much better than nothing at all on those earlier ones */
#    define __func__ "(func)"
#  else
#    define __func__ __FUNCTION__
#  endif
/* for the time being at least, don't complain about there being secure crt alternatives: */
#  ifndef _CRT_SECURE_NO_WARNINGS
#    define _CRT_SECURE_NO_WARNINGS
#  endif
/* for the time being at least, don't complain about using POSIX names instead of ISO C++: */
#  pragma warning ( disable : 4996 )
/* for the time being at least, suppresss some int conversion warnings */
#  pragma warning ( disable : 4244 )     /*'fsl_size_t' to 'int'; this masks other problems that should be fixed*/
#  pragma warning ( disable : 4761 )     /*'integral size mismatch in argument'; more size_t problems*/
#  pragma warning ( disable : 4267 )     /*'size_t' to 'int'; crops up especially in 64-bit builds*/
/* these were extracted from fossil's unistd.h */
#  define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#  include <io.h>
#elif defined(__MINGW32__)
#  define FSL_PLATFORM_IS_WINDOWS 1
#  define FSL_PLATFORM_IS_UNIX 0
#  define FSL_PLATFORM_PLATFORM "windows"
#elif defined(__CYGWIN__)
#  define FSL_PLATFORM_IS_WINDOWS 0
#  define FSL_PLATFORM_IS_UNIX 1
#  define FSL_PLATFORM_PLATFORM "unix"
#else
#  define FSL_PLATFORM_IS_WINDOWS 0
#  define FSL_PLATFORM_IS_UNIX 1
#  define FSL_PLATFORM_PLATFORM "unix"
#endif

#if !defined(HAVE_SIGACTION)
#  if defined(FSL_PLATFORM_IS_UNIX)
#    define HAVE_SIGACTION 1
#  else
#    define HAVE_SIGACTION 0
#  endif
#endif

#include <stdint.h>
#include <inttypes.h>


/** @typedef some_int_type fsl_int_t

    fsl_int_t is a signed integer type used to denote "relative"
    ranges and lengths, or to tell a routine that it should try to
    figure out the length of some byte array itself (e.g.  by using
    fsl_strlen() on it). It is provided primarily for
    documentation/readability purposes, to avoid confusion with the
    widely varying integer semantics used by various APIs. This type
    is never used as a return type for functions which use "result
    code semantics". Those always use an unadorned integer type or
    some API-specific enum type.

    The library typedefs this to a 64-bit type if possible, else
    a 32-bit type.

    @see fsl_strlen_t
*/
typedef int64_t fsl_int_t;
/**
    The unsigned counterpart of fsl_int_t.
*/
typedef uint64_t fsl_uint_t;

/**
   A 32-bit unsigned int type. This typedef is primarily to
   improve documentation of the intent of function arguments
   and struct members.
*/
typedef uint32_t fsl_flag32_t;
typedef uint16_t fsl_flag16_t;

/**
   A signed integer type intended for use with APIs which allow a
   negative value as a length, where a negative value means to use
   strlen(), or an equivalent, to calculate the value.

   This type is limited to 31 length bits because it is most
   frequently used with data intended for sqlite3 APIs which have that
   limitation.
*/
typedef int32_t fsl_strlen_t;

/** @def FSL_INT_T_PFMT
    Fossil's fsl_int_t equivalent of C99's PRIi32 and friends.
 */
#define FSL_INT_T_PFMT PRIi64
/** @def FSL_INT_T_SFMT

    Fossil's fsl_int_t equivalent of C99's SCNi32 and friends.
 */
#define FSL_INT_T_SFMT SCNi64
/** @def FSL_UINT_T_PFMT

    Fossil's fsl_uint_t equivalent of C99's PRIu32 and friends.
 */
#define FSL_UINT_T_PFMT PRIu64
/** @def FSL_UINT_T_SFMT

    Fossil's fsl_uint_t equivalent of C99's SCNu32 and friends.
 */
#define FSL_UINT_T_SFMT SCNu64

/** @def FSL_JULIAN_T_PFMT

    An output format specifier for Julian-format doubles.
 */
#define FSL_JULIAN_T_PFMT ".17g"

/**
    fsl_size_t is an unsigned integer type used to denote absolute
    ranges and lengths. It is provided primarily for
    documentation/readability purposes, to avoid confusion with the
    widely varying integer semantics used by various APIs. While a
    32-bit type is legal, a 64-bit type is required for "unusually
    large" repos and for some metrics reporting even for mid-sized
    repos.
 */
typedef uint64_t fsl_size_t;

/** @def FSL_SIZE_T_PFMT

    Fossil's fsl_size_t equivalent of C99's PRIu32 and friends.

    ACHTUNG: when passing arguments of this type of fsl_appendf(), or
    any function which uses it for formatting purposes, it is very
    important if if you pass _literal integers_ OR enum values, that
    they be cast to fsl_size_t, or the va_list handling might extract
    the wrong number of bytes from the argument list, leading to
    really weird side-effects via what is effectively memory
    corruption.

    That warning applies primarily to the following typedefs and their
    format specifiers: fsl_size_t, fsl_int_t, fsl_uint_t, fsl_id_t.

    The warning does not apply to strongly-typed arguments,
    e.g. variables of the proper type, so long as the format specifier
    string matches the argument type.

    For example:

    ```
    fsl_size_t sz = 3;
    fsl_fprintf( stdout, "%"FSL_SIZE_T_PFMT" %"FSL_SIZE_T_PFMT\n",
                 sz, // OK!
                 3 // BAD! See below...
                 );
    ```

    The "fix" is to cast the literal 3 to a fsl_size_t resp. the type
    appropriate for the format specifier. That ensures that there is
    no (or much less ;) confusion when va_arg() extracts arguments
    from the variadic array.

    Reminders to self:

    ```
    int i = 0;
    f_out(("#%d: %"FSL_ID_T_PFMT" %"FSL_ID_T_PFMT" %"FSL_ID_T_PFMT"\n",
            ++i, 1, 2, 3));
    f_out(("#%d: %"FSL_SIZE_T_PFMT" %"FSL_ID_T_PFMT" %"FSL_SIZE_T_PFMT"\n",
           ++i, (fsl_size_t)1, (fsl_id_t)2, (fsl_size_t)3));
    // This one is the (generally) problematic case:
    f_out(("#%d: %"FSL_SIZE_T_PFMT" %"FSL_ID_T_PFMT" %"FSL_SIZE_T_PFMT"\n",
           ++i, 1, 2, 3));
    ```

    The above was Tested with gcc, clang, tcc on a 32-bit linux
    platform (it has not been problematic on 64-bit builds!). The
    above problem was reproduced on all compiler combinations i
    tricored. Current code (20130824) seems to be behaving well as long
    as callers always cast to help variadic arg handling DTRT.
 */
#define FSL_SIZE_T_PFMT FSL_UINT_T_PFMT

/** @def FSL_SIZE_T_SFMT

    Fossil's fsl_int_t equivalent of C99's SCNu32 and friends.
 */
#define FSL_SIZE_T_SFMT FSL_UINT_T_SFMT

/**
    fsl_id_t is a signed integer type used to store database record
    IDs. It is provided primarily for documentation/readability purposes,
    to avoid confusion with the widely varying integer semantics used
    by various APIs.

    This type "could" be 32-bit (instead of 64) because the
    oldest/largest Fossil repo (the TCL tree, with 15 years of
    history) currently (August 2013) has only 131k RIDs. HOWEVER,
    changing this type can have side-effects vis-a-vis va_arg() deep
    in the fsl_appendf() implementation if FSL_ID_T_PFMT is not 100%
    correct for this typedef. After changing this, _make sure_ to do a
    full clean rebuild and test thoroughly because changing a sizeof
    can produce weird side-effects (effectively memory corruption) on
    unclean rebuilds.
 */
typedef int32_t fsl_id_t;

/** @def FSL_ID_T_PFMT

    Fossil's fsl_id_t equivalent of C99's PRIi32 and friends.

    ACHTUNG: see FSL_SIZE_T_PFMT for important details.
 */
#define FSL_ID_T_PFMT PRIi32

/** @def FSL_ID_T_SFMT

    Fossil's fsl_id_t equivalent of C99's SCNi32 and friends.
 */
#define FSL_ID_T_SFMT SCNi32

/**
    The type used to represent type values. Unless noted otherwise,
    the general convention is Unix Epoch. That said, Fossil internally
    uses Julian Date for times, so this typedef is clearly the result
    of over-specification/over-thinking the problem. THAT said,
    application-level code more commonly works with Unix timestamps,
    so... here it is. Over-specified, perhaps, but not 100%
    unjustifiable.
 */
typedef int64_t fsl_time_t;

/** @def FSL_TIME_T_PFMT

    Fossil's fsl_time_t equivalent of C99's PRIi32 and friends.
 */
#define FSL_TIME_T_PFMT PRIi64

/** @def FSL_TIME_T_SFMT

    Fossil's fsl_time_t equivalent of C99's SCNi32 and friends.
 */
#define FSL_TIME_T_SFMT SCNi64

/**
   If true, the fsl_timer_xxx() family of functions might do something useful,
   otherwise they do not.
 */
#define FSL_CONFIG_ENABLE_TIMER 1

#if !defined(FSL_ENABLE_SQLITE_REGEXP)
#  define FSL_ENABLE_SQLITE_REGEXP 0
#endif

/**
   fossil(1)'s internal buffer size upper limit, which is also its
   blob.content size limit. Changing this has no magic ability to push
   past this limit, as pushing past them would create content
   incompatible with fossil(1), and going past just shy of 2gb would
   exceed sqlite3's limits.
*/
#define FSL_BLOB_MAX_SIZE 0x7fff0000

#if !defined(FSL_SWITCH_FALL_THROUGH)
#  if defined(__GNUC__) && !defined(__clang__) && (__GNUC__ >= 7)
/*
  #define FSL_USING_GCC

  gcc v7+ treats implicit 'switch' fallthrough as a warning
  (i.e. error because we always build with -Wall -Werror -Wextra
  -pedantic).

  Similarly braindead, clang #defines __GNUC__.

  _Sigh_.
*/
#    define FSL_SWITCH_FALL_THROUGH __attribute__ ((fallthrough))
#  else
#    define FSL_SWITCH_FALL_THROUGH
#  endif
#endif
/* /FSL_SWITCH_FALL_THROUGH

   TODO: add support for the C++ attributes for doing this.
*/

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


#endif
/* ORG_FOSSIL_SCM_FSL_CONFIG_H_INCLUDED */
/* end of file include/fossil-scm/config.h */
/* start of file include/fossil-scm/util.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_UTIL_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_UTIL_H_INCLUDED
/*
  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-FileType: Code

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

*/

/** @file util.h

    This file declares a number of utility classes and routines used by
    libfossil. All of them considered "public", suitable for direct use
    by client code.
*/

#include <stdio.h> /* FILE type */
#include <stdarg.h> /* va_list */
#include <time.h> /* tm struct */
#include <stdbool.h>
#if defined(__cplusplus)
extern "C" {
#endif
typedef struct fsl_allocator fsl_allocator;
typedef struct fsl_b fsl_b;
typedef struct fsl_error fsl_error;
typedef struct fsl_finalizer fsl_finalizer;
typedef struct fsl_fstat fsl_fstat;
typedef struct fsl_list fsl_list;
typedef struct fsl_outputer fsl_outputer;
typedef struct fsl_state fsl_state;
typedef struct fsl_id_bag fsl_id_bag;

/**
   fsl_uuid_str and fsl_uuid_cstr are "for documentation and
   readability purposes" typedefs used to denote strings which the API
   requires to be in the form of Fossil UUID strings. Such strings are
   exactly FSL_STRLEN_SHA1 or FSL_STRLEN_K256 bytes long plus a
   terminating NUL byte and contain only lower-case hexadecimal
   bytes. Where this typedef is used, the library requires, enforces,
   and/or assumes (at different times) that fsl_is_uuid() returns true
   for such strings (if they are not NULL, though not all contexts
   allow a NULL UUID). These typedef are _not_ used to denote
   arguments which may refer to partial UUIDs or symbolic names, only
   100% bonafide Fossil UUIDs (which are different from RFC4122
   UUIDs).

   The API guarantees that this typedef will always be (char *) and
   that fsl_uuid_cstr will always ben (char const *), and thus it
   is safe/portable to use those type instead of these. These
   typedefs serve only to improve the readability of certain APIs
   by implying (through the use of this typedef) the preconditions
   defined for UUID strings.

   Sidebar: fossil historically used the term UUID for blob IDs, and
   still uses that term in the DB schema, but it has fallen out of
   favor in documentation and discussions, with "hash" being the
   preferred term. Much of the libfossil code was developed before
   that happened, though, so "UUID" is still prevalent in its API and
   documentation.

   @see fsl_is_uuid()
   @see fsl_uuid_cstr
*/
typedef char * fsl_uuid_str;

/**
   The const counterpart of fsl_uuid_str.

   @see fsl_is_uuid()
   @see fsl_uuid_str
*/
typedef char const * fsl_uuid_cstr;

/**
   A typedef for comparison function used by standard C routines such
   as qsort(). It is provided here primarily to simplify documentation
   of other APIs. Concrete implementations must compare lhs and rhs,
   returning negative, 0, or positive depending on whether lhs is less
   than, equal to, or greater than rhs.

   Implementations might need to be able to deal with NULL
   arguments. That depends on the routine which uses the comparison
   function.
*/
typedef int (*fsl_generic_cmp_f)( void const * lhs, void const * rhs );

/**
   If the NUL-terminated input str is exactly FSL_STRLEN_SHA1 or
   FSL_STRLEN_K256 bytes long and contains only lower-case
   hexadecimal characters, returns the length of the string, else
   returns 0.

   Note that Fossil UUIDs are not RFC4122 UUIDs, but are SHA1 or
   SHA3-256 hash strings. Don't let that disturb you. As Tim
   Berners-Lee writes:

   > The assertion that the space of URIs is a universal space
   sometimes encounters opposition from those who feel there should
   not be one universal space. These people need not oppose the
   concept because it is not of a single universal space: Indeed,
   the fact that URIs form universal space does not prevent anyone
   else from forming their own universal space, which of course by
   definition would be able to envelop within it as a subset the
   universal URI space. Therefore the web meets the "independent
   design" test, that if a similar system had been concurrently and
   independently invented elsewhere, in such a way that the
   arbitrary design decisions were made differently, when they met
   later, the two systems could be made to interoperate.

   Source: https://www.w3.org/DesignIssues/Axioms.html

   (Just mentally translate URI as UUID.)
*/
FSL_EXPORT int fsl_is_uuid(char const * str);

/**
   If x is a valid fossil UUID length, it is returned, else 0 is returned.
*/
FSL_EXPORT int fsl_is_uuid_len(int x);

/**
   Expects str to be a string containing an unsigned decimal
   value. Returns its decoded value, or -1 on error.
*/
FSL_EXPORT fsl_size_t fsl_str_to_size(char const * str);

/**
   Expects str to be a string containing a decimal value,
   optionally with a leading sign. Returns its decoded value, or
   dflt if !str or on error.
*/
FSL_EXPORT fsl_int_t fsl_str_to_int(char const * str, fsl_int_t dflt);


/**
   Generic list container type. This is used heavily by the Fossil
   API for storing arrays of dynamically-allocated objects. It is
   not useful as a non-pointer-array replacement.

   It is up to the APIs using this type to manage the entry count
   member and use fsl_list_reserve() to manage the "capacity"
   member.

   @see fsl_list_reserve()
   @see fsl_list_append()
   @see fsl_list_visit()
*/
struct fsl_list {
  /**
     Array of entries. It contains this->capacity entries,
     this->used of which are "valid" (in use).
  */
  void ** list;
  /**
     Number of "used" entries in the list.
  */
  fsl_size_t used;
  /**
     Number of slots allocated in this->list. Use fsl_list_reserve()
     to modify this. Doing so might move the this->list pointer but
     the values it points to will stay stable.
  */
  fsl_size_t capacity;
};

/**
   Empty-initialized fsl_list structure, intended for const-copy
   initialization.
*/
#define fsl_list_empty_m { .list=NULL, .used=0, .capacity=0 }

/**
   Empty-initialized fsl_list structure, intended for copy
   initialization.
*/
FSL_EXPORT const fsl_list fsl_list_empty;

/**
   Generic interface for finalizing/freeing memory. Intended
   primarily for use as a destructor/finalizer for high-level
   structs. Implementations must semantically behave like free(mem),
   regardless of whether or not they actually free the memory. At
   the very least, they generally should clean up any memory owned by
   mem (e.g. db resources or buffers), even if they do not free() mem.
   some implementations assume that mem is stack-allocated
   and they only clean up resources owned by mem.

   The state parameter is any state needed by the finalizer
   (e.g. a memory allocation context) and mem is the memory which is
   being finalized.

   The exact interpretaion of the state and mem are of course
   implementation-specific.
*/
typedef void (*fsl_finalizer_f)( void * state, void * mem );

/**
   Generic interface for memory finalizers.
*/
struct fsl_finalizer {
  /**
     State to be passed as the first argument to f().
  */
  void * state;
  /**
     Finalizer function. Should be called like this->f( this->state, ... ).
  */
  fsl_finalizer_f f;
};

/** Empty-initialized fsl_finalizer struct. */
#define fsl_finalizer_empty_m {NULL,NULL}

/**
   fsl_finalizer_f() impl which requires that mem be-a
   (fsl_b*).  This function frees all memory associated with
   that buffer and zeroes out the structure, but does not free mem
   (because it is rare that fsl_bs are created on the
   heap). The state parameter is ignored.
*/
FSL_EXPORT int fsl_finalizer_f_buffer( void * state, void * mem );


/**
   Generic state-with-finalizer holder. Used for binding
   client-specified state to another object, such that a
   client-specified finalizer is called with the other object is
   cleaned up.
*/
struct fsl_state {
  /**
     Arbitrary context-dependent state.
  */
  void * state;
  /**
     Finalizer for this->state. If used, it should be called like:

     ```
     this->finalize.f( this->finalize.state, this->state );
     ```

     After which this->state must be treated as if it has been
     free(3)'d. See fsl_state_finalize().
  */
  fsl_finalizer finalize;
};

/** Empty-initialized fsl_state struct. */
#define fsl_state_empty_m {NULL,fsl_finalizer_empty_m}

/**
   Empty-initialized fsl_state struct, intended for
   copy-initializing.
*/
FSL_EXPORT const fsl_state fsl_state_empty;

/**
   If fst is not NULL then:

   - If fst->finalize.f is not null, then it is called and
     passed (fst->finalize.f, fst->state).

   - *fst is cleared out. fst is not freed.

   This is a no-op if fst is NULL.
*/
void fsl_state_finalize(fsl_state * fst);

/**
   Generic interface for streaming out data. Implementations must
   write n bytes from src to their destination channel and return 0
   on success, non-0 on error (assumed to be a value from the fsl_rc_e
   enum). The state parameter is the implementation-specified output
   channel.

   Potential TODO: change the final argument to a pointer, with
   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, 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
   interpretation of the state parameter is
   implementation-specific.
*/
typedef int (*fsl_flush_f)(void * state);

/**
   Generic interface for streaming in data. Implementations must
   read (at most) *n bytes from their input, copy it to dest, assign
   *n to the number of bytes actually read, return 0 on success, and
   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.

   Implementations may need to distinguish a short read due to EOF
   from a short read due to an I/O error, e.g. using feof() and/or
   ferror().
*/
typedef int (*fsl_input_f)( void * state, void * dest, 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 );

/**
   An interface which encapsulates data for managing an output
   destination, primarily intended for use with fsl_output(). Why
   abstract it to this level? So that we can do interesting things
   like output to buffers, files, sockets, etc., using the core
   output mechanism. e.g. so script bindings can send their output
   to the same channel used by the library and other library
   clients.
*/
struct fsl_outputer {
  /**
     Output channel.
  */
  fsl_output_f out;
  /**
     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, ... ) and this->flush(this->state).
  */
  void * state;
};
/** Empty-initialized fsl_outputer instance. */
#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
   member to an opened-for-write (FILE*) handle. By default it will
   use stdout.
*/
FSL_EXPORT const fsl_outputer fsl_outputer_FILE;

/**
   fsl_outputer initializer which uses fsl_flush_f_FILE() and
   fsl_output_f_FILE(). After copying, the state member must be
   pointed to an opened-for-writing (FILE*).
*/
#define fsl_outputer_FILE_m { \
  .out = fsl_output_f_FILE,   \
  .flush = fsl_flush_f_FILE,  \
  .state = NULL               \
}

/**
   Generic stateful alloc/free/realloc() interface.

   Implementations must behave as follows:

   - If 0==n then semantically behave like free(3) and return
   NULL.

   - If 0!=n and !mem then semantically behave like malloc(3), returning
   newly-allocated memory on success and NULL on error.

   - If 0!=n and NULL!=mem then semantically behave like
   realloc(3). Note that realloc specifies: "If n was equal to 0,
   either NULL or a pointer suitable to be passed to free() is
   returned." Which is kind of useless, and thus implementations
   MUST return NULL when n==0.
*/
typedef void *(*fsl_realloc_f)(void * state, void * mem, fsl_size_t n);

/**
   Holds an allocator function and its related state.
*/
struct fsl_allocator {
  /**
     Base allocator function. It must be passed this->state as its
     first argument.
  */
  fsl_realloc_f f;
  /**
     State intended to be passed as the first argument to this->f().
  */
  void * state;
};

/** Empty-initialized fsl_allocator instance. */
#define fsl_allocator_empty_m {NULL,NULL}


/**
   A fsl_realloc_f() implementation which uses the standard
   malloc()/free()/realloc(). The state parameter is ignored.
*/
FSL_EXPORT void * fsl_realloc_f_stdalloc(void * state, void * mem, fsl_size_t n);

/**
   Semantically behaves like malloc(3), but may introduce instrumentation,
   error checking, or similar.
*/
FSL_EXPORT void * fsl_malloc( fsl_size_t n )
#ifdef __GNUC__
  __attribute__ ((malloc))
#endif
  ;

/**
   Semantically behaves like free(3), but may introduce instrumentation,
   error checking, or similar.
*/
FSL_EXPORT void fsl_free( void * mem );

/**
   Behaves like realloc(3). Clarifications on the behaviour (because
   the standard has one case of unfortunate wording involving what
   it returns when n==0):

   - If passed (NULL, n>0) then it semantically behaves like
   fsl_malloc(f, n).

   - If 0==n then it semantically behaves like free(2) and returns
   NULL (clarifying the aforementioned wording problem).

   - If passed (non-NULL, n) then it semantically behaves like
   realloc(mem,n).

   - If n is larger than SIZE_MAX, as it can be on 32-bit targets,
   it returns NULL without calling the allocator, leaving mem
   unchanged, as for any failed allocation.

*/
FSL_EXPORT void * fsl_realloc( void * mem, fsl_size_t n );

/**
   A fsl_flush_f() impl which expects _FILE to be-a (FILE*) opened
   for writing, which this function passes the call on to
   fflush(). If fflush() returns 0, so does this function, else it
   returns non-0.
*/
FSL_EXPORT int fsl_flush_f_FILE(void * _FILE);

/**
   A fsl_finalizer_f() impl which requires that mem be-a (FILE*).
   This function passes that FILE to fsl_fclose(). The state
   parameter is ignored.
*/
FSL_EXPORT void fsl_finalizer_f_FILE( void * state, void * mem );

/**
   A fsl_output_f() impl which requires state to be-a (FILE*), which
   this function passes the call on to fwrite(). Returns 0 on
   success. On error it returns the counterpart of fwrite()'s errno
   value, as per fsl_errno_to_rc(), falling back to FSL_RC_IO.
*/
FSL_EXPORT int fsl_output_f_FILE( void * state, void const * src, fsl_size_t n );

/**
   A fsl_output_f() impl which requires state to be-a (fsl_b*),
   which this function passes to fsl_b_append(). Returns 0 on
   success, FSL_RC_OOM (probably) on error.
*/
FSL_EXPORT int fsl_output_f_b( void * state, void const * src, fsl_size_t n );


/**
   A fsl_output_f() impl which requires state to be-a (int*) referring
   to a writable file descriptor, which this function passes to
   write(2). Returns 0 after writing all n bytes. It retries a write
   interrupted by a signal and continues after a partial write. On
   error it returns the counterpart of write()'s errno value, as per
   fsl_errno_to_rc(), falling back to FSL_RC_IO.
*/
FSL_EXPORT int fsl_output_f_fd( void * state, void const * src, fsl_size_t n );

/**
   A fsl_input_f() implementation which requires that state be
   a readable (FILE*) handle. Returns 0 on success, including a short
   read at end of file. On a read error it returns the counterpart of
   fread()'s errno value, as per fsl_errno_to_rc(), falling back to
   FSL_RC_IO; reading a directory, for example, returns FSL_RC_TYPE.
*/
FSL_EXPORT int fsl_input_f_FILE( void * state, void * dest, fsl_size_t * n );

/**
   A fsl_input_f() implementation which requires that state be a
   readable file descriptor, in the form of an ([const] int*).  This
   function will not modify that value.

   Like fsl_input_f_FILE(), it reads all *n bytes unless the input
   ends first, so a short read means the end of the input, as
   fsl_stream() and fsl_b_fill_from() assume. On a pipe or socket it
   therefore blocks until *n bytes arrive or the writer closes its
   end. A read interrupted by a signal is retried.
*/
FSL_EXPORT int fsl_input_f_fd( void * state, void * dest, fsl_size_t * n );

/**
   A fsl_input_f() implementation which requires that state be a
   readable (fsl_b*) handle. The buffer's cursor member is
   updated to track input postion, but that is the only modification
   made by this routine. Thus the user may need to reset the cursor to
   0 if he wishes to start consuming the buffer at its starting point
   (e.g. call fsl_b_rewind()). Subsequent calls to this function
   will increment the cursor by the number of bytes returned via *n.
   The buffer's "used" member is used to determine the logical end of
   input.

   If fsl_b_err() is non-zero for the state argument, that code
   is returned without other side effects.

   Returns 0 on success and has no error conditions except for invalid
   arguments, which result in undefined beavhiour, or fsl_b_err()
   being true for the state argument. Results are undefined if any
   argument is NULL.

   Tip (and warning): sometimes a routine might have a const buffer
   handle which it would like to use in conjunction with this
   routine but cannot without violating constness. Here's a crude
   workaround:

   ```
   fsl_b kludge = fsl_b_empty;
   fsl_b_external(&kludge, theConstBuffer->mem, theConstBuffer->used);
   rc = some_func( fsl_input_f_buffer, &kludge, ... );
   assert( kludge.mem == theConstBuffer->mem );// not reallocated
   assert( 0==kludge.capacity );// b/c it's an external buffer
   ```

   That is legal because this routine modifies only
   fsl_b::cursor. It is not useful as a constness workaround if
   there is ANY CHANCE WHATSOEVER that the buffer's memory will be
   modified. If such tricks are used for APIs which may modify their
   buffer, the "kludge" buffer (above), because it's an "external"
   buffer, will create a new copy of theConstBuffer's memory before
   making any changes, which will lead a leak if that object is not
   cleaned up.

   [Much later:] a cleaner approach is to use fsl_b_external().
*/
FSL_EXPORT int fsl_input_f_buffer( void * state, void * dest, fsl_size_t * n );


/**
   A generic streaming routine which copies data from an
   fsl_input_f() to an fsl_outpuf_f().

   Reads all data from inF() in chunks of an unspecified size and
   passes them on to outF(). It reads until inF() returns fewer bytes
   than requested. Returns the result of the last call to outF() or
   (only if reading fails) inF(). Results are undefined if either of
   the callback function arguments are NULL.  (This function cannot
   know whether a NULL state argument is legal.)

   Here is an example which basically does the same thing as the
   cat(1) command on Unix systems:

   ```
   fsl_stream( fsl_input_f_FILE, stdin, fsl_output_f_FILE, stdout );
   ```

   Or copy a FILE to a buffer:

   ```
   FILE * f = fopen(...);
   fsl_b myBuf = fsl_b_empty;
   rc = fsl_stream( fsl_input_f_FILE, f, fsl_output_f_b, &myBuf );
   // Note that on error myBuf might be partially populated.
   // Eventually clean up the buffer:
   fsl_b_clear(&myBuf);
   ```
*/
FSL_EXPORT int fsl_stream( fsl_input_f inF, void * inState,
                           fsl_output_f outF, void * outState );

/**
   Consumes two input streams looking for differences.  It stops
   reading as soon as either or both streams run out of input or a
   byte-level difference is found.  It consumes input in chunks of
   an unspecified size, and after this returns the input cursor of
   the streams is not well-defined.  i.e. the cursor probably does
   not point to the exact position of the difference because this
   level of abstraction does not allow that unless we read byte by
   byte.

   Returns 0 if both streams emit the same amount of output and
   that ouput is bitwise identical, otherwise it returns non-0.
*/
FSL_EXPORT int fsl_stream_compare( fsl_input_f in1, void * in1State,
                                   fsl_input_f in2, void * in2State );


/**
   A general-purpose buffer class, analog to Fossil's Blob
   class, but it is not called fsl_blob to avoid confusion with
   DB-side blobs. Buffers are used extensively in fossil to do
   everything from reading files to compressing artifacts to
   creating dynamically-formatted strings. Because they are such a
   pervasive low-level type, and have such a simple structure,
   their members (unlike most other structs in this API) may be
   considered public and used directly by client code (as long as
   they do not mangle their state, e.g. by setting this->capacity
   smaller than this->used!).

   General conventions of this class:

   - ALWAYS initialize them by copying fsl_b_empty or
   (depending on the context) fsl_b_empty_m. Failing to
   initialize them properly leads to undefined behaviour.

   - ALWAYS fsl_b_clear() buffers when done with
   them. Remember that failed routines which output to buffers
   might partially populate the buffer, so be sure to clean up in
   error cases.

   - The `capacity` member specifies how much memory the buffer
   currently holds in its `mem` member. If `capacity` is 0 and `mem`
   is not then the memory is expected to refer to `used` bytes of
   memory which are owned elsewhere. See fsl_b_external() and
   fsl_b_materialize() for details.

   - The `used` member specifies how much of the memory is actually
   "in use" by the buffer. The exact meaning of "used" is
   context-dependent but it's typically equivalent to the strlen() of
   the buffer's contents.

   - As a rule, the public APIs keep (`used`<`capacity`) and always
   (unless documented otherwise) tries to keep the memory buffer
   NUL-terminated (if it has any memory at all). The notable
   potential exception to that is that "external" buffers
   may not be NUL-terminated (see fsl_b_external()).

   - Use fsl_b_reuse() to keep memory around and reset the `used`
   amount to 0. Most library-wide routines which write to buffers will
   re-use that memory if they can, rather than re-allocating.

   This example demonstrates the difference between `used` and
   `capacity` (error checking reduced to assert()ions for clarity):

   ```
   fsl_b b = fsl_b_empty;
   // ALWAYS init via copying fsl_b_empty or (depending on
   // the context) fsl_b_empty_m. The latter is used for
   // in-struct initialization of struct members.
   int rc = fsl_b_reserve(&b, 20);
   assert(0==rc);
   assert(b.capacity>=20); // it may reserve more!
   assert(0==b.used);
   rc = fsl_b_append(&b, "abc", 3);
   assert(0==rc);
   assert(3==b.used);
   assert(0==b.mem[b.used]); // API always NUL-terminates
   fsl_b_reuse(&b);
   assert(0==b.used); // Resets the buffer but...
   assert(b.capacity>=20);  // ... keeps the memory.
   fsl_b_clear(&b); // ALWAYS clean up
   ```

   @see fsl_b_reserve()
   @see fsl_b_resize()
   @see fsl_b_external()
   @see fsl_b_materialize()
   @see fsl_b_append()
   @see fsl_b_appendf()
   @see fsl_b_cstr()
   @see fsl_b_size()
   @see fsl_b_capacity()
   @see fsl_b_clear()
   @see fsl_b_reuse()
   @see fsl_b_err()
   @see fsl_b_err_clear()
*/
struct fsl_b {
  /**
     The raw memory pointed to by this buffer. There are two ways of
     using this member:

     - If `this->capacity` is non-0 then the first `this->capacity`
     bytes of `this->mem` are owned by this buffer instance. The API
     docs call this state "managed" buffers.

     - `If this->capacity` is 0 and this->mem is not NULL then the
     memory is owned by "somewhere else" and this API will treat it as
     _immutable_ (so it may safely point to const data). Its lifetime
     must exceed this object's and any attempt made via this API to
     write to it will cause the memory to be copied (effectively a
     copy-on-write op). The API calls this state "external" buffers
     and refers to the copy-on-write of such buffers as
     "materializing" them. See fsl_b_external() and
     fsl_b_materialize() for details.

     `this->used` bytes are treated as the "used" part of the buffer
     (as opposed to its capacity). When `this->capacity>0` the
     difference beween (`this->capacity - this->used`) represents
     space the buffer has available for use before it will require
     another expansion/reallocation.
  */
  unsigned char * mem;
  /**
     Number of bytes allocated for this buffer. If capacity is 0
     and `this->mem` is not NULL then this buffer's memory is assumed
     to be owned "elsewhere" and will be considered immutable by the
     API. Any attempt to modify it will result in a copy-on-write
     operation
  */
  fsl_size_t capacity;

  /**
     Number of "used" bytes in the buffer. This is generally
     interpreted as the string length of this->mem, and the buffer
     APIs which add data to a buffer always ensure that
     this->capacity is large enough to account for a trailing NUL
     byte in this->mem.

     Library routines which manipulate buffers must ensure that
     (this->used<this->capacity) is always true, expanding the buffer
     if necessary. Much of the API assumes that precondition is always
     met, and any violation of it opens the code to undefined
     behaviour (which is okay, just don't ever break that
     precondition). Most APIs ensure that (used<capacity) is always
     true (as opposed to used<=capacity) because they add a trailing
     NUL byte which is not counted in the "used" length.
  */
  fsl_size_t used;
  /**
     Used by some routines to keep a cursor into this->mem. Note that
     a pointer-based cursor is not valid for some uses because mem can
     be reallocated (and thus moved).
  */
  fsl_size_t cursor;

  /**
     When any buffer-related routines encounter an error, they set
     this flag so that the error can be propagated. Many APIs also
     become no-ops when this is set, the intention being to simplify
     many common uses of this class, e.g.:

     ```
     fsl_b_append(b, ... );
     fsl_b_append(b, ... );
     fsl_b_append(b, ... );
     if(fsl_b_err(b)) ...
     ```

     The alternative (without this member) being to check for an OOM
     error after every append operation.
  */
  int errCode;
};

/** Empty-initialized fsl_b instance, intended for const-copy
    initialization. */
#define fsl_b_empty_m \
  {.mem=NULL,.capacity=0U,.used=0U,.cursor=0U,.errCode=0}

/** Empty-initialized fsl_b instance, intended for copy
    initialization. */
FSL_EXPORT const fsl_b fsl_b_empty;

/**
   A container for storing generic error state. It is used to
   propagate error state between layers of the API back to the
   client. i.e. they act as basic exception containers.

   @see fsl_error_set()
   @see fsl_error_get()
   @see fsl_error_propagate()
   @see fsl_error_clear()
*/
struct fsl_error {
  /**
     Error message text is stored in this->msg.mem. The usable text
     part is this->msg.used bytes long.
  */
  fsl_b msg;
  /**
     Error code, generally assumed to be a fsl_rc_e value. The
     "non-error" code is 0.
  */
  int code;
};

/** Empty-initialized fsl_error instance, intended for const-copy
    initialization. */
#define fsl_error_empty_m {.msg = fsl_b_empty_m, .code = 0}

/** Empty-initialized fsl_error instance, intended for copy
    initialization. */
FSL_EXPORT const fsl_error fsl_error_empty;

/**
   If err is not NULL, populates err with the given code and formatted
   string, replacing any existing state. If fmt==NULL then
   fsl_rc_cstr(rc) is used to get the error string.

   If err is NULL this is a no-op and returns code.

   Returns code on success, some other non-0 code on error.

   As a special case, if 0==code then fmt is ignored and the error
   state is cleared. This will not free any memory held by err but
   will re-set its string to start with a NUL byte, ready for
   re-use later on.

   As a special case, if code==FSL_RC_OOM then fmt is ignored
   to avoid a memory allocation (which would presumably fail).

   @see fsl_error_get()
   @see fsl_error_clear()
   @see fsl_error_propagate()
*/
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 );

/**
   Fetches the error state from err. 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
   reference. As a special case, if the error object has no message
   then the returned string is set to NULL, as opposed to an empty
   string.

   If len is not NULL then *len will be assigned to the length of
   the (*str) string (in bytes).

   @see fsl_error_set()
   @see fsl_error_clear()
   @see fsl_error_propagate()
*/
FSL_EXPORT int fsl_error_get( fsl_error const * err,
                              char const ** str, fsl_size_t *  len );

/**
   If err is not NULL, frees up any resources owned by err and sets
   its error code to 0, but does not free err. This is harmless no-op
   if err is NULL or holds no dynamically allocated no memory.

   @see fsl_error_set()
   @see fsl_error_get()
   @see fsl_error_propagate()
   @see fsl_error_reset()
*/
FSL_EXPORT void fsl_error_clear( fsl_error *  err );

/**
   Sets err->code to 0 and resets its buffer, but keeps any err->msg
   memory around for later re-use. This is a no-op if err is NULL.

   @see fsl_error_clear()
*/
FSL_EXPORT void fsl_error_reset( fsl_error *  err );

/**
   Copies the error state from src to dest. If dest contains state, it is
   cleared/recycled by this operation.

   Returns 0 on success, FSL_RC_MISUSE if either argument is NULL
   or if (src==dest), and FSL_RC_OOM if allocation of the message
   string fails.

   As a special case, if src->code==FSL_RC_OOM, then the code is
   copied but the message bytes (if any) are not (under the
   assumption that we have no more memory).
*/
FSL_EXPORT int fsl_error_copy( fsl_error const * src,
                               fsl_error *  dest );

/**
   Swaps the state between two fsl_error objects and then resets the
   error state on the `from` object. Intended as an allocation
   optimization when propagating error state up the API.

   This is a no-op if from==to.

   Because this modifies one argument differently from the other, it's
   not exactly like a swap, but it has the effect of moving an error
   from the `from` object to the `to` object, while keeping `to`'s
   former memory intact for re-use (now inside the `from` object).

   Results are undefined if either parameter is NULL or either is not
   properly initialized. i.e. neither may refer to uninitialized
   memory. Copying fsl_error_empty at declaration-time is a simple way
   to ensure that instances are cleanly initialized.
*/
FSL_EXPORT void fsl_error_propagate( fsl_error *  from, fsl_error *  to );

/** Old name for fsl_error_propagate() */
#define fsl_error_move fsl_error_propagate
///** Old, misleading name for fsl_error_propagate() */
//#define fsl_error_swap fsl_error_propagate

/**
   Returns the given Unix Epoch timestamp value as its approximate
   Julian Day value. Note that the calculation does not account for
   leap seconds.
*/
FSL_EXPORT double fsl_unix_to_julian( fsl_time_t unixEpoch );

/**
   Returns the current Unix Epoch time converted to its approximate
   Julian form. Equivalent to fsl_unix_to_julian(time(0)). See
   fsl_unix_to_julian() for details. Note that the returned time
   has seconds, not milliseconds, precision.
*/
FSL_EXPORT double fsl_julian_now(void);

#if 0
/** UNTESTED, possibly broken vis-a-vis timezone conversion.

    Returns the given Unix Epoch time value formatted as an ISO8601
    string.  Returns NULL on allocation error, else a string 19
    bytes long plus a terminating NUL
    (e.g. "2013-08-19T20:35:49"). The returned memory must
    eventually be freed using fsl_free().
*/
FSL_EXPORT char * fsl_unix_to_iso8601( fsl_time_t j );
#endif

/**
   Returns true if the first 10 digits of z _appear_ to form the start
   of an ISO date string (YYYY-MM-DD). Whether or not the string is
   really a valid date is left for downstream code to
   determine. Returns false in all other cases, including if z is
   NULL.
*/
FSL_EXPORT bool fsl_str_is_date(const char *z);


/**
   Checks if z is syntactically a time-format string in the format:

   [Y]YYYY-MM-DD

   (Yes, the year may be five-digits, left-padded with a zero for
   years less than 9999.)

   Returns a positive value if the YYYYY part has five digits, a
   negative value if it has four. It returns 0 (false) if z does not
   match that pattern.

   If it returns a negative value, the MM part of z starts at byte offset
   (z+5), and a positive value means the MM part starts at (z+6).

   z need not be NUL terminated - this function does not read past
   the first invalid byte. Thus is can be used on, e.g., full
   ISO8601-format strings. If z is NULL, 0 is returned.
*/
FSL_EXPORT int fsl_str_is_date2(const char *z);


/**
   Returns the current error code of the given buffer. Many buffer
   APIs become noops when this function returns non-0.
*/
FSL_EXPORT int fsl_b_err(fsl_b const * b);

/**
   Resets the error code of the given buffer to 0.
*/
FSL_EXPORT void fsl_b_err_clear(fsl_b *  b);

/**
   Reserves at least n bytes of capacity in buf. Returns 0 on
   success, FSL_RC_OOM if allocation fails. Results are undefined
   if !buf.

   If fsl_b_err() is true and n is not 0 then this function
   returns its value without other side effects. If n is 0 then the
   error state is cleared.

   If b is an external buffer then:

   - If n is 0, this disassociates b->mem from b, effectively clearing
     the buffer's state. Else...

   - The buffer is materialized, transformed into a managed buffer.
     This happens even if n is less than b->used because this routine
     is always used in preparation for writing to the buffer.

   - If n>0 then the greater of (n, b->used) bytes of memory are
     allocated, b->used bytes are copied from b->mem (its external
     memory) to the new block, and b->mem is replaced with the new
     block. Afterwards, b->capacity will be non-0.

   This does not change b->used, nor will it shrink the buffer
   (reduce buf->capacity) unless n is 0, in which case it immediately:

   - frees b->mem (if b is a managed buffer)
   - sets b->capacity, buf->used, and b->cursor to 0
   - sets b->errCode to 0

   @see fsl_b_resize()
   @see fsl_b_materialize()
   @see fsl_b_clear()
*/
FSL_EXPORT int fsl_b_reserve( fsl_b *  b, fsl_size_t n );

/**
   If b is a "managed" buffer or b->errCode is non-0 then this is a
   no-op and returns b->errCode, else b is an "external" buffer and
   it...

   - Allocates enough memory to store b->used bytes plus a NUL
     terminator.

   - Copies b->mem to the new block.

   - NUL-terminates the new block.

   - Assigns b->mem to the new block.

   b is thereby transformed to a managed buffer, i.e. b owns b->mem.

   If fsl_b_err() is non-0 before this call, this call is a no-op
   and that value is returned.

   Returns 0 on success, FSL_RC_OOM on allocation error.

   This materialization happens automatically on demand by fsl_b
   APIs which write to the buffer but clients should use this to
   ensure that it is managed memory before they manipulate b->mem
   directly. (Editing b->mem for an external buffer specifically
   results in Undefined Behavior.)

   @see fsl_b_external()
*/
FSL_EXPORT int fsl_b_materialize( fsl_b *  b );

/**
   Initializes b to be an "external" buffer pointing to n bytes of the
   given memory. If n is negative, the equivalent of fsl_strlen() is
   used to count its length. The buffer API treats external buffers as
   immutable. If asked to write to one, the API will first
   "materialize" the buffer, as documented for
   fsl_b_materialize().

   Either mem must be guaranteed to outlive b or b must be
   materialized before mem goes out of scope.

   ACHTUNG: it is NEVER legal to pass a pointer which may get
   reallocated, as doing so may change its address, invaliding the
   resulting `b->mem` pointer. Similarly, it is never legal to pass it
   scope-local memory unless b's lifetime is limited to that scope.

   If b->mem is not NULL, this function first passes the buffer to
   fsl_b_clear() to ensure that this routine does not leak any
   dynamic memory it may already own.

   Results are undefined if mem is NULL, but n may be 0.

   Results are undefined if passed a completely uninitialized buffer
   object. _Always_ initialize new buffer objects by copying
   fsl_b_empty or (when appropriate) fsl_b_empty_m.

   This function resets b->errCode.

   @see fsl_b_materialize()
*/
FSL_EXPORT void fsl_b_external( fsl_b *  b, void const * mem, fsl_int_t n );

/**
   Convenience equivalent of fsl_b_reserve(b,0).
*/
FSL_EXPORT void fsl_b_clear( fsl_b *  b );

/**
   If b is a managed buffer, this resets b->used, b->cursor, and
   b->mem[0] (if b->mem is not NULL) to 0. If b is an external buffer,
   this clears all state from the buffer, behaving like
   fsl_b_clear() (making it available for reuse as a managed or
   external buffer).

   This does not (de)allocate memory, only changes the logical "used"
   size of the buffer. Returns its argument.

   This function resets b->errCode.

   Returns b.

   Achtung for fossil(1) porters: this function's semantics are much
   different from the fossil's blob_reset(). To get those semantics,
   use fsl_b_reserve(buf, 0) or its convenience form
   fsl_b_clear(). (This function _used_ to be called
   fsl_b_reset(), but it was renamed in the hope of avoiding
   related confusion.)
*/
FSL_EXPORT fsl_b * fsl_b_reuse( fsl_b *  b );

/**
   Similar to fsl_b_reserve() except that...

   - If fsl_b_err() is true, that result is returned with no other
     side effects.

   For managed buffers:

   - It does not free all memory when n==0. Instead it essentially
     makes the memory a length-0, NUL-terminated string.

   - It will try to shrink (realloc) buf's memory if (n<buf->capacity).

   - It sets buf->capacity to (n+1) and buf->used to n. This routine
     allocates one extra byte to ensure that buf is always
     NUL-terminated.

   - On success it always NUL-terminates the buffer at
   offset buf->used.

   For external buffers it behaves slightly differently:

   - If n==buf->used, this is a no-op and returns 0.

   - If n==0 then it behaves like fsl_b_external(buf,"",0)
     and returns 0.

   - Else it materializes the buffer, as per fsl_b_materialize(),
     copies the lesser of (n, buf->used) bytes from buf->mem to that
     memory, NUL-terminates the new block, replaces buf->mem with the
     new block, sets buf->used to n and buf->capacity to n+1.

   Returns 0 on success or FSL_RC_OOM if a (re)allocation fails. On
   allocation error, the buffer's memory state is unchanged.

   @see fsl_b_reserve()
   @see fsl_b_materialize()
   @see fsl_b_clear()
*/
FSL_EXPORT int fsl_b_resize( fsl_b *  buf, fsl_size_t n );

/**
   Swaps the entire state of the left and right arguments. Results are
   undefined if either argument is NULL or points to uninitialized
   memory.
*/
FSL_EXPORT void fsl_b_swap( fsl_b *  left, fsl_b *  right );

/**
   Similar fsl_b_swap() but it also optionally frees one of
   the buffer's memories after swapping them. If clearWhich is
   negative then the left buffer (1st arg) is cleared _after_
   swapping (i.e., the NEW left hand side gets cleared). If
   clearWhich is greater than 0 then the right buffer (2nd arg) is
   cleared _after_ swapping (i.e. the NEW right hand side gets
   cleared). If clearWhich is 0, this function behaves identically
   to fsl_b_swap().

   A couple examples should clear this up:

   ```
   fsl_b_swap_free( &b1, &b2, -1 );
   ```

   Swaps the contents of b1 and b2, then frees the contents
   of the left-side buffer (b1).

   ```
   fsl_b_swap_free( &b1, &b2, 1 );
   ```

   Swaps the contents of b1 and b2, then frees the contents
   of the right-side buffer (b2).
*/
FSL_EXPORT void fsl_b_swap_free( fsl_b *  left,
                                      fsl_b *  right,
                                      int clearWhich );

/**
   Appends the first n bytes of src, plus a NUL byte, to b,
   expanding b as necessary and incrementing b->used by n. If n is
   less than 0 then the equivalent of fsl_strlen((char const*)src)
   is used to calculate the length.

   If fsl_b_err() is true, its result is returned without further
   side effects.

   If b is an external buffer, it is first transformed into a
   managed buffer.

   Results are undefined if b or src are NULL.

   If n is 0 (or negative and !*src), this function ensures that
   b->mem is not NULL and is NUL-terminated, so it may allocate
   to have space for that NUL byte.

   Returns 0 on success, FSL_RC_OOM if allocation of memory fails.

   If this function succeeds, it guarantees that it NUL-terminates the
   buffer (but that the NUL terminator is not counted in b->used).

   This function does not modify b's cursor.

   @see fsl_b_appendf()
   @see fsl_b_reserve()
*/
FSL_EXPORT int fsl_b_append( fsl_b * b, void const * src, fsl_int_t n );

/**
   Convenience form of fsl_b_append() which requires a literal
   C-string and appends it all to (fsl_b*) B.
*/
#define fsl_b_append_literal(B,LITERAL) \
  fsl_b_append(B, "" LITERAL, sizeof(LITERAL)-1)

/**
   Uses fsl_appendf() to append formatted output to the given buffer.
   Returns 0 on success, FSL_RC_OOM if an allocation fails while
   expanding dest, or the non-0 code fsl_appendf() returns, such as
   FSL_RC_RANGE for a string length it cannot format. Results are
   undefined if either of the first two arguments are NULL.

   If fsl_b_err() is true, its result is returned without further
   side effects.

   @see fsl_b_append()
   @see fsl_b_reserve()
*/
FSL_EXPORT int fsl_b_appendf( fsl_b *  dest,
                                   char const * fmt, ... );

/** va_list counterpart to fsl_b_appendf(). */
FSL_EXPORT int fsl_b_appendfv( fsl_b *  dest,
                                    char const * fmt, va_list args );

/**
   Appends the given byte to b. This is slightly more efficient than
   fsl_b_append() for the common case where b has slack memory to
   fill.

   If b->errCode is non-0, this is a no-op and returns that code.

   On success this routine always NUL-terminates b. On error,
   b->errCode is returned.
*/
FSL_EXPORT int fsl_b_appendch(fsl_b *  b, char c);

/**
   Add an EOL to b if it has content (i.e. b->used is not 0) but does
   not end on one, else do nothing. It does not modify empty buffers.
   b is materialized if needed.

   Returns b->errCode and is a no-op if b->errCode is non-0 when this
   is called.
*/
FSL_EXPORT int fsl_b_ensure_eol(fsl_b *  b);

/**
   If b ends with a `\n` character or a pair of `\r\n`, the `\n` or
   `\r\n` pair are "chomped" (to use Perl's term for it), reducing
   b->used by 1 or 2, else this function has no side-effects.

   For external buffers, the b->used is adjusted but the memory is
   otherwise not modified (as external buffers are never guaranteed to
   be NUL-terminated). For non-external buffers b is NUL-terminated at
   its new length. If you really need to chomp an external buffer,
   pass it to fsl_b_materialize() first.

   This is a no-op if b->errCode is non-0. (We don't strictly need to
   do so, but we do for consistency - b's state should not change when
   errCode is non-0.)
*/
FSL_EXPORT void fsl_b_chomp(fsl_b *  b);

/**
   Expects z to be a single argument intended for future call to
   system()-like function. It is quoted/escaped appropriately and
   appended to b, adding a space between any previous contents of
   b. It will fail, returning FSL_RC_SYNTAX, if the input contains
   what it believes to be malicious characters or if z contains any
   non-UTF-8 characters. It does not permit control characters of any
   kind, for example.

   If isFilename is true and z starts with a '-' character then the
   result gets prefixed with `./` (or `.\` on Windows) to (A)
   differentiate it from a flag argument and (B) avoid passing an
   unintended, but valid, flag to a command. isFilename has no further
   effect.

   The intent is that this function be called once per argument for a
   pending system()-style call, and b's contents eventually be used as
   the argument for that system()-style call.

   If b->errCode is non-0 when this is called, this function is a no-op
   and that value is returned.

   If err is not NULL then any validation-time error state are set in
   err and err->code is returned, It may fail for a number of reasons,
   as it performs checks on the input to avoid certain types of
   malicious uses. If initial validation of b->errCode and
   materialization of b (if needed) both pass, err is passed to
   fsl_error_reset() before this function starts its work.

   If err is NULL then this function still returns non-0 on error but
   the caller will not know exactl which validation failed.

   If this function returns FSL_RC_SYNTAX and err is not NULL, err
   will contain more info about the problem. If it returns any other
   error code, it's an allocation error and err will not have been
   updated.

   On error it always updates b->errCode so that subsequent calls
   will not mask the error.
*/
FSL_EXPORT int fsl_b_esc_arg_v2(fsl_b *  b,
                                     fsl_error *  err,
                                     char const *z,
                                     bool isFilename);
/**
   Equivalent to fsl_b_esc_arg_v2() with NULL as its second
   argument.
*/

FSL_EXPORT int fsl_b_esc_arg(fsl_b *  b,
                                  char const *z,
                                  bool isFilename);

/**
   Hex-encodes n bytes of src into n*2 hex-digit bytes appended to
   b. On error, b->errCode will be set to non-0 and that value is
   returned. If the final argument is true, upper-case hex digits are
   used, else lower-case are used.

   If fsl_b_err() is non-0 when this is called, this function has
   no side effects and that value is returned.
*/
FSL_EXPORT int fsl_b_append_hex( fsl_b *  b,
                                      void const * src, fsl_uint_t n,
                                      bool upperCase);


/**
   Compresses the first pIn->used bytes of pIn to pOut. It is ok for
   pIn and pOut to be the same blob.

   If fsl_b_err() is true for pIn buffer, its result is
   returned without further side effects. pOut's error state is ignored
   because it will be replaced.

   pOut must either be the same as pIn or else a properly
   initialized buffer. Any prior contents will be freed or their
   memory reused.

   Results are undefined if either argument is NULL.

   If is pIn!=pOut and pOut has enough memory to hold the compressed
   result then that memory is reused, but on error then pOut->errCode
   may (depending on the source of the error) be non-0 and the
   contents of pOut->mem are effectively undefined.

   Returns 0 on success, FSL_RC_OOM on allocation error (including
   one inside zlib), FSL_RC_RANGE if pIn->used is FSL_BLOB_MAX_SIZE
   or more, a size which fsl_b_uncompress() does not recognise as
   compressed, and FSL_RC_ERROR if the lower-level compression
   routines fail.

   Use fsl_b_uncompress() to uncompress the data. The data are
   encoded with a big-endian, unsigned 32-bit length as the first four
   bytes (holding its uncomressed size), and then the data as
   compressed by zlib.

   @see fsl_b_compress2()
   @see fsl_b_uncompress()
   @see fsl_b_is_compressed()
*/
FSL_EXPORT int fsl_b_compress(fsl_b const *pIn, fsl_b * pOut);

/**
   Compress the concatenation of a blobs pIn1 and pIn2 into pOut.

   pOut must be either empty (cleanly initialized or newly
   recycled) or must be the same as either pIn1 or pIn2.

   Results are undefined if any argument is NULL.

   If fsl_b_err() is true for any buffer, its result is
   returned without further side effects. The buffers are checked in
   the order of their parameter declaration.

   Returns 0 on success, FSL_RC_OOM on allocation error (including
   one inside zlib), FSL_RC_RANGE if the combined size is
   FSL_BLOB_MAX_SIZE or more, as for fsl_b_compress(), and
   FSL_RC_ERROR if the lower-level compression routines fail.

   TODO: if pOut!=(pIn1 or pIn2) then re-use its memory, if it has any.

   @see fsl_b_compress()
   @see fsl_b_uncompress()
   @see fsl_b_is_compressed()
*/
FSL_EXPORT int fsl_b_compress2(fsl_b const *pIn1,
                                    fsl_b const *pIn2,
                                    fsl_b *  pOut);

/**
   Uncompress buffer pIn and store the result in pOut. It is ok for
   pIn and pOut to be the same buffer. Returns 0 on success. If
   pIn!=pOut then on error, depending on the type of error, pOut may
   have been partially written so the state of its contents are
   unspecified (but its state as a buffer object is still valid).

   If fsl_b_err() is true for either buffer, its result is
   returned without further side effects. The buffers are checked in
   the order of their parameter declaration.

   pOut must be either cleanly initialized/empty or the same object as
   pIn. If it has any current memory, it will be reused if it's
   large enough and it is not the same pointer as pIn.

   Results are undefined if any argument is NULL.

   Returns 0 on success, FSL_RC_OOM on allocation error (including
   one inside zlib), FSL_RC_CONSISTENCY if pIn's zlib stream is
   corrupt, truncated, or decodes to more bytes than its 4-byte size
   prefix records, and FSL_RC_ERROR for any other failure of the
   lower-level decompression routines. On error, pOut->errCode is
   updated.

   Note that the decompression process, though computationally costly,
   is a no-op if pIn is not actually compressed.

   As a special case, if pIn==pOut and fsl_b_is_compressed() returns
   false for pIn then this is a no-op.

   @see fsl_b_compress()
   @see fsl_b_compress2()
   @see fsl_b_is_compressed()
*/
FSL_EXPORT int fsl_b_uncompress(fsl_b const * pIn,
                                     fsl_b *  pOut);

/**
   Returns true if this function believes that mem (which must be
   at least len bytes of valid memory long) appears to have been
   compressed by fsl_b_compress() or equivalent. This is not a
   100% reliable check - it could potentially have false positives
   on certain inputs, but that is thought to be unlikely (at least
   for text data).

   Returns 0 if mem is NULL.

   As of 2026-10-15, it is this developer's hope to eliminate all use
   of this in the library. A single false-positive is all it takes to
   break a repo rebuild.
*/
FSL_EXPORT bool fsl_data_is_compressed(unsigned char const * mem, fsl_size_t len);

/**
   Equivalent to fsl_data_is_compressed(buf->mem, buf->used).
*/
FSL_EXPORT bool fsl_b_is_compressed(fsl_b const * buf);

/**
   If fsl_data_is_compressed(mem,len) returns true then this function
   returns the uncompressed size of the data, else it returns a negative
   value.
*/
FSL_EXPORT fsl_int_t fsl_data_uncompressed_size(unsigned char const *mem, fsl_size_t len);

/**
   The fsl_b counterpart of fsl_data_uncompressed_size().
*/
FSL_EXPORT fsl_int_t fsl_b_uncompressed_size(fsl_b const * b);

/**
   Equivalent to ((char const *)b->mem) except that if b->errCode is
   non-0, this returns NULL. The returned string is effectively
   b->used bytes long unless the user decides to apply his own
   conventions. Note that the buffer APIs generally assure that
   buffers are NUL-terminated, meaning that strings returned from this
   function can (for the vast majority of cases) assume that the
   returned string is NUL-terminated (with a string length of b->used
   _bytes_). It is, however, possible for client code to violate that
   convention via direct manipulation of the buffer or using
   non-NUL-terminated extranal buffers.

   Results are undefined if b is NULL.

   @see fsl_b_str()
   @see fsl_b_cstr2()
*/
FSL_EXPORT char const * fsl_b_cstr(fsl_b const * b);

/**
   If b has any memory allocated to it and b->errCode is non-0, that
   memory is returned. If len is not NULL then *len is set to
   b->used. If b has no memory or b->errCode is non-0 then NULL is
   returned and *len (if len is not NULL) is set to 0.

   Results are undefined if b is NULL.

   @see fsl_b_str()
   @see fsl_b_cstr()
*/
FSL_EXPORT char const * fsl_b_cstr2(fsl_b const * b, fsl_size_t *  len);

/**
   Equivalent to ((char *)b->mem) except that if b->errCode is non-0
   then NULL is returned. The returned memory is effectively b->used
   bytes long unless the user decides to apply their own conventions.

   Care must be taken to only write to the returned pointer for memory
   owned or write-proxied by this buffer. More specifically, results
   are undefined if b is an external buffer proxying const bytes. When
   in doubt about whether b is external, use fsl_b_materialize()
   to transform it to a managed buffer before using this routine,
   noting that any of the public fsl_b APIs which write to a
   buffer will materialize it on demand if needed.

   @see fsl_b_take()
*/
FSL_EXPORT char * fsl_b_str(fsl_b const * b);

/**
   "Takes" the memory refered to by the given buffer, transfering
   ownership to the caller. After calling this, b's state will be
   empty. If b is an external buffer, this will materialize it
   first and return NULL if that fails.

   @see fsl_b_materialize()
   @see fsl_b_str()
   @see fsl_b_cstr()
   @see fsl_b_cstr2()
*/
FSL_EXPORT char * fsl_b_take(fsl_b *  b);

/**
   Returns the "used" size of b, or 0 if !b.
*/
#define fsl_b_size(b) (b)->used
#if 0
FSL_EXPORT fsl_size_t fsl_b_size(fsl_b const * b);
#endif

/**
   Returns the current capacity of b, or 0 if !b.
*/
#define fsl_b_capacity(b) (b)->capacity
#if 0
FSL_EXPORT fsl_size_t fsl_b_capacity(fsl_b const * b);
#endif
/**
   Compares the contents of buffers lhs and rhs using memcmp(3)
   semantics. Returns negative, zero, or positive if the first buffer
   is less then, equal to, or greater than the second.  Results are
   undefined if either argument is NULL.

   When buffers of different length match on the first N bytes,
   where N is the shorter of the two buffers' lengths, it treats the
   shorter buffer as being "less than" the longer one.
*/
FSL_EXPORT int fsl_b_compare(fsl_b const * lhs,
                                  fsl_b const * rhs);

/**
   Compares b and the first nStr bytes of the given string. If nStr is
   negative, fsl_strlen() is used to calculate it. Returns true if the
   buffer and the string match, as per the rules of
   fsl_b_compare(), else returns false.
*/
FSL_EXPORT bool fsl_b_eq(fsl_b const * b, char const * str,
                              fsl_int_t nStr);

/**
   Bitwise-compares the contents of b against the file named by
   zFile.  Returns 0 if they have the same size and contents, else
   non-zero.  This function has no way to report if zFile cannot be
   opened, and any error results in a non-0 return value. No
   interpretation/canonicalization of zFile is performed - it is
   used as-is.

   This resolves symlinks and returns non-0 if zFile refers (after
   symlink resolution) to a non-file.

   If zFile does not exist, is not readable, or has a different
   size than b->used, non-0 is returned without opening/reading the
   file contents. If a content comparison is performed, it is
   streamed in chunks of an unspecified (but relatively small)
   size, so it does not need to read the whole file into memory
   (unless it is smaller than the chunk size).
*/
FSL_EXPORT int fsl_b_compare_file( fsl_b const * b, char const * zFile );

/**
   Compare two buffers in constant (a.k.a. O(1)) time and return
   zero if they are equal.  Constant time comparison only applies
   for buffers of the same length.  If lengths are different,
   immediately returns 1. This operation is provided for cases
   where the timing/duration of fsl_b_compare() (or an
   equivalent memcmp()) might inadvertently leak security-relevant
   information.  Specifically, it address the concern that
   attackers can use timing differences to check for password
   misses, to narrow down an attack to passwords of a specific
   length or content properties.
*/
FSL_EXPORT int fsl_b_compare_O1(fsl_b const * lhs, fsl_b const * rhs);

/**
   Overwrites dest's contents with a copy of those from src
   (reusing dest's memory if it has any). Results are undefined if
   either pointer is NULL or invalid. Returns 0 on success,
   FSL_RC_OOM on allocation error.
*/
FSL_EXPORT int fsl_b_copy( fsl_b *  dest,
                                fsl_b const * src );

/**
   Apply the delta in pDelta to the original content pOriginal to
   generate the target content pTarget. All three pointers must point
   to properly initialized memory.

   If pTarget==pOriginal then this is a destructive operation,
   replacing the original's content with its new form.

   If fsl_b_err() is true for any buffer, its result is
   returned without further side effects. The buffers are checked in
   the order of their parameter declaration.

   Return 0 on success, FSL_RC_OOM on allocation error, or one of the
   codes fsl_delta_applied_size() and fsl_delta_apply() return for a
   malformed delta or one which does not belong to pOriginal, such
   as FSL_RC_DELTA_INVALID_TERMINATOR or FSL_RC_CHECKSUM_MISMATCH.
   Use fsl_b_delta_apply2() to get a description of a delta error.

   @see fsl_b_delta_apply()
   @see fsl_delta_apply()
   @see fsl_delta_apply2()
*/
FSL_EXPORT int fsl_b_delta_apply( fsl_b const * pOriginal,
                                       fsl_b const * pDelta,
                                       fsl_b *  pTarget);

/**
   Identical to fsl_b_delta_apply() except that if delta
   application fails then any error messages/codes are written to
   pErr if it is not NULL. It is rare that delta application fails
   (only if the inputs are invalid, e.g. do not belong together or
   are corrupt), but when it does, having error information can be
   useful.

   If fsl_b_err() is true for any buffer, its result is
   returned without further side effects. The buffers are checked in
   the order of their parameter declaration.

   @see fsl_b_delta_apply()
   @see fsl_delta_apply()
   @see fsl_delta_apply2()
*/
FSL_EXPORT int fsl_b_delta_apply2( fsl_b const * pOriginal,
                                        fsl_b const * pDelta,
                                        fsl_b *  pTarget,
                                        fsl_error *  pErr);


/**
   Uses a fsl_input_f() function to buffer input into a fsl_b.

   dest must be a non-NULL, initialized (though possibly empty)
   fsl_b object. Its contents, if any, will be overwritten by
   this function, and any memory it holds might be re-used.

   If fsl_b_err() is true then this function returns its value
   without other side effects.

   The src function is called, and passed the state parameter, to
   fetch the input. If it returns non-0, this function returns that
   error code. src() is called, possibly repeatedly, until it
   reports that there is no more data.

   Whether or not this function succeeds, dest still owns any memory
   pointed to by dest->mem, and the client must eventually free it
   by calling fsl_b_reserve(dest,0).

   dest->mem might (and possibly will) be (re)allocated by this
   function, so any pointers to it held from before this call might
   be invalidated by this call.

   On error non-0 is returned and dest may be partially populated.

   Errors include:

   - Allocation error (FSL_RC_OOM), in which case dest->errCode is
     updated.

   - src() returns an error code, in which case dest->errCode is _not_
     modified.

   - The total input size overflows fsl_size_t (FSL_RC_RANGE), in
     which case dest->errCode is _not_ modified.

   Whether or not the state parameter may be NULL depends on the src
   implementation requirements.

   On success dest will contain the contents read from the input
   source. dest->used will be the length of the read-in data, and
   dest->mem will point to the memory. dest->mem is automatically
   NUL-terminated if this function succeeds, but dest->used does not
   count that terminator. On error the state of dest->mem must be
   considered incomplete, and is not guaranteed to be NUL-terminated.

   Example usage:

   ```
   fsl_b buf = fsl_b_empty;
   int rc = fsl_b_fill_from( &buf,
     fsl_input_f_FILE,
      stdin );
   if( rc ){
   fprintf(stderr,"Error %d (%s) while filling buffer.\n",
   rc, fsl_rc_cstr(rc));
   fsl_b_reserve( &buf, 0 );
     return ...;
   }
   ... use the buf->mem ...
   ... clean up the buffer ...
   fsl_b_reserve( &buf, 0 );
   ```

   To take over ownership of the buffer's memory, do:

   ```
   void * mem = buf.mem;
   buf = fsl_b_empty;
   ```

   In which case the memory must eventually be passed to fsl_free()
   to free it.
*/
FSL_EXPORT int fsl_b_fill_from( fsl_b *  dest,
                                fsl_input_f src, void *  state );

/**
   A fsl_b_fill_from() proxy which overwrite's dest->mem with
   the contents of the given FILE handler (which must be opened for
   read access).  Returns 0 on success, after which dest->mem
   contains dest->used bytes of content from the input source. On
   error dest may be partially filled.
*/
FSL_EXPORT int fsl_b_fill_from_FILE( fsl_b *  dest,
                                     FILE *  src );

/**
   A wrapper for fsl_b_fill_from_FILE() which gets its input
   from the given file name.

   If fsl_b_err() is true then this function returns its value
   without other side effects.

   It uses fsl_fopen() to open the file, so it supports the name '-'
   as an alias for stdin.

   Returns 0 on success and FSL_RC_OOM on allocation error. If the
   file cannot be opened it returns fsl_errno_to_rc() of the
   resulting errno, with FSL_RC_IO as the default, so a missing file
   gives FSL_RC_NOT_FOUND and a permissions failure FSL_RC_ACCESS. A
   read error, including reading a directory, gives FSL_RC_IO. This
   function has no error object, so callers which report the failure
   must name the file themselves.
*/
FSL_EXPORT int fsl_b_fill_from_filename( fsl_b *  dest,
                                         char const * filename );

/**
   Writes the given buffer to the given filename. Returns 0 on success,
   FSL_RC_MISUSE if !b or !fname. If opening, writing, flushing, or
   closing the file fails, it returns fsl_errno_to_rc() of the resulting errno,
   with FSL_RC_IO as the default (so a missing directory gives
   FSL_RC_NOT_FOUND, a permissions failure FSL_RC_ACCESS, and a full
   disk FSL_RC_IO). This function has no error object, so callers
   which report the failure must name the file themselves.

   If fsl_b_err() is true, that result is returned with no other
   side effects.

   Uses fsl_fopen() to open the file, so it supports the name '-'
   as an alias for stdout.
*/
FSL_EXPORT int fsl_b_to_filename( fsl_b const * b,
                                  char const * fname );

/**
   Copy N lines of text from pFrom into pTo. The copy begins at the
   current pFrom->cursor position. On success, pFrom->cursor is left
   pointing at the first character past the last `\n` copied.
   (Modification of the cursor is why pFrom is not const.) The copy is
   made in a single go, not line-by-line.

   If fsl_b_err() is true for either buffer (checked in parameter
   order), that result is returned with no other side effects.

   If pTo==NULL then this routine simply skips over N lines.

   Returns 0 if it copies lines or does nothing (because N is 0 or
   pFrom's contents have been exhausted). Copying fewer lines than
   requested (because of EOF) is not an error. Returns non-0 only on
   allocation error. Results are undefined if pFrom is NULL or not
   properly initialized. Whether or not it copies anything can be
   checked by copying pTo->used before calling this and comparing
   pTo->used to that value afterwards. The difference is the number of
   bytes added.

   @see fsl_b_stream_lines()
*/
FSL_EXPORT int fsl_b_copy_lines(fsl_b *  pTo,
                                     fsl_b *  pFrom,
                                     fsl_size_t N);

/**
   Works identically to fsl_b_copy_lines() except that it sends
   its output to the fTo output function. If fTo is NULL then it
   simply skips over N lines. The callback is called a single time,
   not once per line.

   If fsl_b_err() is true, that result is returned with no other
   side effects.

   @see fsl_b_copy_lines()
*/
FSL_EXPORT int fsl_b_stream_lines(fsl_output_f fTo, void *  toState,
                                       fsl_b *  pFrom,
                                       fsl_size_t N);


/**
   Works like fsl_appendfv(), but appends all output to a
   dynamically-allocated string, expanding the string as necessary
   to collect all formatted data. The returned NUL-terminated string
   is owned by the caller and it must be cleaned up using
   fsl_free(...). If !fmt, NULL is returned. It is conceivable that
   it returns NULL on a zero-length formatted string, e.g.  (%.*s)
   with (0,"...") as arguments, but it will only do that if the
   whole format string resolves to empty.

   It also returns NULL on any error fsl_appendfv() reports, which
   is FSL_RC_OOM in practice but is FSL_RC_RANGE for an unsupported
   conversion character or an over-long argument. The result code
   is not available to the caller; use fsl_b_appendf() where it
   matters.
*/
FSL_EXPORT char * fsl_mprintf( char const * fmt, ... );

/**
   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. Returns 0 on success, non-0
   on error. Returns 0 without side-effects if !n. If !*fmt it sets
   dest to an empty string and returns 0. Returns FSL_RC_MISUSE if
   !dest or !fmt, else a formatting error as documented for
   fsl_appendfv(). Truncating the output to n bytes is not an
   error.

   If the destination buffer is long enough, this function
   NUL-terminates it.
*/
FSL_EXPORT int fsl_snprintf( char * dest, fsl_size_t n, char const * fmt, ... );

/**
   va_list counterpart to fsl_snprintf()
*/
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 );

/**
   Similar to strndup(3) but returns NULL if !src.  The returned
   memory must eventually be passed to fsl_free(). Returns NULL on
   allocation error. If len is less than 0 and src is not NULL then
   fsl_strlen() is used to calculate its length.

   If src is not NULL but len is 0 then it will return an empty
   (length-0) string, as opposed to NULL.
*/
FSL_EXPORT char * fsl_strndup( char const * src, fsl_int_t len );

/**
   Equivalent to strlen(3) but returns 0 if src is NULL.  It counts
   bytes, not UTF characters.
*/
FSL_EXPORT fsl_size_t fsl_strlen( char const * src );

/**
   Convenience helper for use with fsl_strlen_t-type string semantics.
*/
static inline fsl_size_t fsl_nstrlen(char const * z, fsl_strlen_t n){
  return n<0 ? fsl_strlen(z) : (fsl_size_t)n;
}

/**
   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_strlen_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 );

/**
   Equivalent to fsl_strcmp(), but with a signature suitable
   for use as a generic comparison function (e.g. for use with
   qsort() and search algorithms).
*/
FSL_EXPORT int fsl_strcmp_cmp( void const * lhs, void const * rhs );

/**
   Case-insensitive form of fsl_strcmp().

   @implements fsl_generic_cmp_f()
*/
FSL_EXPORT int fsl_stricmp(const char *zA, const char *zB);

/**
   Equivalent to fsl_stricmp(), but with a signature suitable
   for use as a generic comparison function (e.g. for use with
   qsort() and search algorithms).

   @implements fsl_generic_cmp_f()
*/
FSL_EXPORT int fsl_stricmp_cmp( void const * lhs, void const * rhs );

/**
   fsl_strcmp() variant which compares at most nByte bytes of the
   given strings, case-insensitively.  If nByte is less than 0 then
   fsl_strlen(zB) is used to obtain the length for comparision
   purposes.
*/
FSL_EXPORT int fsl_strnicmp(const char *zA, const char *zB, fsl_int_t nByte);

/**
   fsl_strcmp() variant which compares at most nByte bytes of the
   given strings, case-sensitively. Returns 0 if nByte is 0.
*/
FSL_EXPORT int fsl_strncmp(const char *zA, const char *zB, fsl_size_t nByte);

/**
   BSD strlcpy() variant which is less error prone than strncpy. Copy up to
   dstsz - 1 characters from src to dst and NUL-terminate the resulting string
   if dstsz is not 0.

   Returns the length of the string it writes to dst. If it returns a value
   equal to or greater than its 3rd argument then the output was truncated.
*/
FSL_EXPORT fsl_size_t fsl_strlcpy(char *dst, const char *src, fsl_size_t dstsz);

/**
   BSD strlcat() variant which is less error prone than strncat. Append src to
   the end of dst. Append at most dstsz - strlen(dst - 1) characters, and
   NUL-terminate unless dstsize is 0 or the passed in dst string was longer
   than dstsz to begin with.

   Returns the initial string-length of dest plus the length src. If
   it returns a value equal to or greater than its 3rd argument then
   the output was truncated.
*/
FSL_EXPORT fsl_size_t fsl_strlcat(char *dst, const char *src, fsl_size_t dstsz);

/**
   Equivalent to fsl_strncmp(lhs, rhs, X), where X is either
   FSL_STRLEN_SHA1 or FSL_STRLEN_K256: if both lhs and rhs are
   longer than FSL_STRLEN_SHA1 then they are assumed to be
   FSL_STRLEN_K256 bytes long and are compared as such, else they
   are assumed to be FSL_STRLEN_SHA1 bytes long and compared as
   such.

   Potential FIXME/TODO: if their lengths differ, i.e. one is v1 and
   one is v2, compare them up to their common length then, if they
   still compare equivalent, treat the shorter one as less-than the
   longer.
*/
FSL_EXPORT int fsl_uuidcmp( fsl_uuid_cstr lhs, fsl_uuid_cstr rhs );

/**
   Returns false if s is NULL or starts with any of (0 (NUL), '0'
   (ASCII character zero), 'f', 'n', "off"), case-insensitively,
   else it returns true.
*/
FSL_EXPORT bool fsl_str_bool( char const * s );

/**
   _Almost_ equivalent to fopen(3) but:

   - 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 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_fclose() (as opposed to fclose()) to
   close these handles, as it has logic to skip closing the
   standard streams.

   Potential TODOs:

   - extend mode string to support 'x', meaning "exclusive", analog
   to open(2)'s O_EXCL flag. Barring race conditions, we have
   enough infrastructure to implement that. (It turns out that
   glibc's fopen() supports an 'x' with exactly this meaning.)

   - extend mode to support a 't', meaning "temporary". The idea
   would be that we delete the file from the FS right after
   opening, except that Windows can't do that.
*/
FSL_EXPORT FILE * fsl_fopen(char const * name, char const *mode);

/**
   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);

/**
   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_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:

   ACHTUNG: this interface changed significantly in 2021-09:

   - The output function was changed from a type specific to this
   interface to fsl_output_f().

   - The return semantics where changed from printf()-like to
   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:

   `%s` works like conventional printf `%s` except that any precision
   value can be modified via the '#' flag to count 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 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
   (B) converts certain characters (namely '<' and '&') to their HTML
   escaped equivalents.

   `%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 code
   originally derived from that one some years ago!). It is still to
   be determined whether we "really need" that behaviour (we don't
   really need either one, seeing as the library is not CGI-centric
   like fossil(1) is).

   `%r` requires an int and renders it in "ordinal form". That is,
   the number 1 converts to "1st" and 398 converts to "398th".

   `%q` quotes a string as required for SQL. That is, '\''
   characters get doubled. It does NOT included the outer quotes
   and NULL values get replaced by the string "(NULL)" (without
   quotes). See `%Q`...

   `%Q` works like `%q`, but includes the outer '\'' characters and
   NULL pointers get output as the string literal "NULL" (without
   quotes), i.e. an SQL NULL. If modified with `%!Q` then it instead
   uses double quotes, the intent being for use with identifiers.
   In that form it still emits `NULL` without quotes, but it is not
   intended to be used with `NULL` values.

   `%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 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_b
   const*) argument. It does not support the '#' flag.

   `%B`: works like `%Q` but takes its input from a (fsl_b
   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. 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).

   `%R`: requires an integer argument and renders it like fsl_rc_cstr()
   would. If that function result is NULL then "#n" is used, where n
   is the integer argument.

   Some of these extensions may be disabled by setting certain macros
   when compiling appendf.c (see that file for details).

   Returns 0 on success. On error it stops, having emitted any output
   up to that point, and returns:

   - FSL_RC_RANGE if fmt contains a conversion character this
     function does not support, or if a string or buffer argument is
     longer than INT_MAX bytes.

   - FSL_RC_OOM if `%F` or a long `%/` argument cannot allocate its
     working memory.

   - FSL_RC_MISUSE if a `%F` argument is NULL.

   - The first non-0 value returned by pfAppend(), unchanged.

   This function has no error object, so it sets no error message.

   Potential TODO: add fsl_bytes_fossilize_out() which works like
   fsl_bytes_fossilize() but sends its output to an fsl_output_f(), so
   that this routine doesn't need to alloc for that case.
*/
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 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
  ;

/**
   Works like fsl_appendf() except that it sends the first n bytes of
   str as-is to pfAppend(). If n is negative, fsl_strlen() is used to
   calculate its lenght.
*/
FSL_EXPORT int fsl_appendn(fsl_output_f pfAppend, void * pfAppendArg,
                           const char *str, fsl_int_t n);


/**
   A fsl_output_f() impl which requires that state be an opened,
   writable (FILE*) handle.
*/
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:
   0 on success, FSL_RC_IO if writing fails, or a formatting error
   as documented for fsl_appendfv(). Returns FSL_RC_MISUSE if !fp or
   !fmt.
*/
FSL_EXPORT int fsl_fprintf( FILE * fp, char const * fmt, ... );

/**
   The va_list counterpart of fsl_fprintf().
*/
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
   than or equal to self->capacity then there are no side effects. If
   n is greater than self->capacity, self->list is reallocated and
   self->capacity is adjusted to be at least n (it might be bigger -
   this function may pre-allocate a larger value).

   Passing an n of 0 when self->capacity is 0 is a no-op.

   Newly-allocated slots will be initialized with NULL pointers.

   Returns 0 on success, FSL_RC_MISUSE if !self, FSL_RC_OOM if
   reservation of new elements fails.

   The return value should be used like this:

   ```
   fsl_size_t const n = number of bytes to allocate;
   int const rc = fsl_list_reserve( myList, n );
   if( rc ) { ... error ... }
   ```

   @see fsl_list_clear()
   @see fsl_list_visit_free()
*/
FSL_EXPORT int fsl_list_reserve( fsl_list *  self, fsl_size_t n );

/**
   Appends a bitwise copy of cp to self->list, expanding the list as
   necessary and adjusting self->used.

   Returns 0 on success, FSL_RC_OOM on allocation error, FSL_RC_MISUSE
   if !self.

   Ownership of cp is unchanged by this call. cp may not be NULL.
*/
FSL_EXPORT int fsl_list_append( fsl_list *  self, void * cp );

/**
   Swaps all contents of both lhs and rhs. Results are undefined if
   lhs or rhs are NULL or not properly initialized (via initial copy
   initialization from fsl_list_empty resp. fsl_list_empty_m).
*/
FSL_EXPORT void fsl_list_swap( fsl_list *  lhs, fsl_list *  rhs );

/** @typedef typedef int (*fsl_list_visitor_f)(void * p, void * visitorState )

    Generic visitor interface for fsl_list lists.  Used by
    fsl_list_visit(). p is the pointer held by that list entry and
    visitorState is the 4th argument passed to fsl_list_visit().

    Implementations must return 0 on success. Any other value causes
    looping to stop and that value to be returned, but interpretation
    of the value is up to the caller (it might or might not be an
    error, depending on the context). Note that client code may use
    custom values, and is not strictly required to use FSL_RC_xxx
    values. HOWEVER...  all of the libfossil APIs which take these
    as arguments may respond differently to some codes (most notable
    FSL_RC_BREAK, which they tend to treat as a
    stop-iteration-without-error result), so clients are strongly
    encourage to return an FSL_RC_xxx value on error.
*/
typedef int (*fsl_list_visitor_f)(void * obj, void * visitorState );

/**
   A fsl_list_visitor_f() implementation which requires that obj be
   arbitrary memory which can legally be passed to fsl_free()
   (which this function does). The visitorState parameter is
   ignored.
*/
FSL_EXPORT int fsl_list_v_fsl_free(void * obj, void * visitorState );


/**
   For each item in self->list, visitor(item,visitorState) is
   called.  The item is owned by self. The visitor function MUST
   NOT free the item (unless the visitor is a finalizer!), but may
   manipulate its contents if application rules do not specify
   otherwise.

   If order is 0 or greater then the list is traversed from start
   to finish, else it is traverse from end to begin.

   Returns 0 on success, non-0 on error.

   If visitor() returns non-0 then looping stops and that code is
   returned.
*/
FSL_EXPORT int fsl_list_visit( fsl_list const * self, int order,
                               fsl_list_visitor_f visitor, void * visitorState );

/**
   A list clean-up routine which takes a callback to clean up its
   contents.

   Passes each element in the given list to
   childFinalizer(item,finalizerState). If that returns non-0,
   processing stops and that value is returned, otherwise
   fsl_list_reserve(list,0) is called and 0 is returned.

   WARNING: if cleanup fails because childFinalizer() returns non-0,
   the returned object is effectively left in an undefined state and
   the client has no way (unless the finalizer somehow accounts for it)
   to know which entries in the list were cleaned up. Thus it is highly
   recommended that finalizer functions follow the conventional wisdom
   of "destructors do not throw."

   @see fsl_list_visit_free()
*/
FSL_EXPORT int fsl_list_clear( fsl_list *  list,
                               fsl_list_visitor_f childFinalizer,
                               void * finalizerState );
/**
   Similar to fsl_list_clear(list, fsl_list_v_fsl_free, NULL), but
   only frees list->list if the second argument is true, otherwise
   it sets the list's length to 0 but keep the list->list memory
   intact for later use.

   Be sure only to use this on lists of types for which fsl_free()
   is legal. i.e. don't use it on a list of fsl_deck objects or
   other types which have their own finalizers.

   Results are undefined if list is NULL.

   @see fsl_list_clear()
*/
FSL_EXPORT void fsl_list_visit_free( fsl_list *  list, bool freeListMem );

/**
   Works similarly to the visit operation without the _p suffix
   except that the pointer the visitor function gets is a (**)
   pointing back to the entry within this list. That means that
   callers can assign the entry in the list to another value during
   the traversal process (e.g. set it to 0). If shiftIfNulled is
   true then if the callback sets the list's value to 0 then it is
   removed from the list and self->used is adjusted (self->capacity
   is not changed).
*/
FSL_EXPORT int fsl_list_visit_p( fsl_list *  self, int order,
                                 bool shiftIfNulled,
                                 fsl_list_visitor_f visitor, void * visitorState );


/**
   Sorts the given list using the given comparison function. Neither
   argument may be NULL. The arugments passed to the comparison function
   will be pointers to pointers to the original entries, and may (depending
   on how the list is used) point to NULL.
*/
FSL_EXPORT void fsl_list_sort( fsl_list *  li, fsl_generic_cmp_f cmp);

/**
   Searches for a value in the given list, using the given
   comparison function to determine equivalence. The comparison
   function will never be passed a NULL value by this function - if
   value is NULL then only a NULL entry will compare equal to it.
   Results are undefined if li or cmpf are NULL.

   Returns the index in li of the entry, or a negative value if no
   match is found.
*/
FSL_EXPORT fsl_int_t fsl_list_index_of( fsl_list const * li,
                                        void const * value,
                                        fsl_generic_cmp_f cmpf);

/**
   Equivalent to fsl_list_index_of(li, key, fsl_strcmp_cmp).
*/
FSL_EXPORT fsl_int_t fsl_list_index_of_cstr( fsl_list const * li,
                                             char const * key );


/**
   Returns 0 if the given file is readable. Flags may be any values
   accepted by the access(2) resp. _waccess() system calls.
*/
FSL_EXPORT int fsl_file_access(const char *zFilename, int flags);

/**
   Computes a canonical pathname for a file or directory. Makes the
   name absolute if it is relative. Removes redundant / characters.
   Removes all /./ path elements. Converts /A/../ to just /. If the
   slash parameter is non-zero, the trailing slash, if any, is
   retained.

   If zRoot is not NULL then it is used for transforming a relative
   zOrigName into an absolute path. If zRoot is NULL fsl_getcwd()
   is used to determine the virtual root directory. If zRoot is
   empty (starts with a NUL byte) then this function effectively
   just sends zOrigName through fsl_file_simplify_name().

   Returns 0 on success, FSL_RC_MISUSE if !zOrigName or !pOut,
   FSL_RC_OOM if an allocation fails.

   pOut, if not NULL, is _appended_ to, so be sure to set pOut->used=0
   (or pass it to fsl_b_reuse()) before calling this to start
   writing at the beginning of a re-used buffer. On error pOut might
   conceivably be partially populated, but that is highly
   unlikely. Nonetheless, be sure to fsl_b_clear() it at some
   point regardless of success or failure.

   This function does no actual filesystem-level processing unless
   zRoot is NULL or empty (and then only to get the current
   directory). This does not confirm whether the resulting file
   exists, nor that it is strictly a valid filename for the current
   filesystem. It simply transforms a potentially relative path
   into an absolute one.

   Example:

   ```
   int rc;
   char const * zRoot = "/a/b/c";
   char const * zName = "../foo.bar";
   fsl_b buf = fsl_b_empty;
   rc = fsl_file_canonical_name2(zRoot, zName, &buf, 0);
   if(rc){
     fsl_b_clear(&buf);
     return rc;
   }
   assert(0 == fsl_strcmp( "/a/b/foo.bar, fsl_b_cstr(&buf)));
   fsl_b_clear(&buf);
   ```
*/
FSL_EXPORT int fsl_file_canonical_name2(const char *zRoot,
                                        const char *zOrigName,
                                        fsl_b *  pOut,
                                        bool slash);

/**
   Equivalent to fsl_file_canonical_name2(NULL, zOrigName, pOut, slash).

   @see fsl_file_canonical_name2()
*/

FSL_EXPORT int fsl_file_canonical_name(const char *zOrigName,
                                       fsl_b *  pOut, bool slash);

/**
   Calculates the "directory part" of zFilename and _appends_ it to
   pOut. The directory part is all parts up to the final path
   separator ('\\' or '/'). If leaveSlash is true then the separator
   part is appended to pOut, otherwise it is not. This function only
   examines the first nLen bytes of zFilename.  If nLen is negative
   then fsl_strlen() is used to determine the number of bytes to
   examine.

   If zFilename ends with a slash then it is considered to be its
   own directory part. i.e.  the dirpart of "foo/" evaluates to
   "foo" (or "foo/" if leaveSlash is true), whereas the dirpart of
   "foo" resolves to nothing (empty - no output except a NUL
   terminator sent to pOut).

   Returns 0 on success, FSL_RC_MISUSE if !zFilename or !pOut,
   FSL_RC_RANGE if 0==nLen or !*zFilename, and FSL_RC_OOM if
   appending to pOut fails. If zFilename contains only a path
   separator and leaveSlash is false then only a NUL terminator is
   appended to pOut if it is not already NUL-terminated.

   This function does no filesystem-level validation of the the
   given path - only string evaluation.
*/
FSL_EXPORT int fsl_file_dirpart(char const * zFilename, fsl_int_t nLen,
                                fsl_b * pOut, bool leaveSlash);

/**
   Return the tail of a NUL-terminated file pathname. The tail is the
   last component of the path.  For example, the tail of "/a/b/c.d" is
   "c.d". If the name ends in a slash, a pointer to its NUL terminator
   is returned.
*/
FSL_EXPORT const char *fsl_file_tail(const char *z);

/**
   Writes the absolute path name of the current directory to zBuf,
   which must be at least nBuf bytes long (nBuf includes the space
   for a trailing NUL terminator).

   Returns FSL_RC_RANGE if the name would be too long for nBuf,
   FSL_RC_IO if it cannot determine the current directory (e.g. a
   side effect of having removed the directory at runtime or similar
   things), and 0 on success.

   On success, if outLen is not NULL then the length of the string
   written to zBuf is assigned to *outLen. The output string is
   always NUL-terminated.

   On Windows, the name is converted from unicode to UTF8 and all '\\'
   characters are converted to '/'.  No conversions are needed on
   Unix.
*/
FSL_EXPORT int fsl_getcwd(char *zBuf, fsl_size_t nBuf, fsl_size_t * outLen);


/**
   Return true if the filename given is a valid filename
   for a file in a repository. Valid filenames follow all of the
   following rules:

   -  Does not begin with "/"
   -  Does not contain any path element named "." or ".."
   -  Does not contain any of these characters in the path: "\"
   -  Does not end with "/".
   -  Does not contain two or more "/" characters in a row.
   -  Contains at least one character

   Invalid UTF8 characters result in a false return if bStrictUtf8 is
   true.  If bStrictUtf8 is false, invalid UTF8 characters are
   silently ignored. See
   https://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences and
   https://en.wikipedia.org/wiki/Unicode (for the non-characters).

   Fossil compatibility note: the bStrictUtf8 flag must be true
   when parsing new manifests but is false when parsing legacy
   manifests, for backwards compatibility.

   z must be NUL terminated. Results are undefined if !z.

   Note that periods in and of themselves are valid filename
   components, with the special exceptions of "." and "..", one
   implication being that "...." is, for purposes of this function,
   a valid simple filename.
*/
FSL_EXPORT bool fsl_is_simple_pathname(const char *z, bool bStrictUtf8);

/**
   Return the size of a file in bytes. Returns -1 if the file does
   not exist or is not stat(2)able.
*/
FSL_EXPORT fsl_int_t fsl_file_size(const char *zFilename);

/**
   Return the modification time for a file.  Return -1 if the file
   does not exist or is not stat(2)able.
*/
FSL_EXPORT fsl_time_t fsl_file_mtime(const char *zFilename);

#if 0
/**
   Don't use this. The wd (working directory) family of functions
   might or might-not be necessary and in any case they require
   a fsl_cx context argument because they require repo-specific
   "allow-symlinks" setting.

   Return TRUE if the named file is an ordinary file or symlink
   and symlinks are allowed.

   Return false for directories, devices, fifos, etc.
*/
FSL_EXPORT bool fsl_wd_isfile_or_link(const char *zFilename);
#endif

/**
   Returns true if the named file is an ordinary file. Returns false
   for directories, devices, fifos, symlinks, etc. The name
   may be absolute or relative to the current working dir.
*/
FSL_EXPORT bool fsl_is_file(const char *zFilename);

/**
   Returns true if the given file is a symlink, else false. The name
   may be absolute or relative to the current working dir. On Windows
   platforms this always returns false.
*/
FSL_EXPORT bool fsl_is_symlink(const char *zFilename);

/**
   Returns true if the given filename refers to a plain file or
   symlink, else returns false. The name may be absolute or relative
   to the current working dir.
*/
FSL_EXPORT bool fsl_is_file_or_link(const char *zFilename);

/**
   Returns true if the given path appears to be absolute, else
   false. On Unix a path is absolute if it starts with a '/'.  On
   Windows a path is also absolute if it starts with a letter, a
   colon, and either a backslash or forward slash.
*/
FSL_EXPORT bool fsl_is_absolute_path(const char *zPath);

/**
   Simplify a filename by:

   * converting all \ into / on windows and cygwin
   * removing any trailing and duplicate /
   * removing /./
   * removing /A/../

   Changes are made in-place.  Return the new name length.

   If n is <0 then fsl_strlen() is used to calculate the length.

   If the slash parameter is true, the trailing slash, if any, is
   retained, else any trailing slash is removed.

   As a special case, if the input string (simplified) is "/" then the
   output string will be "/", regardless of the value of the final
   argument. That behavior is debatable but this API is really
   intended to be used for paths deeper than the root directory.
*/
FSL_EXPORT fsl_size_t fsl_file_simplify_name(char *z, fsl_int_t n_, bool slash);

/**
   Return true if string z matches glob pattern zGlob and false if the
   pattern does not match. Always returns false if either argument is
   NULL. Supports all globbing rules supported by sqlite3_strglob().
*/
FSL_EXPORT bool fsl_str_glob(const char *zGlob, const char *z);

/**
   Parses zPatternList as a comma-and/or-fsl_isspace()-delimited
   list of glob patterns (as supported by fsl_str_glob()). Each
   pattern in that list is copied and appended to tgt in the form
   of a new (char *) owned by that list.

   Returns 0 on success, FSL_RC_OOM if copying a pattern to tgt
   fails, FSL_RC_MISUSE if !tgt or !zPatternList. An empty
   zPatternList is not considered an error (to simplify usage) and
   has no side-effects. On allocation error, tgt might be partially
   populated.

   Elements of the glob list may be optionally enclosed in single
   or double-quotes.  This allows a comma to be part of a glob
   pattern.

   Leading and trailing spaces on unquoted glob patterns are
   ignored.

   Note that there is no separate "glob list" class. A "glob list"
   is simply a fsl_list whose list entries are glob-pattern strings
   owned by that list.

   Calling this does not reset tgt's list, so it may be called
   multiple times to prepare a given list.

   Examples of a legal value for zPatternList:

   ```
   "*.c *.h, *.sh, '*.in'"
   ```

   @see fsl_glob_list_append()
   @see fsl_glob_list_matches()
   @see fsl_glob_list_clear()
*/
FSL_EXPORT int fsl_glob_list_parse( fsl_list *  tgt, char const * zPatternList );

/**
   Appends a single blob pattern to tgt, in the form of a new (char *)
   owned by tgt. This function copies zGlob and appends that copy
   to tgt.

   Returns 0 on success, FSL_RC_MISUSE if !tgt or !zGlob or
   !*zGlob, FSL_RC_OOM if appending to the list fails.

   @see fsl_glob_list_parse()
   @see fsl_glob_list_matches()
   @see fsl_glob_list_clear()
*/
FSL_EXPORT int fsl_glob_list_append( fsl_list *  tgt, char const * zGlob );

/**
   Assumes globList is a list of (char [const] *) glob values and
   tries to match each one against zNeedle using
   fsl_str_glob(). If any glob matches, it returns a pointer to the
   matched globList->list entry. If no matches are found, or if any
   argument is invalid, NULL is returned.

   The returned bytes are owned by globList and may be invalidated at
   its leisure. It is primarily intended to be used as a boolean,
   for example:

   ```
   if( fsl_glob_list_matches(myGlobs, someFilename) ) { ... }
   ```

   @see fsl_glob_list_parse()
   @see fsl_glob_list_append()
   @see fsl_glob_list_clear()
*/
FSL_EXPORT char const * fsl_glob_list_matches( fsl_list const * globList,
                                               char const * zNeedle );

/**
   If globList is not NULL this is equivalent to
   fsl_list_visit_free(globList, 1), otherwise it is a no-op.

   Note that this does not free the globList object itself, just
   its underlying list entries and list memory. (In practice, lists
   are either allocated on the stack or as part of a higher-level
   structure, and not on the heap.)

   @see fsl_glob_list_parse()
   @see fsl_glob_list_append()
   @see fsl_glob_list_matches()
*/
FSL_EXPORT void fsl_glob_list_clear( fsl_list *  globList );


/**
   Returns true if the given letter is an ASCII alphabet character.
*/
FSL_EXPORT bool fsl_isalpha(int c);

/**
   Returns true if c is a lower-case ASCII alphabet character.
*/
FSL_EXPORT bool fsl_islower(int c);

/**
   Returns true if c is an upper-case ASCII alphabet character.
*/
FSL_EXPORT bool fsl_isupper(int c);

/**
   Returns true if c is ' ', '\\r' (ASCII 13dec), or '\\t' (ASCII 9
   dec).
*/
FSL_EXPORT bool fsl_isspace(int c);

/**
   Returns true if c is an ASCII digit in the range '0' to '9'.
*/
FSL_EXPORT bool fsl_isdigit(int c);

/**
   Equivalent to fsl_isdigit(c) || fsl_isalpha().
*/
FSL_EXPORT bool fsl_isalnum(int c);

/**
   Returns the upper-case form of c if c is an ASCII alphabet
   letter, else returns c.
*/
FSL_EXPORT int fsl_tolower(int c);

/**
   Returns the lower-case form of c if c is an ASCII alphabet
   letter, else returns c.
*/
FSL_EXPORT int fsl_toupper(int c);

#ifdef _WIN32
/**
   Translate MBCS to UTF-8.  Return a pointer to the translated
   text. ACHTUNG: Call fsl_mbcs_free() (not fsl_free()) to
   deallocate any memory used to store the returned pointer when
   done.
*/
FSL_EXPORT char * fsl_mbcs_to_utf8(char const * mbcs);

/**
   Frees a string allocated from fsl_mbcs_to_utf8(). Results are undefined
   if mbcs was allocated using any other mechanism.
*/
FSL_EXPORT void fsl_mbcs_free(char * mbcs);
#endif
/* _WIN32 */

/**
   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.

   This function exists only for Windows. On other platforms
   it behaves like fsl_strdup().

   The returned type is (wchar_t*) on Windows and (char*)
   everywhere else.
*/
FSL_EXPORT void *fsl_utf8_to_unicode(const char *zUtf8);

/**
   Translates Unicode text into UTF-8.  Return a pointer to the
   translated text. Call fsl_unicode_free() to deallocate any
   memory used to store the returned pointer when done.

   This function exists only for Windows. On other platforms it
   behaves like fsl_strdup().
*/
FSL_EXPORT char *fsl_unicode_to_utf8(const void *zUnicode);

/**
   Translate text from the OS's character set into UTF-8. Return a
   pointer to the translated text. Call fsl_os_str_free() to
   deallocate any memory used to store the returned pointer when
   done.

   This function must not convert '\' to '/' on Windows/Cygwin, as
   it is used in places where we are not sure it's really filenames
   we are handling, e.g. fsl_getenv() or handling the argv
   arguments from main().

   On Windows, translate some characters in the in the range
   U+F001 - U+F07F (private use area) to ASCII. Cygwin sometimes
   generates such filenames. See:
   <https://cygwin.com/cygwin-ug-net/using-specialnames.html>
*/
FSL_EXPORT char *fsl_filename_to_utf8(const void *zFilename);

/**
   Attempts to ensure that the name of a file in the filesystem matches
   the same case as one provided by the user. This distinction can be
   significant for users on case-insensitive filesystems.

   `zDir` must be the name of the target directory and `zPath` must be
   a relative path rooted at `zDir`.  If `zPath` does not exist, it is
   assumed to be a _potential_ name and `*zOut` will be set to an
   as-is copy of `zPath`.

   If `isCaseSensitive` is true then this function is essentially a
   dummy stub which returns a copy of `zPath`, made using
   fsl_strdup(), via `*zOut`.

   If isCaseSensitive is false, then it behaves rather differently:

   Uses opendir() on the given directory and scans it for a name
   matching `zPath`, case-insensitvely and recursively. On success,
   the result is a case-correct copy of `zPath`.

   On error, non-zero is returned and `*zOut` is not modified. On
   success, `*zOut` is modified as described above and ownership of it
   is transfered to the caller, who must eventually pass it to
   fsl_free().

   Non-0 error codes include:

   - FSL_RC_OOM on allocation error.
   - If opendir() fails on `zDir` or on a matching subdirectory, the
     counterpart of its errno value, as per fsl_errno_to_rc(),
     falling back to FSL_RC_IO: for example FSL_RC_NOT_FOUND for a
     missing directory and FSL_RC_ACCESS for an unreadable one.

   Design note: `isCaseSensitive` is provided as a bool, rather than a
   fsl_cx instance (which has a setting for that flag), so that this
   routine can be used in cases where a fsl_cx is not readily
   available and in cases where this validation is desired on
   case-sensitive filesystems. When a fsl_cx is available,
   fsl_cx_is_case_sensitive() may optionally be used to as the value
   for the first argument. Depending on _how_ filenames are collected,
   however, this case-check may or may not be entirely superfluous.
*/
FSL_EXPORT int fsl_filename_preferred_case(bool isCaseSensitive, const char *zDir,
                                           const char *zPath, char **zOut);

/**
   Translate text from UTF-8 to the OS's filename character set.
   Return a pointer to the translated text. Call
   fsl_os_str_free() to deallocate any memory used to store the
   returned pointer when done.

   On Windows, characters in the range U+0001 to U+0031 and the
   characters '"', '*', ':', '<', '>', '?' and '|' are invalid in
   filenames. Therefore, translate those to characters in the in the
   range U+F001 - U+F07F (private use area), so those characters
   never arrive in any Windows API. The filenames might look
   strange in Windows explorer, but in the cygwin shell everything
   looks as expected.

   See: <https://cygwin.com/cygwin-ug-net/using-specialnames.html>

   The returned type is (wchar_t*) on Windows and (char*)
   everywhere else.
*/
FSL_EXPORT void *fsl_utf8_to_filename(const char *zUtf8);


/**
   Deallocate pOld, which must be NULL or must have been allocated by
   fsl_filename_to_utf8(), fsl_utf8_to_filename(), fsl_getenv(), or
   another routine which explicitly documents this function as being
   the proper finalizer for its returned memory.
*/
FSL_EXPORT void fsl_os_str_free(void *pOld);

/**
   Returns a (possible) copy of the environment variable with the
   given key, or NULL if no entry is found. The returned value must
   be passed to fsl_os_str_free() to free it. ACHTUNG: DO NOT
   MODIFY the returned value - on Unix systems it is _not_ a
   copy. That interal API inconsistency "should" be resolved
   (==return a copy from here, but that means doing it everywhere)
   to avoid memory ownership problems later on.

   Why return a copy? Because native strings from at least one of
   the more widespread OSes often have to be converted to something
   portable and this requires allocation on such platforms, but
   not on Unix. For API transparency, that means all platforms get
   the copy(-like) behaviour.
*/
FSL_EXPORT char *fsl_getenv(const char *zName);

/**
   Collects a list of directories intended to use as temp dirs in the
   current environment. The returned array ends with a NULL element to
   mark its end.  The memory's ownership is a bit awkward and
   therefore it must be eventually freed by passing it to
   fsl_temp_dirs_free().

   No entries in the returned list contain a trailing slash unless the
   entry is itself a reference to a Unix-style root directory (which
   would be highly unusual).

   The list of directories varies by platform:

   Windows:

   - `GetTempPath()`, `$TEMP`, `$TMP`, "."

   Non-Windows:

   - `$TMPDIR`, "/var/tmp", "/usr/tmp", "/tmp", "/temp",
   "."

   (`$X` refers to the value of environment variable `X`.)

   Noting that only directories in those lists which actually exist
   (at the time this is called) are added to the list (also noting
   that "." always exists unless CWD is deleted while the app is
   active). If no suitable directories are found, an empty array (with
   a leading `NULL` element) is returned, but this would indicate
   that, e.g., even CWD does not exist (so the app has bigger
   problems).

   `NULL` is only returned if allocation of the containing array
   fails. Failure to allocate memory for a given directory name (as
   those require conversion on some platforms) is ignored and such
   entries are simply skipped over.

   @see fsl_temp_dirs_free()
   @see fsl_file_tempname()
*/
FSL_EXPORT char ** fsl_temp_dirs_get(void);

/**
   If aDirs is not NULL then it is expected to be an array created by
   fsl_temp_dirs_get() and it frees the list's entries and the list
   itself. After calling this, the argument's memory is invalidated
   and any use of it leads to undefined results.

   This is a harmless no-op if the argument is NULL.

   @see fsl_temp_dirs_get()
   @see fsl_file_tempname()
*/
FSL_EXPORT void fsl_temp_dirs_free(char **aDirs);

/**
   Creates a semi-random temp filename and appends it to the given
   buffer. The second argument is an optional string to prefix
   each filename with. If it is NULL then a library-wide default is
   used. If it is empty then no prefix is used. The final argument is
   expected to be NULL or a list of directories in the format
   constructed by fsl_temp_dirs_get(). If it is not NULL, this
   function uses the first entry in dirs which refers to an existing
   directory. If it is NULL then the buffer is filled with the new
   name with no directory prefix.

   Returns...

   - 0 on success, in which case tgt is populated with the new name.

   - If tgt->errCode is not 0 when this is called, that is returned
     and this function has no further side effects.

   - FSL_RC_NOT_FOUND if dirs is empty or refers only to non-existent
     directories.

   - FSL_RC_OOM if allocating memory for the target buffer fails.

   - FSL_RC_RANGE if, after some hard-coded number of attempts, it is
     unable to construct a unique filename due to name collisions in
     the target directory. That "shouldn't ever happen."

   Sidebars:

   - This function does no translation or validation of the 2nd
     argument other than to check if it is NULL. It "should" be either
     a file base name, with no path component, or a relative path
     component for which the caller has already created the directory.
     e.g. use the base name of the application, e.g. "my-app".

   - This function does not actually write to the filesystem, it just
     constructs a name. There is hypothetically a window of
     opportunity for another file with the same name to be created
     before the caller has a chance to create the file, but the
     chances of that actually happening are close enough to zero to
     rule them out for all practical purposes.

   - The RNG is officially unspecified. (That said:
     sqlite3_randomness().)

   @see fsl_temp_dirs_get()
   @see fsl_temp_dirs_free()
*/
FSL_EXPORT int fsl_file_tempname(fsl_b *  tgt, char const *zPrefix,
                                 char * const * dirs);

/**
   Returns a positive value if zFilename is a directory, 0 if
   zFilename does not exist, or a negative value if zFilename
   exists but is something other than a directory. Results are
   undefined if zFilename is NULL.

   This function expects zFilename to be a well-formed path -
   it performs no normalization on it.
*/
FSL_EXPORT int fsl_dir_check(const char *zFilename);

/**
   Check the given path to determine whether it is an empty directory.
   Returns 0 on success (i.e., directory exists and is empty), <0 if
   the provided path is not a directory or cannot be opened, and >0 if
   the directory is not empty.
*/
FSL_EXPORT int fsl_dir_is_empty(const char *path);

/**
   Deletes the given file from the filesystem. Returns 0 on
   success. If the component is a directory, this operation will
   fail. If zFilename refers to a symlink, the link (not its target)
   is removed.

   Results are undefined if zFilename is NULL.

   Potential TODO: if it refers to a dir, forward the call to
   fsl_rmdir().
*/
FSL_EXPORT int fsl_file_unlink(const char *zFilename);

/**
   Renames file zFrom to zTo using the OS's equivalent of
   `rename(2)`. Both files must be in the same filesystem and any
   directory parts of zTo must already exist. Returns 0 on success,
   FSL_RC_OOM if a filename conversion allocation fails (on platforms
   which do that), or a FSL_RC_xxx counterpart of an `errno` value if
   the `rename(2)` call fails (as per fsl_errno_to_rc()).
*/
FSL_EXPORT int fsl_file_rename(const char *zFrom, const char *zTo);

/**
   Deletes an empty directory from the filesystem. Returns 0
   on success. There are any number of reasons why deletion
   of a directory can fail, some of which include:

   - It is not empty or permission denied (FSL_RC_ACCESS).

   - Not found (FSL_RC_NOT_FOUND).

   - Is not a directory or (on Windows) is a weird pseudo-dir type for
     which rmdir() does not work (FSL_RC_TYPE).

   - I/O error (FSL_RC_IO).

   @see fsl_dir_is_empty()
*/
FSL_EXPORT int fsl_rmdir(const char *zFilename);

/**
   Sets the mtime (Unix epoch) for a file. Returns 0 on success,
   non-0 on error. If newMTime is less than 0 then the current
   time(2) is used. This routine does not create non-existent files
   (e.g. like a Unix "touch" command).
*/
FSL_EXPORT int fsl_file_mtime_set(const char *zFilename, fsl_time_t newMTime);

/**
   On non-Windows platforms, this function sets or unsets the
   executable bits on the given filename. All other permissions are
   retained as-is. Returns 0 on success. On Windows this is a no-op,
   returning 0.

   If the target is a directory or a symlink, this is a no-op and
   returns 0.
*/
FSL_EXPORT int fsl_file_exec_set(const char *zFilename, bool isExec);

/**
   Returns true if the argument is fsl_stat()'able and has the
   executable bit set, else false.
*/
FSL_EXPORT bool fsl_file_isexec(const char *zFilename);

/**
   Makes a bitwise copy of the file zFrom to file zTo, creating any
   directories needed for the target file's if they do not already
   exist. If the source file is executable then the target file will
   also be made so, but any failure to do so (e.g. because the target
   filesystem does not support it) is silently ignored.

   Returns 0 on success. On error it may return any number of result
   codes if opening a file fails, if a mkdir fails (see
   fsl_mkdir_for_file()), or if any I/O fails.

   Results are undefined if the source and target refer to the
   same file.
*/
FSL_EXPORT int fsl_file_copy(char const *zFrom, char const *zTo);

/**
   Create the directory with the given name if it does not already
   exist. If forceFlag is true, delete any prior non-directory
   object with the same name.

   Return 0 on success, non-0 on error.

   If the directory already exists then 0 is returned, not an error
   (FSL_RC_ALREADY_EXISTS), because that simplifies usage. If
   another filesystem entry with this name exists and forceFlag is
   true then that entry is deleted before creating the directory,
   and this operation fails if deletion fails. If forceFlag is
   false and a non-directory entry already exists, FSL_RC_TYPE is
   returned.

   For recursively creating directories, use fsl_mkdir_for_file().

   Bug/corner case: if zFilename refers to a symlink to a
   non-existent directory, this function gets slightly confused,
   tries to make a dir with the symlink's name, and returns
   FSL_RC_ALREADY_EXISTS. How best to resolve that is not yet
   clear. The problem is that stat(2)ing the symlink says "nothing
   is there" (because the link points to a non-existing thing), so
   we move on to the underlying mkdir(), which then fails because
   the link exists with that name.
*/
FSL_EXPORT int fsl_mkdir(const char *zName, bool forceFlag);

/**
   A convenience form of fsl_mkdir() which can recursively create
   directories. If zName has a trailing slash then the last
   component is assumed to be a directory part, otherwise it is
   assumed to be a file part (and no directory is created for that
   part). zName may be either an absolute or relative path.

   Returns 0 on success (including if all directories already exist).
   Returns FSL_RC_OOM if there is an allocation error. Returns
   FSL_RC_TYPE if one of the path components already exists and is not
   a directory. Returns FSL_RC_RANGE if zName is NULL or empty. If
   zName is only 1 byte long, this is a no-op.

   On systems which support symlinks, a link to a directory is
   considered to be a directory for purposes of this function.

   If forceFlag is true and a non-directory component is found in
   the filesystem where zName calls for a directory, that component
   is removed (and this function fails if removal fails).

   Examples:

   "/foo/bar" creates (if needed) /foo, but assumes "bar" is a file
   component. "/foo/bar/" creates /foo/bar. However "foo" will not
   create a directory - because the string has no path component,
   it is assumed to be a filename.

   Both "/foo/bar/my.doc" and "/foo/bar/" result in the directories
   "/foo/bar".
*/
FSL_EXPORT int fsl_mkdir_for_file(char const *zName, bool forceFlag);

/**
   This function expects its second argument to refer to a symlink
   (and that the caller has already validated that it is one). The
   `readlink(2)` system call is used to fetch the contents of that
   link and the target buffer is populated with those contents
   (reusing any memory the buffer may already own).

   Returns 0 on success, FSL_RC_OOM if copying to the target buffer
   fails due to an allocation error, or an error propagated from
   `readlink()` in the form of a fsl_errno_to_rc() result.

   Caveat: on Windows platforms this function simply passes the buffer
   to fsl_b_reuse() and returns 0. It should arguably read the
   contents of zFilename into the buffer in that case, on the
   assumption that the file is a pseudo-symlink. That decision may be
   re-evaluated if/when the library claims to have fossil-compatible
   symlink support.

   Bugs:

   - This function has a limited internal buffer as a target for
     `readlink()`. It "should be" long enough for any "reasonable"
     uses in the scope of this library, but there's bound to be some
     user out there who wants to use it for other contexts.
*/
FSL_EXPORT int fsl_symlink_read(fsl_b *  tgt, char const * zFilename);

/**
   Creates a symlink or pseudo-symlink named zLinkFile linking to
   zTargetFile. If realLink is true and this is a non-Windows platform
   then:

   - fsl_file_simplify_name() is used to normalize zLinkFile.

   - `symlink(2)` is used to link zTargetFile to a new link named the
      simplified form of zLinkFile. If zLinkFile already exists, this
      will fail.

   If realLink is false or this is a Windows platform, a file is
   created named zLinkFile containing the string zTargetFile as its
   contents. If a file or symlink named zLinkFile already exists, it
   is removed before writing the new contents.

   In both cases the parent directories for zLinkFile are created, if
   needed, but that process will fail with FSL_RC_TYPE if any
   non-directory components with conflicting names are found in the
   to-be-mkdir'd path.

   Returns 0 on success or some lower-level result code if
   creation/writing of a directory, a symlink, or pseudo-symlink
   fails.
*/
FSL_EXPORT int fsl_symlink_create(char const *zTargetFile, char const * zLinkFile,
                                  bool realLink);

/**
   Reads symlink zFrom, as per fsl_symlink_read(), then creates a copy
   named zTo, as per fsl_symlink_create(). The first argument for the
   latter call is the contents of the result of fsl_symlink_read().
   The 2nd and 3rd arguments to fsl_symlink_create() are the 2nd and
   3rd arguments to this function.

   Returns 0 on success, FSL_RC_OOM on OOM, or any of various
   filesystem-related non-0 codes if reading or saving the link fails.
*/
FSL_EXPORT int fsl_symlink_copy(char const *zFrom, char const *zTo, bool realLink);

/**
   Uses fsl_getenv() to look for the environment variables
   (FOSSIL_USER, (Windows: USERNAME), (Unix: USER, LOGNAME)). If
   it finds one it returns a copy of that value, which must
   eventually be passed to fsl_free() to free it (NOT
   fsl_os_str_free(), though fsl_getenv() requires that one). If
   it finds no match, or if copying the entry fails, it returns
   NULL.

   @see fsl_cx_user_set()
   @see fsl_cx_user_get()
*/
FSL_EXPORT char * fsl_user_name_guess(void);

/**
   Tries to find the user's home directory. If found, 0 is
   returned, tgt's memory is _overwritten_ (not appended) with the
   path, and tgt->used is set to the path's string length.  (Design
   note: the overwrite behaviour is inconsistent with most of the
   API, but the implementation currently requires this.)

   On Unix platforms the home directory is taken from the HOME
   environment variable. On Windows it is the first of LOCALAPPDATA,
   APPDATA, and HOMEPATH (prefixed by HOMEDRIVE when that is set)
   which is set. FOSSIL_HOME and XDG_CONFIG_HOME are not consulted
   here: they apply only to locating the global config database,
   which fsl_config_global_preferred_name() does before or after
   calling this function.

   If requireWriteAccess is true then the directory is checked for
   write access, and FSL_RC_ACCESS is returned if that check
   fails. For historical (possibly techinical?) reasons, this check
   is only performed on Unix platforms. On others this argument is
   ignored. When writing code on Windows, it may be necessary to
   assume that write access is necessary on non-Windows platform,
   and to pass 1 for the second argument even though it is ignored
   on Windows.

   On error non-0 is returned and tgt is updated with an error
   string OR (if the error was an allocation error while appending
   to the path or allocating MBCS strings for Windows), it returns
   FSL_RC_OOM and tgt "might" be updated with a partial path (up to
   the allocation error), and "might" be empty (if the allocation
   error happens early on).

   This routine does not canonicalize/transform the home directory
   path provided by the environment, other than to convert the
   string byte encoding on some platforms. i.e. if the environment
   says that the home directory is "../" then this function will
   return that value, possibly to the eventual disappointment of
   the caller.

   Result codes include:

   - FSL_RC_OK (0) means a home directory was found and tgt is
   populated with its path.

   - FSL_RC_NOT_FOUND means the home directory (platform-specific)
   could not be found.

   - FSL_RC_ACCESS if the home directory is not writable and
   requireWriteAccess is true. Unix platforms only -
   requireWriteAccess is ignored on others.

   - FSL_RC_TYPE if the home (as determined via inspection of the
   environment) is not a directory.

   - FSL_RC_OOM if a memory (re)allocation fails.
*/
FSL_EXPORT int fsl_find_home_dir( fsl_b *  tgt, bool requireWriteAccess );

/**
   Values for use with the fsl_fstat::type field.
*/
enum fsl_fstat_type_e {
/** Sentinel value for unknown/invalid filesystem entry types. */
FSL_FSTAT_TYPE_UNKNOWN = 0,
/** Indicates a directory filesystem entry. */
FSL_FSTAT_TYPE_DIR,
/** Indicates a non-directory, non-symlink filesystem entry.
    Because fossil's scope is limited to SCM work, it assumes that
    "special files" (sockets, etc.) are just files, and makes no
    special effort to handle them.
*/
FSL_FSTAT_TYPE_FILE,
/** Indicates a symlink filesystem entry. */
FSL_FSTAT_TYPE_LINK
};
typedef enum fsl_fstat_type_e fsl_fstat_type_e;

/**
   Bitmask values for use with the fsl_fstat::perms field.

   Only permissions which are relevant for fossil are listed here.
   e.g. read-vs-write modes are irrelevant for fossil as it does not
   track them. It manages only the is-executable bit. In in the
   contexts of fossil manifests, it also treats "is a symlink" as a
   permission flag.
*/
enum fsl_fstat_perm_e {
/**
   Sentinel value.
*/
FSL_FSTAT_PERM_UNKNOWN = 0,
/**
   The executable bit, as understood by Fossil. Fossil does not
   differentiate between different +x values for user/group/other.
*/
FSL_FSTAT_PERM_EXE = 0x01
};
typedef enum fsl_fstat_perm_e fsl_fstat_perm_e;

/**
   A simple wrapper around the stat(2) structure resp. _stat/_wstat
   (on Windows). It exposes only the aspects of stat(2) info which
   Fossil works with, and not any platform-/filesystem-specific
   details except the executable bit for the permissions mode and some
   handling of symlinks.
*/
struct fsl_fstat {
  /**
     Indicates the type of filesystem object.
  */
  fsl_fstat_type_e type;
  /**
     The time of the last file metadata change (owner, permissions,
     etc.). The man pages (neither for Linux nor Windows) do not
     specify exactly what unit this is. Let's assume seconds since the
     start of the Unix Epoch.
  */
  fsl_time_t ctime;
  /**
     Last modification time.
  */
  fsl_time_t mtime;
  /**
     The size of the stat'd file, in bytes.
  */
  fsl_size_t size;
  /**
     Contains the filesystem entry's permissions as a bitmask of
     fsl_fstat_perm_e values. Note that only the executable bit for
     _files_ (not directories) is exposed here.
  */
  int perm;
};

/** Empty-initialized fsl_fstat structure, intended for const-copy
    construction. */
#define fsl_fstat_empty_m {FSL_FSTAT_TYPE_UNKNOWN,0,0,-1,0}

/** Empty-initialized fsl_fstat instance, intended for non-const copy
    construction. */
FSL_EXPORT const fsl_fstat fsl_fstat_empty;

/**
   Runs the OS's stat(2) equivalent to populate fst (if not NULL) with
   information about the given file.

   The second argument may be NULL.

   Returns 0 on success. Results are undefined if zFilename is NULL or
   invalid. Returns FSL_RC_NOT_FOUND if no filesystem entry is found
   for the given name and FSL_RC_OOM if converting the name to the
   platform's filename encoding fails. Any other failure of the
   underlying stat()/lstat()/_wstati64() call returns the counterpart
   of its errno value, as per fsl_errno_to_rc(), falling back to
   FSL_RC_IO. Note that the fst parameter may be NULL,
   in which case the return value will be 0 if the name is stat-able,
   but will return no other information about it.

   The derefSymlinks argument is ignored on non-Unix platforms.  On
   Unix platforms, if derefSymlinks is true then stat(2) is used, else
   lstat(2) (if available on the platform) is used. For most cases
   clients should pass true. They should only pass false if they need
   to differentiate between symlinks and files.

   The fsl_fstat_type_e family of flags can be used to determine the
   type of the filesystem object being stat()'d (file, directory, or
   symlink). It does not apply any special logic for platform-specific
   oddities other than symlinks (e.g. character devices and such).
*/
FSL_EXPORT int fsl_stat(const char *zFilename, fsl_fstat *  fst,
                        bool derefSymlinks);

/**
   Create a new fossil-format delta between the memory zIn and zOut.

   The delta is written into a preallocated buffer, zDelta, which
   must be at least 60 bytes longer than the target memory, zOut.
   The delta string will be NUL-terminated, but it might also
   contain embedded NUL characters if either the zSrc or zOut files
   are binary.

   On success this function returns 0 and the length of the delta
   string, in bytes, excluding the final NUL terminator character,
   is written to *deltaSize.

   Returns FSL_RC_OOM if memory allocation fails during generation of
   the delta. Returns FSL_RC_RANGE if lenSrc or lenOut are "too
   big" (if they cause an overflow in the math).

   Results are undefined if any pointer is NULL.

   Output Format:

   The delta begins with a base64 number followed by a newline.
   This number is the number of bytes in the TARGET file.  Thus,
   given a delta file z, a program can compute the size of the
   output file simply by reading the first line and decoding the
   base-64 number found there.  The fsl_delta_applied_size()
   routine does exactly this.

   After the initial size number, the delta consists of a series of
   literal text segments and commands to copy from the SOURCE file.
   A copy command looks like this:

   (Achtung: extra backslashes are for Doxygen's benefit - not
   visible in the processsed docs.)

   NNN\@MMM,

   where NNN is the number of bytes to be copied and MMM is the
   offset into the source file of the first byte (both base-64).
   If NNN is 0 it means copy the rest of the input file.  Literal
   text is like this:

   NNN:TTTTT

   where NNN is the number of bytes of text (base-64) and TTTTT is
   the text.

   The last term is of the form

   NNN;

   In this case, NNN is a 32-bit bigendian checksum of the output
   file that can be used to verify that the delta applied
   correctly.  All numbers are in base-64.

   Pure text files generate a pure text delta.  Binary files
   generate a delta that may contain some binary data.

   Algorithm:

   The encoder first builds a hash table to help it find matching
   patterns in the source file.  16-byte chunks of the source file
   sampled at evenly spaced intervals are used to populate the hash
   table.

   Next we begin scanning the target file using a sliding 16-byte
   window.  The hash of the 16-byte window in the target is used to
   search for a matching section in the source file.  When a match
   is found, a copy command is added to the delta.  An effort is
   made to extend the matching section to regions that come before
   and after the 16-byte hash window.  A copy command is only
   issued if the result would use less space that just quoting the
   text literally. Literal text is added to the delta for sections
   that do not match or which can not be encoded efficiently using
   copy commands.

   @see fsl_delta_applied_size()
   @see fsl_delta_apply()
*/
FSL_EXPORT int fsl_delta_create( unsigned char const *zSrc, fsl_size_t lenSrc,
                      unsigned char const *zOut, fsl_size_t lenOut,
                      unsigned char *zDelta, fsl_size_t * deltaSize);

/**
   Works identically to fsl_delta_create() but sends its output to
   the given output function. out(outState,...) may be called any
   number of times to emit delta output. Each time it is called it
   should append the new bytes to its output channel.

   The semantics of the return value and the first four arguments
   are identical to fsl_delta_create(), with these ammendments
   regarding the return value:

   - Returns FSL_RC_MISUSE if any of (zV1, zV2, out) are NULL.

   - If out() returns non-0 at any time, delta generation is
     aborted and that code is returned.

   Example usage:

   ```
   int rc = fsl_delta_create( v1, v1len, v2, v2len,
                              fsl_output_f_FILE, stdout);
   ```
*/
FSL_EXPORT int fsl_delta_create2( unsigned char const *zV1, fsl_size_t lenV1,
                                  unsigned char const *zV2, fsl_size_t lenV2,
                                  fsl_output_f out, void * outState);

/**
   A fsl_delta_create() wrapper which uses the first two arguments
   as the original and "new" content versions to delta, and outputs
   the delta to the 3rd argument (overwriting any existing contents
   and re-using any memory it had allocated).

   If any of the buffers have the same address, FSL_RC_MISUSE is
   returned. If fsl_b_err() is true for the 3rd argument, that
   value is returned without side effects. If allocation of memory for
   the delta fails, FSL_RC_OOM is returned and delta's errCode is
   updated with that value. If either input is larger than
   UINT32_MAX bytes, which the delta format cannot encode,
   FSL_RC_RANGE is returned.

   Results are undefined if any argument is NULL.

   Returns 0 on success.
*/
FSL_EXPORT int fsl_b_delta_create( fsl_b const * src,
                                        fsl_b const * newVers,
                                        fsl_b *  delta);

/**
   Apply a delta created using fsl_delta_create().

   The output buffer must be big enough to hold the whole output
   file and a NUL terminator at the end. The
   fsl_delta_applied_size() routine can be used to determine that
   size.

   zSrc represents the original sources to apply the delta to.
   It must be at least lenSrc bytes of valid memory.

   zDelta holds the delta (created using fsl_delta_create()),
   and it must be lenDelta bytes long.

   On success this function returns 0 and writes the applied delta
   to zOut.

   Returns FSL_RC_MISUSE if any pointer argument is NULL. Returns
   FSL_RC_RANGE if lenSrc or lenDelta are "too big" (if they cause an
   overflow in the math) or lenDelta is 0. Invalid delta input can
   cause any of FSL_RC_RANGE, FSL_RC_DELTA_INVALID_TERMINATOR,
   FSL_RC_CHECKSUM_MISMATCH, FSL_RC_SIZE_MISMATCH, or
   FSL_RC_DELTA_INVALID_OPERATOR to be returned.

   Refer to the fsl_delta_create() documentation above for a
   description of the delta file format.

   @see fsl_delta_applied_size()
   @see fsl_delta_create()
   @see fsl_delta_apply2()
*/
FSL_EXPORT int fsl_delta_apply( unsigned char const *zSrc, fsl_size_t lenSrc,
                     unsigned char const *zDelta, fsl_size_t lenDelta,
                     unsigned char *zOut );

/**
   Functionally identical to fsl_delta_apply() but any errors
   generated during application of the delta (as distinct from
   argument validation) are described in more detail in pErr. If pErr
   is NULL this behaves exactly as documented for fsl_delta_apply().
*/
FSL_EXPORT int fsl_delta_apply2( unsigned char const *zSrc,
                                 fsl_size_t lenSrc,
                                 unsigned char const *zDelta,
                                 fsl_size_t lenDelta,
                                 unsigned char *zOut,
                                 fsl_error * pErr);
/**
  Calculates the size (in bytes) of the output from applying a the
  given delta. On success 0 is returned and *appliedSize will be
  updated with the amount of memory required for applying the
  delta. zDelta must point to lenDelta bytes of memory in the
  format emitted by fsl_delta_create(). It is legal for appliedSize
  to point to the same memory as the 2nd argument.

  Returns FSL_RC_RANGE if lenDelta is too short to be a delta. Returns
  FSL_RC_DELTA_INVALID_TERMINATOR if the delta's encoded length is not
  properly terminated.

  Results are undefined if any pointer argument is NULL.

  This routine is provided so that an procedure that is able to call
  fsl_delta_apply() can learn how much space is required for the
  output and hence allocate no more space that is really needed.

  TODO?: consolidate 2nd and 3rd parameters into one i/o parameter?

  @see fsl_delta_apply()
  @see fsl_delta_create()
*/
FSL_EXPORT int fsl_delta_applied_size(unsigned char const *zDelta,
                                      fsl_size_t lenDelta,
                                      fsl_size_t * appliedSize);

/**
   "Fossilizes" the first len bytes of the given input string. If
   (len<0) then fsl_strlen(inp) is used to calculate its length.
   The output replaces the contents of out (it sets out->used to 0
   before writing), which is expanded as needed and out->used is
   updated accordingly.  Returns 0 on success, FSL_RC_MISUSE if !inp
   or !out. If 0==len or (!*inp && len<0), it sets out->used to 0 and
   returns 0. Returns FSL_RC_OOM if reservation of the output buffer
   fails (it is expanded, at most, one time by this function), or
   fsl_b_err() of out if that is non-0.

   Fossilization replaces the following bytes/sequences with the
   listed replacements:

   (Achtung: usage of doubled backslashes here it just to please
   doxygen - they will show up as single slashes in the processed
   output.)

   - Backslashes are doubled.

   - (\\n, \\r, \\v, \\t, \\f) are replaced with \\\\X, where X is the
   conventional encoding letter for that escape sequence.

   - Spaces are replaced with \\s.

   - Embedded NULs are replaced by \\0 (numeric 0, not character
   '0').
*/
FSL_EXPORT int fsl_bytes_fossilize( unsigned char const * inp, fsl_int_t len,
                         fsl_b * out );
/**
   "Defossilizes" bytes encoded by fsl_bytes_fossilize() in-place.
   inp must be a string encoded by fsl_bytes_fossilize(), and the
   decoding processes stops at the first unescaped NUL terminator.
   It has no error conditions except for !inp or if inp is not
   NUL-terminated, both of which invoke in undefined behaviour.

   If resultLen is not NULL then *resultLen is set to the resulting string
   length.

*/
FSL_EXPORT void fsl_bytes_defossilize( unsigned char * inp, fsl_size_t * resultLen );

/**
   Defossilizes the contents of b. Equivalent to:
   fsl_bytes_defossilize( b->mem, &b->used );
*/
FSL_EXPORT void fsl_b_defossilize( fsl_b *  b );

/**
   Returns true if the input string contains only valid lower-case
   base-16 digits. If any invalid characters appear in the string,
   false is returned.
*/
FSL_EXPORT bool fsl_validate16(const char *zIn, fsl_size_t nIn);

/**
   The input string is a base16 value.  Convert it into its canonical
   form.  This means that digits are all lower case and that conversions
   like "l"->"1" and "O"->"0" occur.
*/
FSL_EXPORT void fsl_canonical16(char *z, fsl_size_t n);

/**
   Decode a N-character base-16 number into base-256.  N must be a
   multiple of 2. The output buffer must be at least N/2 characters
   in length. Returns 0 on success, FSL_RC_RANGE if N is odd or if
   any of the first N bytes of zIn is not a hexadecimal digit. On
   error, pOut may have been partly written.
*/
FSL_EXPORT int fsl_decode16(const unsigned char *zIn, unsigned char *pOut, fsl_size_t N);

/**
   Encode a N-digit base-256 in base-16. N is the byte length of pIn
   and zOut must be at least (N*2+1) bytes long (the extra is for a
   terminating NUL). Returns zero on success, FSL_RC_MISUSE if !pIn
   or !zOut.
*/
FSL_EXPORT int fsl_encode16(const unsigned char *pIn, unsigned char *zOut, fsl_size_t N);

/*
   Undo the obscuring of text performed by obscure().  Or, if the input is
   not hexadecimal (meaning the input is not the output of obscure()) then
   do the equivalent of strdup().
  
   The result is memory obtained from malloc that should be freed by the caller.
*/
FSL_EXPORT char * fsl_unobscure(const char *zIn);

/**
   Tries to convert the value of errNo, which is assumed to come
   from the global errno, to a fsl_rc_e code. If it can, it returns
   something approximating the errno value, else it returns dflt.

   Example usage:

   ```
   FILE * f = fsl_fopen("...", "...");
   int rc = f ? 0 : fsl_errno_to_rc(errno, FSL_RC_IO);
   ...
   ```

   Why require the caller to pass in errno, instead of accessing it
   directly from this function? To avoid the the off-chance that
   something changes errno between the call and the conversion
   (whether or not that's possible is as yet undetermined). It can
   also be used by clients to map to explicit errno values to
   fsl_rc_e values, e.g. fsl_errno_to_rc(EROFS,-1) returns
   FSL_RC_ACCESS.

   A list of the errno-to-fossil conversions:

   - 0: FSL_RC_OK (0)

   - EINVAL: FSL_RC_MISUSE (could arguably be FSL_RC_RANGE, though)

   - ENOMEM: FSL_RC_OOM

   - EACCES, EBUSY, EPERM, EROFS, EDQUOT, EAGAIN: FSL_RC_ACCESS

   - EISDIR, ENOTDIR: FSL_RC_TYPE

   - ENAMETOOLONG, ELOOP, ERANGE: FSL_RC_RANGE

   - ENOENT: FSL_RC_NOT_FOUND

   - EEXIST: FSL_RC_ALREADY_EXISTS

   - EIO: FSL_RC_IO

   Any other value for errNo causes dflt to be returned.
*/
FSL_EXPORT int fsl_errno_to_rc(int errNo, int dflt);

/**
   Make the given string safe for HTML by converting every "<" into
   "&lt;", every ">" into "&gt;", every "&" into "&amp;", and
   encode '"' as &quot; so that it can appear as an argument to
   markup.

   The escaped output is send to out(oState,...).

   Returns 0 on success or if there is nothing to do (input has a
   length of 0, in which case out() is not called). Returns
   FSL_RC_MISUSE if !out or !zIn. If out() returns a non-0 code
   then that value is returned to the caller.

   If n is negative, fsl_strlen() is used to calculate zIn's length.
*/
FSL_EXPORT int fsl_htmlize(fsl_output_f out, void * oState,
                const char *zIn, fsl_int_t n);

/**
   Functionally equivalent to fsl_htmlize() but optimized to perform
   only a single allocation.

   Returns 0 on success or if there is nothing to do (input has a
   length of 0). Returns FSL_RC_MISUSE if !p or !zIn, and
   FSL_RC_OOM on allocation error.

   If n is negative, fsl_strlen() is used to calculate zIn's length.
*/
FSL_EXPORT int fsl_htmlize_to_buffer(fsl_b *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 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);


/** @enum fsl_diff2_flag_e

   Flags for use with the 2021-era text-diff generation APIs
   (fsl_dibu and friends). This set of flags may still change
   considerably.

   Maintenance reminders:

   - Some of these values are holy and must not be changed without
     also changing the corresponding code in diff2.c.

   - Where these entries semantically overlap with their
     older/deprecated fsl_diff_flag_e counterparts, they MUST (for the
     sake of avoiding client-side Grief) have the same values because
     some internal APIs are used by both of the diff APIs.

  @see fsl_dibu_impl_flags_e

   TODO?:

   - Move the diff-builder-specific flags from here to, possibly, the
     fsl_dibu::implFlags member or a new flag member dedicated to this
     type of flag.
*/
enum fsl_diff2_flag_e {
/** Ignore end-of-line whitespace. Applies to all diff builders. */
FSL_DIFF2_IGNORE_EOLWS = 0x01,
/** Ignore all 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", meaning more than 10000
   lines inserted or deleted, as in fossil(1). 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,
/*
  ACHTUNG: do not use 0x2000 because it would semantically collide
  with FSL_DIFF_ANSI_COLOR.
*/
/**
   More precise but slower side-by-side diff algorithm, for diffs
   which use that.
*/
FSL_DIFF2_SLOW_SBS =       0x4000,
/**
   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,

/**
   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
};

/**
   Flags for use with various concrete fsl_dibu implementations.
   Specifically, these are flags for fsl_dibu::implFlags (as opposed
   to fsl_dibu::pimplFlags, which must not be modified by clients).

   Note that it is perfectly legitimate for different entries to have
   the same values, but different semantics, so long as the different
   entries are specific to different fsl_dibu types.
*/
enum fsl_dibu_impl_flags_e {
/**
   Tells the TCL diff builder that the complete output and each line
   should be wrapped in {...}.
*/
FSL_DIBU_TCL_BRACES = 0x01,
/**
   Tells the TCL diff builder that the squiggly braces embedded in any
   output (as opposed to the braces added by FSL_DIBU_TCL_BRACES)
   need to be backslash-escaped. Whether this is required depends on
   how the output will be used.
*/
FSL_DIBU_TCL_BRACES_ESC = 0x02,
/**
   Tells the TCL diff builder to generate a complete TCL/TK app as output.
   The resulting script can (if tcl and tk are installed) be run with
   tclsh to get a graphical diff.

   Note that this flag includes both FSL_DIBU_TCL_BRACES and
   FSL_DIBU_TCL_BRACES_ESC.
*/
FSL_DIBU_TCL_TK = 0x07

};

/**
   An instance of this class is used to convey certain state to
   fsl_dibu 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_dibu implementations may require that some
   ostensibly optional fields be filled out. Documenting that is TODO,
   as the builders get developed.
*/
struct fsl_dibu_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 hint for side-by-side, a.k.a. split, diffs.

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

     Note that not all diff builders use this. e.g. a diff builder
     which outputs to an ncurses widget cannot do so via this method
     and instead has to use the drawing methods of that API. Thus is
     is legal for this method to be NULL for some builders.
  */
  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_dibu_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_dibu_opt fsl_dibu_opt;

/** Initialized-with-defaults fsl_dibu_opt structure, intended for
    const-copy initialization. */
#define fsl_dibu_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_dibu_opt structure, intended for
    non-const copy initialization. */
extern const fsl_dibu_opt fsl_dibu_opt_empty;

/**
   Information about each line of a file being diffed.

   This type is only in the public API for use by the fsl_dibu
   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.
  /** Index of first non-space char. */
  unsigned short indent;
  /** Number of bytes without leading/trailing space. */
  unsigned short nw;
  /** 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,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_dibu 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_dibu 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 *  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 *  pA,
                             const fsl_dline *  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 *  pA,
                                       const fsl_dline *  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_dibu fsl_dibu;

/**
   This class is the basis of libfossil's port of the diff engine
   added to fossil(1) in 2021-09, colloquially known as the "diff
   builder."

   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().
*/
struct fsl_dibu {
  /**
     Config info, owned by higher-level routines. Every diff builder
     requires one of these but not all options are relevant for all
     builders.

     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_dibu_opt const * opt;
  /**
     Can optionally be set by factory functions to some internal
     opaque value, so that non-member routines specific to that type can determine
     whether any given builder is of the proper type.
  */
  void const * typeID;
  /**
     If not NULL, this is called once per pass 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).

     b->lnLHS and b->lnRHS will be set to 0 before each call.

     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_dibu *  b);

  /**
     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:

     ```
     @@ -A,B +C,D @@
     ```

     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_dibu* ,
                     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_dibu* , 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_dibu* , 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_dibu* , 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_dibu* , 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_dibu* , 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 use 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_dibu* , 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).

     Minor achtung: for a multi-file diff run, this gets called after
     each file. The library does not have enough information to know
     when a builder is "done for good" and if a custom builder
     requires, e.g., extra post-diff-loop processing, the client will
     have to take care of that themselves.
  */
  int (*finish)(fsl_dibu*  b);
  /**
     This optional method is similar to this->finish() but it is not
     called by the library. It is intended to be called, if it's not
     NULL, by the client after they are done, e.g., looping over a
     series of diffs with the same builder. Some builders can use this
     to flush any final state, e.g. dumping out change count totals or
     some such.

     As an example, the TCL/TK-based builder, when the FSL_DIBU_TCL_TK
     flag is set on this->implFlag, embeds a TK script in the output
     from this method.
  */
  int (*finally)(fsl_dibu*  b);
  /**
     Must free any state owned by this builder, including the builder
     object. It must not generate any output.
  */
  void (*finalize)(fsl_dibu* );
  /**
     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 called
     for both passes, including start() and finish().  Only finalize()
     and finally() are 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;
  /**
     Space for private, implementation-specific flags, e.g. for
     tracking basic output state, e.g. of opening/closing tags. This
     must not be modified by clients.
  */
  unsigned int pimplFlags;
  /**
     Space for implementation-specific flags which clients may set to
     modify the dibu's behaviour. This is different from
     fsl_dibu_opt::diffFlags in that these flags are specific to a
     given dibu type. See the fsl_dibu_impl_flags_e enum for the list
     of flags for the library-provided diff builders.
  */
  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.

     Maintenance reminder/TODO: we can't increment this from the main
     diff driver because... we possibly could, but we'd need to patch
     the various diff builders which currently do this themselves.
     The main diff driver doesn't have enough info to know when to set
     it, though. That "could" be done in this->finally() but that
     method is optional.
  */
  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;

  /**
     Metrics maintained by the core diff algorithm. These are updated
     during the first pass through a given fsl_diff_v2() run. They are
     NEVER reset by the builder algo because it cannot know if the
     user wants a running total or a per-file total. Clients running
     diffs in a loop may want to reset them on each loop. The simplest
     way is to cop fsl_dibu_empty.metrics over them. It is legal for a
     given builder to reset these in their start(), finish(), or
     finally() methods, depending on how the builder is used.

     Note that all metrics apply to the RHS version, not the LHS.
  */
  struct {
    /** Number of lines inserted performed so far. */
    uint32_t insertions;
    /** Number of lines deleted so far. */
    uint32_t deletions;
    /** Number of line-level edits performed so far. */
    uint32_t edits;
    /** Number of line replacements performed so far.
        These are different from edits in that the whole line
        differs in the LHS/RHS. */
    uint32_t replacements;
  } metrics;
};

/** Initialized-with-defaults fsl_dibu structure, intended for
    const-copy initialization. */
#define fsl_dibu_empty_m { \
  NULL/*opt*/,NULL/*typeID*/,                                         \
  NULL/*start()*/,NULL/*chunkHeader()*/,NULL/*skip()*/, NULL/*common()*/, \
  NULL/*insertion()*/,NULL/*deletion()*/, NULL/*replacement()*/, \
  NULL/*edit()*/, NULL/*finish()*/, NULL/*finally()*/,NULL/*finalize()*/, \
  false/*twoPass*/,0U/*passNumber*/, \
  NULL/*pimpl*/, 0U/*pimplFlags*/,0U/*implFlags*/,0U/*fileCount*/,         \
  0/*lnLHS*/,0/*lnRHS*/,                                              \
  {/*metrics*/0,0,0,0} \
}

/** Initialized-with-defaults fsl_dibu structure, intended for
    non-const copy initialization. */
extern const fsl_dibu fsl_dibu_empty;

/**
   Type IDs for use with fsl_dibu_factory().
*/
enum fsl_dibu_e {
/**
   Sentinel entry.
*/
FSL_DIBU_INVALID = 0,
/**
   A "dummy" diff builder intended only for testing the
   fsl_dibu interface and related APIs. It does not produce
   output which is generically useful.
*/
FSL_DIBU_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:

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

   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_DIBU_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_dibu_opt::diffFlags to disable that).

   Supported flags:

   - FSL_DIFF2_LINE_NUMBERS (makes it incompatible with patch(1))
   - FSL_DIFF2_NOINDEX
*/
FSL_DIBU_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.
*/
FSL_DIBU_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_DIBU_SPLIT_TEXT
};
typedef enum fsl_dibu_e fsl_dibu_e;

/**
   A factory for creating fsl_dibu 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_dibu_factory( fsl_dibu_e type,
                                 fsl_dibu **pOut );

/**
   Base allocator for fsl_dibu instances. If extra is >0 then
   that much extra space is allocated as part of the same memory block
   and the pimpl member of the returned object is pointed to that
   space. Example (OOM handling elided for legibility):

   ```
   struct MyState { int x; int y; };
   typedef struct MyState MyState;
   fsl_dibu * b = fsl_dibu_alloc(sizeof(MyState));
   MyState * my = (MyState*)b->pimpl;
   my->x = 1;
   my->y = 2;
   ... populate b's members ...
   ... use b, then clean it up ...
   b->finalize(b);
   ```

   From within b's methods, the custom state can be accessed via its
   `pimpl` member.

   @see fsl_dibu_finalizer()
*/
FSL_EXPORT fsl_dibu * fsl_dibu_alloc(fsl_size_t extra);

/**
   This is a generic finalizer function for use as a
   fsl_dibu::finalize() method. It simply zeroes out b and
   passes it fsl_free(). This is suitable for builders created using
   fsl_dibu_alloc() _only_ if their custom state manages no
   extra memory. If they manage any custom memory then the require a
   custom, type-specific finalizer method.
*/
FSL_EXPORT void fsl_dibu_finalizer(fsl_dibu *  b);

/**
   This counterpart of fsl_diff_text() defines its output format in
   terms of a fsl_dibu instance which the caller must provide.
   The caller is responsible for pointing pBuilder->opt to a
   configuration object suitable for the desired diff. In particular,
   pBuilder->opt->out and (if necessary) pBuilder->opt->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. This function has no error
   object, so it sets no error message: the caller reports the
   failure, naming the inputs.

   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->opt->diffFlags contains the FSL_DIFF2_NOTTOOBIG flag.

   - FSL_RC_DIFF_WS_ONLY if pBuilder->opt->diffFlags contains
   FSL_DIFF2_IGNORE_ALLWS and the inputs differ only in whitespace
   or are identical and non-empty. No output is generated in that
   case.

   - FSL_RC_MISUSE if pv1 or pv2 is NULL.

   - 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_dibu_factory()
   @see fsl_diff_text()
   @see fsl_diff_v2_raw()
*/
FSL_EXPORT int fsl_diff_v2(fsl_b const * pv1,
                           fsl_b const * pv2,
                           fsl_dibu *  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 may be NULL, in which case fsl_dibu_opt_empty is used.

   - 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_b const * pv1,
                               fsl_b const * pv2,
                               fsl_dibu_opt 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 and pOut is not modified. A field out of range
   (month 01-12, day 01-31, hour 00-24, minute and second 00-59) also
   makes it return false. The day is not checked against the month,
   so 2024-02-31 is accepted, as it is by fossil(1).

   This function does NOT confirm that zDate ends with a NUL
   byte. i.e.  if passed a valid date string which has trailing
   bytes after it then those are simply ignored. This is so that it
   can be used to read subsets of larger strings.

   Achtung: this calculation may, due to voodoo-level
   floating-point behaviours, differ by a small fraction of a point
   (at the millisecond level) for a given input compared to other
   implementations (e.g. sqlite's strftime() _might_ differ by a
   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 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 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 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
   underlying errno to one of the FSL_RC_xxx values, falling
   back to FSL_RC_IO if it cannot figure out anything more
   specific.
*/
FSL_EXPORT int fsl_chdir(const char *zChDir);

/**
   Works like fsl_chdir(zTo) but passes (zCurrent,nCurrent,NULL) to
   fsl_getcwd() to save the current dir name. Returns non-0 if either
   fsl_getcwd() or fsl_chdir() fails. To "pop" the dir just
   fsl_chdir() to zCurrent.
*/
FSL_EXPORT int fsl_chdir2(const char *zTo, char * zCurrent, fsl_size_t nCurrent);

/**
   A custom strftime() implementation.

   dest must be valid memory at least destLen bytes long. The result
   will be written there.

   fmt must contain the format string. See the source file strftime.c
   for the complete list of format specifiers and their descriptions.

   timeptr must be the time the caller wants to format.

   Returns 0 if any arguments are NULL.

   On success it returns the number of bytes written to dest, not
   counting the terminating NUL byte (which it also writes). It
   returns 0 on any error, and the client may need to distinguish
   between real errors and (destLen==0 or !*fmt), both of which could
   also look like errors.

   TODOs:

   - Refactor this to take a callback or a fsl_b, so that we can
   format arbitrarily long output.

   - Refactor it to return an integer error code.

   (This implementation is derived from public domain sources
   dating back to the early 1990's.)
*/
FSL_EXPORT fsl_size_t fsl_strftime(char *dest, fsl_size_t destLen,
                                   const char *format,
                                   const struct tm *timeptr);

/**
   A convenience form of fsl_strftime() which takes its timestamp in
   the form of a Unix Epoch time. See fsl_strftime() for the
   semantics of the first 3 arguments and the return value. If
   convertToLocal is true then epochTime gets converted to local
   time (via, oddly enough, localtime(3)), otherwise gmtime(3) is
   used for the conversion.
*/
FSL_EXPORT fsl_size_t fsl_strftime_unix(char * dest, fsl_size_t destLen,
                                        char const * format,
                                        fsl_time_t epochTime,
                                        bool convertToLocal);


/**
   A convenience form of fsl_strftime() which assumes that the
   formatted string is of "some reasonable size" and appends its
   formatted representation to b. Returns 0 on success, non-0 on
   error. If any argument is NULL or !*format then FSL_RC_MISUSE is
   returned. FSL_RC_RANGE is returned if the underlying call to
   fsl_strftime() fails (which it will if the format string
   resolves to something "unususually long"). It returns FSL_RC_OOM
   if appending to b fails due to an allocation error.
*/
FSL_EXPORT int fsl_b_strftime(fsl_b *  b,
                                   char const * format,
                                   const struct tm *timeptr);

/**
   "whence" values for use with fsl_b_seek(). They are analog to
   the "whence" argument of fseek(2) but are not guaranteed to have
   the same values.
*/
enum fsl_b_seek_e {
FSL_B_SEEK_SET = 1,
FSL_B_SEEK_CUR = 2,
FSL_B_SEEK_END = 3
};
typedef enum fsl_b_seek_e fsl_b_seek_e;

/**
   "Seeks" b's internal cursor to a position specified by the given offset
   from either the current cursor position (FSL_B_SEEK_CUR), the start
   of the buffer (FSL_B_SEEK_SET), or the end (FSL_B_SEEK_END).
   If the cursor would be placed out of bounds, it will be placed at the start
   resp. end of the buffer.

   The "end" of a buffer is the value of its fsl_b::used member,
   i.e. its one-after-the-end marker, as opposed to the at-the-end
   marker. That is: a seek to FSL_B_SEEK_END with an offset of -1
   would leave the cursor at the last available byte, not
   one-past-the-end.

   Returns the new position.

   Note that most buffer algorithms, e.g. fsl_b_append(), do not
   modify the cursor. Only certain special-case algorithms use it.

   @see fsl_b_tell()
   @see fsl_b_rewind()
*/
FSL_EXPORT fsl_size_t fsl_b_seek(fsl_b *  b, fsl_int_t offset,
                                      fsl_b_seek_e  whence);

/**
   Returns the buffer's current cursor position.

   @see fsl_b_rewind()
   @see fsl_b_seek()
*/
FSL_EXPORT fsl_size_t fsl_b_tell(fsl_b const * b);

/**
   Resets b's cursor to the beginning of the buffer.

   @see fsl_b_tell()
   @see fsl_b_seek()
*/
FSL_EXPORT void fsl_b_rewind(fsl_b *  b);

/**
   Read from buf until consuming a character matching delim, which must
   be representable as an unsigned char. The consumed bytes, including any
   matching delim character, are stored in *ret, and a terminating NUL
   added when the delimiter or end-of-buffer is encountered.

   If *retsz is non-zero, *ret must either be pre-allocated to at least
   *retsz bytes, or be a NULL pointer. *ret must be passable to fsl_free();
   it is grown as needed as if by fsl_realloc() and *retsz updated with
   its new size. It is the caller's responsiblity to fsl_free() *ret when
   it is no longer needed. Even on failure, *ret may be updated.

   Return the number of bytes read, including any matched delim character.
   If no bytes were read and the stream is at end-of-buffer, return -1.
   If an error occurs, return -1 and set buf->errCode to indicate the error.

   n.b. This routine matches getdelim(3) semantics. Callers must check
   buf->errCode to distinguish between end-of-buffer and error.
   https://pubs.opengroup.org/onlinepubs/9799919799/functions/getdelim.html

   Example:

   ```
   char *line = NULL;
   size_t sz = 0;
   ssize_t len;

   while ((len = fsl_b_getdelim(&line, &sz, '\n', &buf)) != -1)
     fprintf(stdout, "line (%ld bytes): %s\n", len, line);

   fsl_free(line);
   if (fsl_b_err(&buf))
     errx(buf.errCode, "fsl_b_getdelim: %s", fsl_rc_cstr(buf.errCode));
   ```

   @see fsl_b_getline()
*/
FSL_EXPORT fsl_int_t fsl_b_getdelim(char **ret, size_t *retsz,
                                         int delim, fsl_b *buf);

/**
   Equivalent to fsl_b_getdelim() with `delim` equal to '\n'.

   @see fsl_b_getdelim()
*/
FSL_EXPORT fsl_int_t fsl_b_getline(char **ret, size_t *retsz,
                                        fsl_b *buf);

/**
   The "Path Finder" class is a utility class for searching the
   filesystem for files matching a set of common prefixes and/or
   suffixes (i.e. directories and file extensions).

   Example usage:

   ```
   fsl_pathfinder pf = fsl_pathfinder_empty;
   int rc;
   char const * found = NULL;
   rc = fsl_pathfinder_ext_add( &pf, ".doc" );
   if(rc) { ...error... }
   // The following error checks are elided for readability:
   rc = fsl_pathfinder_ext_add( &pf, ".txt" );
   rc = fsl_pathfinder_ext_add( &pf, ".wri" );
   rc = fsl_pathfinder_dir_add( &pf, "." );
   rc = fsl_pathfinder_dir_add( &pf, "/my/doc/dir" );
   rc = fsl_pathfinder_dir_add( &pf, "/other/doc/dir" );

   rc = fsl_pathfinder_search( &pf, "MyDoc", &found, NULL);
   if(0==rc){ assert(NULL!=found); }

   // Eventually clean up:
   fsl_pathfinder_clear(&pf);
   ```

   @see fsl_pathfinder_dir_add()
   @see fsl_pathfinder_ext_add()
   @see fsl_pathfinder_clear()
   @see fsl_pathfinder_search()
*/
struct fsl_pathfinder {
  /**
     Holds the list of search extensions. Each entry
     is a (char *) owned by this object.
  */
  fsl_list ext;
  /**
     Holds the list of search directories. Each entry is a (char *)
     owned by this object.
  */
  fsl_list dirs;
  /**
     Used to build up a path string during fsl_pathfinder_search(),
     and holds the result of a successful search. We use a buffer,
     as opposed to a simple string, because (A) it simplifies the
     search implementation and (B) reduces allocations (it gets
     reused for each search).
  */
  fsl_b buf;
};

typedef struct fsl_pathfinder fsl_pathfinder;
/**
   Initialized-with-defaults fsl_pathfinder instance, intended for
   const copy initialization.
*/
#define fsl_pathfinder_empty_m {\
  .ext = fsl_list_empty_m,      \
  .dirs = fsl_list_empty_m,     \
  .buf = fsl_b_empty_m     \
}

/**
   Initialized-with-defaults fsl_pathfinder instance, intended for
   copy initialization.
*/
FSL_EXPORT const fsl_pathfinder fsl_pathfinder_empty;

/**
   Frees all memory associated with pf, but does not free pf.
   Is a no-op if pf is NULL.
*/
FSL_EXPORT void fsl_pathfinder_clear(fsl_pathfinder *  pf);

/**
   Equivalent to fsl_pathfinder_dir_add2() with -1 as a final
   argument.

   @see fsl_pathfinder_ext_add()
   @see fsl_pathfinder_search()
*/
FSL_EXPORT int fsl_pathfinder_dir_add(fsl_pathfinder *  pf,
                                      char const * dir);

/**
   Adds the given directory to pf's search path. Returns 0 on
   success, FSL_RC_MISUSE if !pf or !dir (dir _may_ be an empty
   string), FSL_RC_OOM if copying the string or adding it to the
   list fails.

   If strLen is negative, fsl_strlen() is used to calculate the length
   of the string.

   @see fsl_pathfinder_ext_add()
   @see fsl_pathfinder_search()
*/
FSL_EXPORT int fsl_pathfinder_dir_add2(fsl_pathfinder *  pf, char const * dir,
                                       fsl_int_t strLen);

/**
   Adds the given directory to pf's search extensions. Returns 0 on
   success, FSL_RC_MISUSE if !pf or !dir (dir _may_ be an empty
   string), FSL_RC_OOM if copying the string or adding it to the
   list fails.

   Note that the client is responsible for adding a "." to the
   extension, if needed, as this API does not apply any special
   meaning to any characters in a search extension. e.g. "-journal"
   and "~" are both perfectly valid extensions for this purpose.

   @see fsl_pathfinder_dir_add()
   @see fsl_pathfinder_search()
*/
FSL_EXPORT int fsl_pathfinder_ext_add2(fsl_pathfinder *  pf, char const * ext,
                                       fsl_int_t strLen);

/**
   Equivalent to fsl_pathfinder_ext_add2() with -1 as a final
   argument.

   @see fsl_pathfinder_dir_add()
   @see fsl_pathfinder_search()
*/
FSL_EXPORT int fsl_pathfinder_ext_add(fsl_pathfinder *  pf,
                                      char const * ext);

/**
   Splits a conventional path-separator-delimited string into tokens
   and adds each as either a directory (if isDirs is true) or an
   extension in the given fsl_pathfinder object. Returns 0 on success,
   FSL_RC_OOM on allocation error. pathLen is the length of the path
   string. If it's negative, fsl_strlen() is used to calculate it.

   See fsl_path_splitter for the semantics of the splitting.
*/
FSL_EXPORT int fsl_pathfinder_split( fsl_pathfinder *  tgt,
                                     bool isDirs,
                                     char const * path,
                                     fsl_int_t pathLen );

/**
   Searches for a file whose name can be constructed by some
   combination of pf's directory/extension lists and the given base
   name.

   It searches for files in the following manner:

   If the 2nd parameter exists as-is in the filesystem, it is
   treated as a match, otherwise... Loop over all directories
   in pf->dirs. Create a path with DIR/base, or just base if
   the dir entry is empty (length of 0). Check for a match.
   If none is found, then... Loop over each extension in
   pf->ext, creating a path named DIR/baseEXT (note that it
   does not add any sort of separator between the base and the
   extensions, so "~" and "-foo" are legal extensions). Check
   for a match.

   On success (a readable filesystem entry is found):

   - It returns 0.

   - If pOut is not NULL then `*pOut` is set to the NUL-terminated
     path it found. The bytes of the returned string are only valid
     until the next search operation on pf, so copy them if you need
     them.  Note that the returned path is _not_ normalized via
     fsl_file_canonical_name() or similar, and it may very well return
     a relative path (if base or one of pf->dirs contains a relative
     path part). As a special case, if `base` is found as-is, without
     a lookup, `*pOut` is set to `base`, so has its lifetime.

   - If outLen is not NULL, *outLen will be set to the length of the
     returned string.

   On error:

   - Returns FSL_RC_MISUSE if !pf, !base, !*base.

   - Returns FSL_RC_OOM on allocation error (it uses a buffer to hold
     its path combinations and return value).

   - Returns FSL_RC_NOT_FOUND if it finds no entry.

   The host platform's customary path separator is used to separate
   directory/file parts ('\\' on Windows and '/' everywhere else).

   Note that it _is_ legal for pOut and outLen to both be NULL, in
   which case a return of 0 signals that an entry was found, but the
   client has no way of knowing what path it might be (unless, of
   course, they rely on internal details of the fsl_pathfinder API,
   which they most certainly should not do).

   Tip: if the client wants to be certain that this function will not
   allocate memory, simply use fsl_b_reserve() on pf->buf to
   reserve the desired amount of space in advance. As long as the
   search paths never surpass that length, this function will not need
   to allocate. (Until/unless the following TODO is implemented...)

   Potential TODO: use fsl_file_canonical_name() so that the search
   dirs themselves do not need to be entered using
   platform-specific separators. The main reason it's not done now
   is that it requires another allocation. The secondary reason is
   because it's sometimes useful to use relative paths in this
   context (based on usage in previous trees from which this code
   derives).

   @see fsl_pathfinder_dir_add()
   @see fsl_pathfinder_ext_add()
   @see fsl_pathfinder_clear()
*/
FSL_EXPORT int fsl_pathfinder_search(fsl_pathfinder *  pf,
                                     char const * base,
                                     char const ** pOut,
                                     fsl_size_t *  outLen );


/**
   A utility class for creating ZIP-format archives. All members
   are internal details and must not be mucked about with by the
   client. See fsl_zip_file_add() for an example of how to use it.

   Note that it creates ZIP content in memory, as opposed to
   streaming it (it is not yet certain if abstractly streaming a
   ZIP is possible), so creating a ZIP file this way is exceedingly
   memory-hungry.

   @see fsl_zip_file_add()
   @see fsl_zip_timestamp_set_julian()
   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_end()
   @see fsl_zip_body()
   @see fsl_zip_finalize()
*/
struct fsl_zip_writer {
  /**
     Number of entries (files + dirs) added to the zip file so far.
  */
  fsl_size_t entryCount;
  /**
     Current DOS-format time of the ZIP.
  */
  int32_t dosTime;
  /**
     Current DOS-format date of the ZIP.
  */
  int32_t dosDate;
  /**
     Current Unix Epoch time of the ZIP.
  */
  fsl_time_t unixTime;
  /**
     An artificial root directory which gets prefixed
     to all inserted filenames.
  */
  char * rootDir;
  /**
     The buffer for the table of contents.
  */
  fsl_b toc;
  /**
     The buffer for the ZIP file body.
  */
  fsl_b body;
  /**
     Internal scratchpad for ops which often allocate
     small buffers.
  */
  fsl_b scratch;
  /**
     The current list of directory entries (as (char *)).
  */
  fsl_list dirs;
};
typedef struct fsl_zip_writer fsl_zip_writer;

/**
   An initialized-with-defaults fsl_zip_writer instance, intended
   for in-struct or const-copy initialization.
*/
#define fsl_zip_writer_empty_m {                \
  0/*entryCount*/,                            \
  0/*dosTime*/,                             \
  0/*dosDate*/,                             \
  0/*unixTime*/,                            \
  NULL/*rootDir*/,                          \
  fsl_b_empty_m/*toc*/,                \
  fsl_b_empty_m/*body*/,               \
  fsl_b_empty_m/*scratch*/,            \
  fsl_list_empty_m/*dirs*/                  \
}

/**
   An initialized-with-defaults fsl_zip_writer instance,
   intended for copy-initialization.
*/
FSL_EXPORT const fsl_zip_writer fsl_zip_writer_empty;

/**
   Sets a virtual root directory in z, such that all files added
   with fsl_zip_file_add() will get this directory prefixed to
   it.

   If zRoot is NULL or empty then this clears the virtual root,
   otherwise is injects any directory levels it needs to into the
   being-generated ZIP. Note that zRoot may contain multiple levels of
   directories, e.g. "foo/bar/baz", but it must be legal for use in a
   ZIP file.

   This routine copies zRoot's bytes, so they may be transient.

   Returns 0 on success, FSL_RC_MISUSE if !z, FSL_RC_OOM on
   allocation error. Returns FSL_RC_RANGE if zRoot is an absolute
   path or if zRoot cannot be normalized to a "simplified name" (as
   per fsl_is_simple_pathname(), with the note that this routine
   will pass a copy of zRoot through fsl_file_simplify_name()
   first).

   @see fsl_zip_finalize()
*/
FSL_EXPORT int fsl_zip_root_set(fsl_zip_writer *  z,
                                char const * zRoot );

/**
   Adds a file or directory to the ZIP writer z. zFilename is the
   virtual name of the file or directory. If pContent is NULL then
   it is assumed that we are creating one or more directories,
   otherwise the ZIP's entry is populated from pContent. The
   permsFlag argument specifies the fossil-specific permission
   flags from the fsl_fileperm_e enum, but currently ignores the
   permsFlag argument for directories. Not that this function
   creates directory entries for any files automatically, so there
   is rarely a need for client code to create them (unless they
   specifically want to ZIP an empty directory entry).

   Notes of potential interest:

   - The ZIP is created in memory, and thus creating ZIPs with this
   API is exceedingly memory-hungry.

   - The timestamp of any given file must be set separately from
   this call using fsl_zip_timestamp_set_unix() or
   fsl_zip_timestamp_set_julian(). That value is then used for
   subsequent file-adds until a new time is set.

   - If a root directory has been set using fsl_zip_root_set() then
   that name, plus '/' (if the root does not end with one) gets
   prepended to all files added via this routine.

   - The ZIP is written without the zip64 extensions, so this
   returns FSL_RC_RANGE for content larger than 4GiB minus one byte,
   a name longer than 65535 bytes, or an archive which has grown
   past 4GiB.

   Returns 0 on success, FSL_RC_OOM on allocation error, or
   FSL_RC_RANGE as described above. z has no error message state,
   so the caller reports the failure.

   An example of the ZIP-generation process:

   ```
   int rc;
   fsl_zip_writer z = fsl_zip_writer_empty;
   fsl_b buf = fsl_b_empty;
   fsl_b const * zipBody;

   // ...fill the buf buffer (not shown here)...

   // Optionally set a virtual root dir for new files:
   rc = fsl_zip_root_set( &z, "myRootDir" ); // trailing slash is optional
   if(rc) { ... error ...; goto end; }

   // We must set a timestamp which will be used until we set another:
   fsl_zip_timestamp_set_unix( &z, time(NULL) );

   // Add a file:
   rc = fsl_zip_file_add( &z, "foo/bar.txt", &buf, FSL_FILE_PERM_REGULAR );
   // Clean up our content:
   fsl_b_reuse(&buf); // only needed if we want to re-use the buffer's memory
   if(rc) goto end;

   // ... add more files the same way (not shown) ...

   // Now "seal" the ZIP file:
   rc = fsl_zip_end( &z );
   if(rc) goto end;

   // Fetch the ZIP content:
   zipBody = fsl_zip_body( &z );
   // zipBody now points to zipBody->used bytes of ZIP file content
   // which can be sent to an arbitrary destination, e.g.:
   rc = fsl_b_to_filename( zipBody, "my.zip" );

   end:
   fsl_b_clear(&buf);
   // VERY important, once we're done with z:
   fsl_zip_finalize( &z );
   if(rc){...we had an error...}
   ```

   @see fsl_zip_timestamp_set_julian()
   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_end()
   @see fsl_zip_body()
   @see fsl_zip_finalize()
*/
FSL_EXPORT int fsl_zip_file_add( fsl_zip_writer *  z,
                                 char const * zFilename,
                                 fsl_b const * pContent,
                                 int permsFlag );

/**
   Ends the ZIP-creation process, padding all buffers, writing all
   final required values, and freeing up most of the memory owned
   by z. After calling this, z->body contains the full generated
   ZIP file.

   Returns 0 on success, FSL_RC_OOM on allocation error, or
   FSL_RC_RANGE if z holds more than 65535 entries or its central
   directory would start beyond 4GiB, limits of the ZIP format
   without the zip64 extensions. On error z's
   contents may still be partially intact (for debugging purposes)
   and z->body will not hold complete/valid ZIP file contents. Results are undefined if
   !z or z has not been properly initialized.

   The caller must eventually pass z to fsl_zip_finalize() to free
   up any remaining resources.

   @see fsl_zip_timestamp_set_julian()
   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_file_add()
   @see fsl_zip_body()
   @see fsl_zip_finalize()
   @see fsl_zip_end_take()
*/
FSL_EXPORT int fsl_zip_end( fsl_zip_writer *  z );

/**
   This variant of fsl_zip_end() transfers the current contents
   of the zip's body to dest, replacing (freeing) any contents it may
   hold when this is called, then passes z to fsl_zip_finalize()
   to free any other resources (which are invalidated by the removal
   of the body).

   Returns 0 on success, FSL_RC_MISUSE if either pointer is NULL,
   some non-0 code if the proxied fsl_zip_end() call fails. On
   error, the transfer of contents to dest does NOT take place, but
   z is finalized (if it is not NULL) regardless of success or
   failure (even if dest is NULL). i.e. on error z is still cleaned
   up.
*/
FSL_EXPORT int fsl_zip_end_take( fsl_zip_writer *  z,
                                 fsl_b *  dest );

/**
   This variant of fsl_zip_end_take() passes z to fsl_zip_end(),
   write's the ZIP body to the given filename, passes
   z to fsl_zip_finalize(), and returns the result of
   either end/save combination. Saving is not attempted
   if ending the ZIP fails.

   On success 0 is returned and the contents of the ZIP are in the
   given file. On error z is STILL cleaned up, and the file might
   have been partially populated (only on I/O error after writing
   started). In either case, z is cleaned up and ready for re-use or
   (in the case of a heap-allocated instance) freed.
*/
FSL_EXPORT int fsl_zip_end_to_filename( fsl_zip_writer *  z,
                                        char const * filename );


/**
   Returns a pointer to z's ZIP content buffer. The contents are ONLY
   valid after fsl_zip_end() returns 0.

   @see fsl_zip_timestamp_set_julian()
   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_file_add()
   @see fsl_zip_end()
   @see fsl_zip_end_take()
   @see fsl_zip_finalize()
*/
FSL_EXPORT fsl_b const * fsl_zip_body( fsl_zip_writer const * z );

/**
   Frees all memory owned by z and resets it to a clean state, but
   does not free z. Any fsl_zip_writer instance which has been
   modified via the fsl_zip_xxx() family of functions MUST
   eventually be passed to this function to clean up any contents
   it might have accumulated during its life. After this returns,
   z is legal for re-use in creating a new ZIP archive.

   @see fsl_zip_timestamp_set_julian()
   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_file_add()
   @see fsl_zip_end()
   @see fsl_zip_body()
*/
FSL_EXPORT void fsl_zip_finalize(fsl_zip_writer *  z);

/**
   Set z's date and time from a Julian Day number. Results are
   undefined if !z. Results will be invalid if rDate is negative. The
   timestamp is applied to all fsl_zip_file_add() operations until it
   is re-set.

   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_file_add()
   @see fsl_zip_end()
   @see fsl_zip_body()
*/
FSL_EXPORT void fsl_zip_timestamp_set_julian(fsl_zip_writer *  z,
                                             double rDate);

/**
   Set z's date and time from a Unix Epoch time. Results are
   undefined if !z. Results will be invalid if rDate is negative. The
   timestamp is applied to all fsl_zip_file_add() operations until it
   is re-set.
*/
FSL_EXPORT void fsl_zip_timestamp_set_unix(fsl_zip_writer *  z,
                                           fsl_time_t epochTime);

/**
   State for the fsl_timer_xxx() family of functions.

   Achtung: timer support is only enabled if the library is built with
   the proper clock support. Windows builds mostly support it
   automatically (all except wall clock time) and non-Windows builds
   do if the library is built with HAVE_CLOCK_GETTIME (for
   clock_gettime(2)) and HAVE_GETRUSAGE (for getrusage(2)) both set to
   true values. That said: the library currently _assumes_ that
   non-Windows builds have both of those POSIX-2008 functions. On
   Windows, building with HAVE_CLOCK_GETTIME is necessary only for
   fsl_timer::wall.

   Example usage:

   ```
   fsl_timer tTotal = fsl_timer_empty;
   fsl_timer tRun;
   fsl_timer_start(&tRun);
   ... do some work ...
   fsl_timer_add(&tRun, &tTotal);
   ```

   After that, `tTotal` contains the microseconds of time which
   elapsed between the time `tRun` was started and the time
   fsl_timer_add() was called.

   @see fsl_timer_start()
   @see fsl_timer_fetch()
   @see fsl_timer_add()
   @see fsl_timer_stop()
*/
struct fsl_timer {
  /**
     The amount of time (microseconds) spent in "user space".
  */
  uint64_t user;

  /**
     The amount of time (microseconds) spent in "kernel space".
  */
  uint64_t system;

  /**
     The microseconds of "wall clock" time. Only available if built
     with HAVE_CLOCK_GETTIME. (Patches for a Windows alternative would
     be welcomed.)
  */
  uint64_t wall;
};
typedef struct fsl_timer fsl_timer;

/**
   Initialized-with-defaults fsl_timer instance,
   intended for const copy initialization.
*/
#define fsl_timer_empty_m {.user=0,.system=0,.wall=0}

/**
   Initialized-with-defaults fsl_timer instance,
   intended for non-const copy initialization.
*/
FSL_EXPORT const fsl_timer fsl_timer_empty;

/**
   Sets t's counter state to the current CPU timer usage, as
   determined by the OS. It is legal to pass an uninitialized instance
   to this function, as this function will fully populate it.

   @see fsl_timer_fetch()
   @see fsl_timer_add()
*/
FSL_EXPORT void fsl_timer_start(fsl_timer *  t);

/**
   Sets each of pUser, pSys, and pWall to the number of
   microseconds which have elapsed since t was passed
   to fsl_timer_start().
*/
FSL_EXPORT void fsl_timer_fetch(fsl_timer const * t,
                                uint64_t * pUser, uint64_t * pSys,
                                uint64_t * pWall);

/**
   Captures the current time and adds the difference of tStart and
   the current time to tgt's members. Intended for
   keeping track of interruptable running times.

   Example usage:

   ```
   fsl_timer timerTotal = fsl_timer_empty; // copy init is important
   fsl_timer timerWork;                    // here it's not

   fsl_timer_start(&timerWork);
   ... do some timed work...
   fsl_timer_add(&timerWork, &timerTotal);

   ... do some non-timed work ...

   fsl_timer_start(&timerWork);
   ... do some timed work...
   fsl_timer_add(&timerWork, &timerTotal);
   ```

   The end result will be that timerTotal holds the accumulated times
   between each start/add invocation.
*/
FSL_EXPORT void fsl_timer_add(fsl_timer const * tStart,
                                fsl_timer *  tgt);

/**
   Returns the difference in _CPU_ times in microseconds since t was
   last passed to fsl_timer_start() or fsl_timer_reset().  It might
   return 0 due to system-level precision restrictions. Note that this
   is not useful for measuring wall times.
*/
FSL_EXPORT uint64_t fsl_timer_cpu(fsl_timer const * t);

/**
   Resets t's state to contain relative times by subtracting its
   starting time from the current time. Returns the post-adjustment
   (t->system+t->user).

   @see fsl_timer_start()
   @see fsl_timer_reset()
*/
FSL_EXPORT uint64_t fsl_timer_stop(fsl_timer *  t);

/**
   A convenience macro for timing a block of code (BODY) with the
   fsl_timer API. TGT is a (fsl_timer*) object which must initially
   start out zeroed out (e.g. initialied by copying from
   fsl_timer_empty or fsl_timer_empty_m). SUFFIX is a unique-per-scope
   name suffix for a scope-local temporary fsl_timer object, so must
   be suitable as the suffix of a C identifier. The run-time of BODY
   is fsl_timer_add()'d to (fsl_timer*) TGT.

   Example usage:

   ```
   fsl_timer_scope3(__COUNTER__,&myTimer,{
     ... your code to time ...
   });
   ```

   For compilers which do not like `__COUNTER__`, just use any
   identifier suffix which is unique to the call scope, e.g. an
   integer.
*/
#define fsl_timer_scope3(SUFFIX,TGT,BODY)  \
  fsl_timer _tm ## SUFFIX;                 \
  fsl_timer_start(&_tm ## SUFFIX);         \
  BODY;                                    \
  fsl_timer_add(&_tm ## SUFFIX, TGT)

/**
   Convenience form of fsl_timer_scope3() which uses __COUNTER__ as
   its 2nd argument. Note that __COUNTER__ is a C extension but is
   believed to be supported on all modern (as of 2025) C compilers.
*/
#define fsl_timer_scope(TGT,BODY) \
  fsl_timer_scope3(__COUNTER__,TGT,BODY)


/**
   For the given red/green/blue values (all in the range of 0 to
   255, or truncated to be so!) this function returns the RGB
   encoded in the lower 24 bits of a single number. See
   fsl_gradient_color() for an explanation and example.

   For those asking themselves, "why does an SCM API have a function
   for encoding RGB colors?" the answer is: fossil(1) has a long
   history of using HTML color codes to set the color of branches,
   and this is provided in support of such features.

   @see fsl_rgb_decode()
   @see fsl_gradient_color()
*/
FSL_EXPORT unsigned int fsl_rgb_encode( int r, int g, int b );

/**
   Given an RGB-encoded source value, this function decodes
   the lower 24 bits into r, g, and b. Any of r, g, and b may
   be NULL to skip over decoding of that part.

   @see fsl_rgb_encode()
   @see fsl_gradient_color()
*/
FSL_EXPORT void fsl_rgb_decode( unsigned int src, int *r, int *g, int *b );

/**
   For two color values encoded as RRGGBB values (see below for the
   structure), this function computes a gradient somewhere between
   those colors. c1 and c2 are the edges of the gradient.
   numberOfSteps is the number of steps in the gradient. stepNumber
   is a number less than numberOfSteps which specifies the "degree"
   of the gradients. If either numberOfSteps or stepNumber is 0, c1
   is returned. stepNumber of equal to or greater than c2 returns
   c2.

   The return value is an RGB-encoded value in the lower 24 bits,
   ordered in big-endian. In other words, assuming rc is the return
   value:

   - red   = (rc&0xFF0000)>>16
   - green = (rc&0xFF00)>>8
   - blue  = (rc&0xFF)

   Or use fsl_rgb_decode() to break it into its component parts.

   It can be passed directly to a printf-like function, using the
   hex-integer format specifier, e.g.:

   ```
   fsl_b_appendf(&myBuf, "#%06x", rc);
   ```

   Tip: for a given HTML RRGGBB value, its C representation is
   identical: HTML \#F0D0A0 is 0xF0D0A0 in C.

   @see fsl_rgb_encode()
   @see fsl_rgb_decode()
*/
FSL_EXPORT unsigned int fsl_gradient_color(unsigned int c1, unsigned int c2,
                                           unsigned int numberOfSteps,
                                           unsigned int stepNumber);

/**
   "Simplifies" an SQL string by making the following modifications
   inline:

   - Consecutive non-newline spaces outside of an SQL string are
   collapsed into one space.

   - Consecutive newlines outside of an SQL string are collapsed into
   one space.

   Contents of SQL strings are not transformed in any way.

   len must be the length of the sql string. If it is negative,
   fsl_strlen(sql) is used to calculate the length.

   Returns the number of bytes in the modified string (its strlen) and
   NUL-terminates it at the new length. Thus the input string must be
   at least one byte longer than its virtual length (its NUL
   terminator byte suffices, provided it is NUL-terminated, as we can
   safely overwrite that byte).

   If !sql or its length resolves to 0, this function returns 0
   without side effects.
*/
FSL_EXPORT fsl_size_t fsl_simplify_sql( char * sql, fsl_strlen_t len );

/**
   Convenience form of fsl_simplify_sql() which assumes b holds an SQL
   string. It gets processed by fsl_simplify_sql() and its 'used'
   length potentially gets adjusted to match the adjusted SQL string.
*/
FSL_EXPORT fsl_size_t fsl_simplify_sql_buffer( fsl_b *  b );

/**
   Returns the result of calling the platform's equivalent of
   isatty(fd). e.g. on Windows this is _isatty() and on Unix
   isatty(). i.e. it returns true if it thinks that the given file
   descriptor value is attached to an interactive terminal, else it
   returns false.

   The standard file descriptors are: 0=stdin, 1=stdout, and 2=stderr.
*/
FSL_EXPORT bool fsl_isatty(int fd);

/**
   A container type for lists of db record IDs. This is used in
   several places as a cache for record IDs, to keep track of ones
   we know about, ones we know that we don't know about, and to
   avoid duplicate processing in some contexts.

   This container does not support modification during traversal and
   has undefined behavior in such cases.
*/
struct fsl_id_bag {
  /**
     Number of entries of this->list which are in use (have a
     positive value). They need not be contiguous!  Must be <=
     capacity.
  */
  fsl_size_t entryCount;
  /**
     The number of elements allocated for this->list.
  */
  fsl_size_t capacity;
  /**
     The number of elements in this->list which have a zero or
     positive value. Must be <= capacity.
  */
  fsl_size_t used;
  /**
     Array of IDs this->capacity elements long. "Used" elements
     have a positive value. Unused ones are set to 0.
  */
  fsl_id_t * list;
};

/**
   Initialized-with-defaults fsl_id_bag structure,
   intended for copy initialization.
*/
FSL_EXPORT const fsl_id_bag fsl_id_bag_empty;

/**
   Initialized-with-defaults fsl_id_bag structure,
   intended for in-struct initialization.
*/
#define fsl_id_bag_empty_m {      \
  .entryCount = 0, .capacity = 0, \
  .used = 0, .list = NULL         \
}

/**

   Return the number of elements in the bag.
*/
FSL_EXPORT fsl_size_t fsl_id_bag_count(fsl_id_bag const * p);

/**

   Remove element e from the bag if it exists in the bag. If e is not
   in the bag, this is a no-op. Returns true if it removes an element,
   else false.

   e must be positive. Results are undefined if e<=0.
*/
FSL_EXPORT bool fsl_id_bag_remove(fsl_id_bag *  p, fsl_id_t e);

/**
   Returns true if e is in the given bag. Returns false if it is
   not. It is illegal to pass an e value of 0, and that will trigger
   an assertion in debug builds. In non-debug builds, behaviour if
   passed 0 is undefined.
*/
FSL_EXPORT bool fsl_id_bag_contains(fsl_id_bag const * p, fsl_id_t e);

/**
   Insert element e into the bag if it is not there already.  Returns
   0 if it actually inserts something or if it already contains such
   an entry, and some other value on error (namely FSL_RC_OOM on
   allocation error).

   e must be positive or an assertion is triggered in debug builds. In
   non-debug builds, behaviour is undefined if passed 0.
*/
FSL_EXPORT int fsl_id_bag_insert(fsl_id_bag *  p, fsl_id_t e);

/**
   Returns the ID of the first element in the bag.  Returns 0 if the
   bag is empty.

   ```
   fsl_id_t rid = fsl_id_bag_first(debag);
   int rc = 0;
   for( ; !rc && rid>0; rid = fsl_id_bag_next(debag, rid) ){
     rc = ...;
   }
   ```

*/
FSL_EXPORT fsl_id_t fsl_id_bag_first(fsl_id_bag const * p);

/**
   Returns the next element in the bag after e.  Return 0 if e is
   the last element in the bag.  Any insert or removal from the bag
   might reorder the bag. It is illegal to pass this 0 (and will
   trigger an assertion in debug builds). For the first call, pass
   it the non-0 return value from fsl_id_bag_first(). For
   subsequent calls, pass the previous return value from this
   function.

   @see fsl_id_bag_first()
*/
FSL_EXPORT fsl_id_t fsl_id_bag_next(fsl_id_bag const * p, fsl_id_t e);

/**
   Swaps the contents of the given bags.
*/
FSL_EXPORT void fsl_id_bag_swap(fsl_id_bag *  lhs, fsl_id_bag *  rhs);

/**
   Copies all entries from src into dest. Returns 0 on success,
   FSL_RC_OOM on allocation error.

   An alternative approach: if dest is empty then
   fsl_id_bag_swap(src,dest), perhaps followed by
   fsl_id_bag_clear(src) or fsl_id_bag_reuse(src), is more efficient
   (does not allocate).
*/
FSL_EXPORT int fsl_id_bag_copy(fsl_id_bag const * src, fsl_id_bag * dest);

/**
   Frees any memory owned by p, but does not free p.
*/
FSL_EXPORT void fsl_id_bag_clear(fsl_id_bag *  p);

/**
   Resets p's internal list, effectively emptying it for re-use, but
   does not free its memory. Immediately after calling this
   fsl_id_bag_count() will return 0. Returns p.
*/
FSL_EXPORT fsl_id_bag * fsl_id_bag_reuse(fsl_id_bag *  p);

/** @deprecated

   Older (deprecated) name of fsl_id_bag_reuse().
*/
#define fsl_id_bag_reset fsl_id_bag_reuse

/**
   Return true if p contains a merge marker on a line by itself, else
   returns false.

   @see fsl_b_merge3()
*/
FSL_EXPORT bool fsl_b_contains_merge_marker(fsl_b const *p);

/**
   Performs a three-way merge.

   The merge is an edit against pV2. Both pV1 and pV2 have a common
   origin at pPivot. Apply the changes of pPivot ==> pV1 to pV2,
   appending them to pOut. (Pedantic side-note: the input buffers are
   not const because we need to manipulate their cursors, but their
   buffered memory is not modified.)

   If merge conflicts are encountered, it continues as best as it can
   and injects "indiscrete" markers in the output to denote the nature
   of each conflict. If conflictCount is not NULL then on success the
   number of merge conflicts is written to *conflictCount.

   Returns 0 on success, FSL_RC_OOM on OOM, FSL_RC_DIFF_BINARY if any
   input appears to be binary.

   @see fsl_b_contains_merge_marker()
*/
FSL_EXPORT int fsl_b_merge3(fsl_b *  pPivot,
                                 fsl_b *  pV1,
                                 fsl_b *  pV2,
                                 fsl_b *  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.

   If fsl_b_err() is true for the given buffer, that code is
   returned without other side effects.

   If the 2nd argument is true, squiggly braces within the string are
   escaped, else they are not. Whether that's required or not depends
   on how the resulting TCL will be used. If it will be eval'd directly,
   it must be escaped. If it will be read as a file and tokenized, it
   needn't be.
 */
FSL_EXPORT int fsl_b_append_tcl_literal(fsl_b *  b,
                                             bool escapeSquigglies,
                                             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
   prompt a user for a response. To that end, the interface passes on
   2 pieces of information to the client: the event ID and a filename.
   It is up to the application to translate that ID into a
   user-readable form, get a response (using a well-defined set of
   response IDs), and convey that back to the
   library via the callback's result pointer interface.

   This enum will be extended as the library develops new requirements
   for interactive use.

   @see fsl_confirm_response_e
*/
enum fsl_confirm_event_e {
/**
   Sentinal value.
*/
FSL_CEVENT_INVALID = 0,
/**
   An operation requests permission to overwrite a locally-modified
   file. e.g. when performing a checkout over a locally-edited
   version. Overwrites of files which are known to be in the previous
   (being-overwritten) checkout version are automatically overwritten.
*/
FSL_CEVENT_OVERWRITE_MOD_FILE = 1,
/**
   An operation requests permission to overwrite an SCM-unmanaged file
   with one which is managed by SCM. This can happen, e.g., when
   switching from a version which did not contain file X, but had file
   X on disk, to a version which contains file X.
*/
FSL_CEVENT_OVERWRITE_UNMGD_FILE = 2,
/**
   An operation requests permission to remove a LOCALLY-MODIFIED file
   which has been removed from SCM management. e.g. when performing a
   checkout over a locally-edited version and an edited file was
   removed from the SCM somewhere between those two versions.
   UMODIFIED files which are removed from the SCM between two
   checkouts are automatically removed on the grounds that it poses no
   data loss risk because the other version is "somewhere" in the SCM.
*/
FSL_CEVENT_RM_MOD_UNMGD_FILE = 3,

/**
   Indicates that the library cannot determine which of multiple
   potential versions to choose from and requires the user to
   select one.
*/
FSL_CEVENT_MULTIPLE_VERSIONS = 4

};
typedef enum fsl_confirm_event_e fsl_confirm_event_e;

/**
   Answers to questions posed to clients via the
   fsl_confirm_callback_f() interface.

   This enum will be extended as the library develops new requirements
   for interactive use.

   @see fsl_confirm_event_e
*/
enum fsl_confirm_response_e {
/**
   Sentinel/default value - not a valid answer. Guaranteed to have a
   value of 0. No other entries in this enum are guaranteed to have
   well-known/stable values: always use the enum symbols instead of
   integer values.
*/
FSL_CRESPONSE_INVALID = 0,
/**
   Accept the current event and continue processes.
*/
FSL_CRESPONSE_YES = 1,
/**
   Reject the current event and continue processes.
*/
FSL_CRESPONSE_NO = 2,
/**
   Reject the current event and stop processesing. Cancellation is
   generally considered to be a recoverable error.
*/
FSL_CRESPONSE_CANCEL = 3,
/**
   Accept the current event and all identical event types for the
   current invocation of this particular SCM operation.
*/
FSL_CRESPONSE_ALWAYS = 5,
/**
   Reject the current event and all identical event types for the
   current invocation of this particular SCM operation.
*/
FSL_CRESPONSE_NEVER = 6,
/**
   For events which are documented as being multiple-choice,
   this answer indicates that the client has set the index of
   their choice in the fsl_confirm_response::multipleChoice
   field:

   - FSL_CEVENT_MULTIPLE_VERSIONS
*/
FSL_CRESPONSE_MULTI = 7
};
typedef enum fsl_confirm_response_e fsl_confirm_response_e;

/**
   A response for use with the fsl_confirmer API. It is intended to
   encapsulate, with a great deal of abstraction, answers to typical
   questions which the library may need to interactively query a user
   for. e.g. confirmation about whether to overwrite a file or which
   one of 3 versions to select.

   This type will be extended as the library develops new requirements
   for interactive use.
*/
struct fsl_confirm_response {
  /**
     Client response to the current fsl_confirmer question.
  */
  fsl_confirm_response_e response;
  /**
     If this->response is FSL_CRESPONSE_MULTI then this must be set to
     the index of the client's multiple-choice answer.

     Events which except this in their response:

     - FSL_CEVENT_MULTIPLE_VERSIONS
  */
  uint16_t multipleChoice;
};
/**
   Convenience typedef.
*/
typedef struct fsl_confirm_response fsl_confirm_response;

/**
   Empty-initialized fsl_confirm_detail instance to be used for
   const copy initialization.
*/
#define fsl_confirm_response_empty_m {FSL_CRESPONSE_INVALID, -1}

/**
   Empty-initialized fsl_confirm_detail instance to be used for
   non-const copy initialization.
*/
FSL_EXPORT const fsl_confirm_response fsl_confirm_response_empty;

/**
   A struct for passing on interactive questions to
   fsl_confirmer_callback_f implementations.
*/
struct fsl_confirm_detail {
  /**
     The message ID of this confirmation request. This value
     determines how the rest of this struct's values are to
     be interpreted.
  */
  fsl_confirm_event_e eventId;
  /**
     Depending on the eventId, this might be NULL or might refer to a
     filename. This will be a filename for following confirmations
     events:

     - FSL_CEVENT_OVERWRITE_MOD_FILE
     - FSL_CEVENT_OVERWRITE_UNMGD_FILE
     - FSL_CEVENT_RM_MOD_UNMGD_FILE

     For all others it will be NULL.

     Whether this name refers to an absolute or relative path is
     context-dependent, and not specified by this API. In general,
     relative paths should be used if/when what they are relative to
     (e.g. a checkout root) is/should be clear to the user. The intent
     is that applications can display that name to the user in a UI
     control, so absolute paths "should" "generally" be avoided
     because they can be arbitrarily long.
  */
  const char * filename;
  /**
     Depending on the eventId, this might be NULL or might
     refer to a list of details of a type specified in the
     documentation for that eventId.

     Implementation of such an event is still TODO, but we have at
     least one use case lined up (asking a user which of several
     versions is intended when the checkout-update operation is given
     an ambiguous hash prefix).

     Events for which this list will be populated:

     - FSL_CEVENT_MULTIPLE_VERSIONS: each list entry will be a (char
     const*) with a version number, branch name, or similar, perhaps
     with relevant metadata such as a checkin timestamp. The client is
     expected to pick one answer, set its list index to the
     fsl_confirm_response::multipleChoice member, and to set
     fsl_confirm_response::response to FSL_CRESPONSE_MULTI.

     In all cases, a response of FSL_CRESPONSE_CANCEL will trigger a
     cancellation.

     In all cases, the memory for the items in this list is owned by
     (or temporarily operated on the behalf of) the routine which has
     launched this query. fsl_confirm_callback_f implements must never
     manipulate the list's or its content's state.
  */
  const fsl_list * multi;
};
typedef struct fsl_confirm_detail fsl_confirm_detail;

/**
   Empty-initialized fsl_confirm_detail instance to be used for
   const-copy initialization.
*/
#define fsl_confirm_detail_empty_m \
  {FSL_CEVENT_INVALID, NULL, NULL}

/**
   Empty-initialized fsl_confirm_detail instance to be used for
   non-const-copy initialization.
*/
FSL_EXPORT const fsl_confirm_detail fsl_confirm_detail_empty;

/**
   Should present the user (if appropriate) with an option of how to
   handle the given event write that answer to
   outAnswer->response. Return 0 on success, non-0 on error, in which
   case the current operation will fail with that result code.
   Answering with FSL_CRESPONSE_CANCEL is also considered failure but
   recoverably so, whereas a non-cancel failure is considered
   unrecoverable.
*/
typedef int (*fsl_confirm_callback_f)(fsl_confirm_detail const * detail,
                                      fsl_confirm_response *outAnswer,
                                      void * confirmerState);

/**
   A fsl_confirm_callback_f and its callback state, packaged into a
   neat little struct for easy copy/replace/restore of confirmers.
*/
struct fsl_confirmer {
  /**
     Callback which can be used for basic interactive confirmation
     purposes, within the very libfossil-centric limits of the
     interface.
  */
  fsl_confirm_callback_f callback;
  /**
     Opaque state pointer for this->callback. Its lifetime is not
     managed by this object and it is assumed, if not NULL, to live at
     least as long as this object.
  */
  void * callbackState;
};
typedef struct fsl_confirmer fsl_confirmer;
/** Empty-initialized fsl_confirmer instance for const-copy
    initialization. */
#define fsl_confirmer_empty_m {NULL,NULL}
/** Empty-initialized fsl_confirmer instance for non-const-copy
    initialization. */
FSL_EXPORT const fsl_confirmer fsl_confirmer_empty;

/**
   State for use with fsl_dircrawl_f() callbacks.

   @see fsl_dircrawl()
*/
struct fsl_dircrawl_state {
  /**
     Absolute directory name of the being-visited directory.
  */
  char const *absoluteDir;
  /**
     Name (no path part) of the entry being visited.
  */
  char const *entryName;
  /**
     Filesystem entry type.
  */
  fsl_fstat_type_e entryType;
  /**
     Opaque client-specified pointer which was passed to
     fsl_dircrawl().
  */
  void * callbackState;

  /**
     Directory depth of the crawl process, starting at 1 with
     the directory passed to fsl_dircrawl().
  */
  unsigned int depth;
};
typedef struct fsl_dircrawl_state fsl_dircrawl_state;

/**
   Callback type for use with fsl_dircrawl(). Its argument contains
   all crawling-relevant state for entry being visited.

   Implementations must return 0 on success or another FSL_RC_xxx
   value on error.

   Special return values:

   - FSL_RC_BREAK will cause directory-crawling to stop without an
     error (returning 0).

   - Returning FSL_RC_NOOP will cause recursion into a directory to
     be skipped, but traversal to otherwise continue.

   All pointers in the state argument are owned by fsl_dircrawl() and
   will be invalidated as soon as the callback returns, thus they must
   be copied if they are needed for later.
*/
typedef int (*fsl_dircrawl_f)(fsl_dircrawl_state const *);

/**
   Recurses into a directory and calls a callback for each filesystem
   entry.  It does not change working directories, but callbacks are
   free to do so as long as they restore the working directory before
   returning.

   The first argument is the name of the directory to crawl. In order
   to avoid any dependence on a specific working directory, if it is
   not an absolute path then this function will expand it to an
   absolute path before crawling begins. For each entry under the
   given directory, it calls the given callback, passing it a
   fsl_dircrawl_state object holding various state. All pointers in
   that object, except for the callbackState pointer, are owned by
   this function and may be invalidated as soon as the callback
   returns.

   For each directory entry, it recurses into that directory,
   depth-first _after_ passing it to the callback.

   It DOES NOT resolve/follow symlinks, instead passing them on to the
   callback for processing. Note that passing a symlink to this
   function will not work because this function does not resolve
   symlinks. Thus it provides no way to traverse symlinks, as its
   scope is only features suited for the SCM and symlinks have no
   business being in an SCM. (Fossil supports symlinks, more or less,
   but libfossil does not.)

   It silently skips any files for which stat() fails or is not of a
   "basic" file type (e.g. character devices and such).

   Returns 0 on success, FSL_RC_TYPE if the given name is not a
   directory, and FSL_RC_RANGE if it recurses "too deep," (some
   "reasonable" internally hard-coded limit), in order to help avoid a
   stack overflow.

   If the callback returns non-0, iteration stops and returns that
   result code unless the result is FSL_RC_BREAK or FSL_RC_NOOP, with
   those codes being treated specially, as documented for
   fsl_dircrawl_f() callbacks.
*/
FSL_EXPORT int fsl_dircrawl(char const * dirName, fsl_dircrawl_f callback,
                            void * callbackState);

/**
   Strips any trailing slashes ('/') from the given string by
   assigning those bytes to NUL and returns the number of slashes
   NUL'd out. nameLen must be the length of the string. If nameLen is
   negative, fsl_strlen() is used to calculate its length.
*/
FSL_EXPORT fsl_size_t fsl_strip_trailing_slashes(char * name, fsl_int_t nameLen);

/**
   A convenience from of fsl_strip_trailing_slashes() which strips
   trailing slashes from the given buffer and changes its b->used
   value to account for any stripping. Results are undefined if b is
   not properly initialized.

   If b is an external buffer, this routine materializes it and strips
   it on success. On materialization error b->errCode will be non-0.
*/
FSL_EXPORT void fsl_b_strip_slashes(fsl_b *  b);

/**
   Edits b in-place, stripping out any hash-style single-line comments
   and adjusting b->used.

   If b is an external buffer then this is a no-op but a potential
   TODO is have it materialize the buffer in that case and return an
   int (FSL_RC_OOM on OOM).
*/
FSL_EXPORT void fsl_b_strip_hash_comments(fsl_b * b);

/**
   Appends each ID from the given bag to the given buffer using the given
   separator string. Returns FSL_RC_OOM on allocation error.

   If fsl_b_err() is true for the given buffer, that code is
   returned without other side effects.
*/
FSL_EXPORT int fsl_id_bag_to_buffer(fsl_id_bag const * bag,
                                    fsl_b *  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 false.
*/
FSL_EXPORT bool fsl_looks_like_binary(fsl_b 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_b 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_b 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_b const * b, unsigned int *pBomSize);

/**
   Returns true if b starts with a UTF-8 byte-order mark (EF BB BF) or
   a UTF-16 one (FF FE or FE FF).
*/
FSL_EXPORT bool fsl_b_has_bom(fsl_b const * b);

/**
   Converts b in place to UTF-8 with no byte-order mark, as fossil(1)
   does with the inputs to diff and annotate:

   - A UTF-8 byte-order mark is removed.
   - Text that starts with a UTF-16 byte-order mark, in either byte
     order, is converted to UTF-8. Surrogate pairs become characters
     above U+FFFF, and an unpaired surrogate becomes U+FFFD.
   - Anything else is left unchanged.

   Returns 0 on success or FSL_RC_OOM if allocation fails, in which
   case b is unchanged.
*/
FSL_EXPORT int fsl_b_to_utf8_no_bom(fsl_b * b);

/**
   Populates the first n bytes of tgt with random bytes. Note that n
   must be 31 bits or less (2GB). The exact source of randomness is
   not guaranteed by the API, but the implementation currently uses
   sqlite3_randomness().
*/
FSL_EXPORT void fsl_randomness(unsigned int n, void *tgt);


/**
   Given a filename and its length, this function returns a pointer to
   the last instance of a path separator character in that string,
   checking for both `/` and `\\`. If the length is negative,
   fsl_strlen() is used to calculate it. If no separator is found,
   NULL is returned.
*/
FSL_EXPORT char const * fsl_last_path_sep(char const * str, fsl_int_t slen );

/**
   A helper type for tokenizing conventional PATH-style strings.
   Initialize them with fsl_path_splitter_init() and iterate over them
   with fsl_path_splitter_next().
*/
struct fsl_path_splitter {
  /** Begining of the input range. */
  char const * begin;
  /** One-after-the-end of the input range. */
  char const * end;
  /** Position for the next token lookup. */
  char const * pos;
  /** List of token separator characters (ASCII only). */
  char const * separators;
};
typedef struct fsl_path_splitter fsl_path_splitter;
/** @def fsl_path_splitter_empty_m

   Default-initialized fsl_path_splitter instance, intended for const-copy
   initialization. On Windows builds its separators member is set to
   ";" and on other platforms it's set to ":;".
*/
#if FSL_PLATFORM_IS_WINDOWS
#  define fsl_path_splitter_empty_m {NULL,NULL,NULL,";"}
#else
#  define fsl_path_splitter_empty_m {NULL,NULL,NULL,":;"}
#endif

/**
   Default-initialized fsl_path_splitter instance, intended for
   copy initialization.

   @see fsl_path_splitter_empty_m
*/
FSL_EXPORT const fsl_path_splitter fsl_path_splitter_empty;

/**
   Wipes out pt's current state by copying fsl_path_splitter_empty
   over it and initializes pt to use the given path as its input. If
   len is 0 or more then it must be the length of the string, in
   bytes. If len is less than 0, fsl_strlen() is used to determine the
   path's length.  (When dealing with inputs which are not
   NUL-terminated, it's critical that the user pass the correct
   non-negative length.)

   If the client wants to modify pt->separators, it must be done
   *after* calling this.

   Use fsl_path_splitter_next() to iterate over the path entries.
*/
void fsl_path_splitter_init( fsl_path_splitter *  pt, char const * path,
                             fsl_int_t len );

/**
   Given a fsl_path_splitter which was formerly initialized using
   fsl_path_splitter_init(), this iterates over the next-available
   path component in the input, skipping over empty entries (leading,
   consecutive, or trailing separator characters).

   The separator characters are specified by pt->separators, which must
   be a NUL-terminated string of 1 or more characters.

   If a non-empty entry is found then:

   - *token is set to the first byte of the entry.

   - *len is assigned to the byte length of the entry.

   If no entry is found then:

   - *token, and *len are not modified.

   - FSL_RC_NOT_FOUND is returned if the end of the path was found
   while tokenizing.

   - FSL_RC_MISUSE is returned if pt->separators is NULL or empty or
   contains any non-ASCII characters.

   - FSL_RC_RANGE is returned if called after the previous case, or
   if the input object's path has a length of 0.

   In any non-0-return case, it's not a fatal error, it's simply
   information about why tokenization cannot continue, and can
   normally be ignored. After non-0 is returned, the tokenizer must be
   re-initialized if it is to be used again.

   Example:

   @code
   char const * t = 0;
   fsl_size_t tLen = 0;
   fsl_path_splitter pt = fsl_path_splitter_empty;
   fsl_path_splitter_init(&pt, path, pathLen);
   while(0==fsl_path_splitter_next(&pt, &t, &tLen)){
      // The next element is the tLen bytes of memory starting at t:
      printf("Path element: %.*s\n", (int)tLen, t);
   }
   @endcode
*/
int fsl_path_splitter_next( fsl_path_splitter *  pt, char const ** token,
                            fsl_size_t *  len );

/**
   Implements a cross-platform system(3) interface. It passes its
   argument, which must not be NULL or empty, to the equivalent of
   system(3). Returns 0 if that call returns 0, else it will return a
   FSL_RC code approximating the lower-level error code (noting that
   this system's man pages are a bit vague on the exact return
   semantics of system(3)). If it cannot convert an errno value to an
   approximate FSL_RC value, it will return FSL_RC_ERROR.
*/
int fsl_system(const char *zOrigCmd);

typedef struct fsl_url fsl_url;

/**
   A type for parsing URLs. Its memory is managed by fsl_url_parse()
   and fsl_url_cleanup().
*/
struct fsl_url {
  /** The raw, unparsed URL. */
  char const * raw;
  /** The URL's scheme, in lower case. */
  char const * scheme;
  /** The URL's username, with %XX escapes decoded, or NULL. */
  char const * username;
  /** The URL's username's password, with %XX escapes decoded, or
      NULL. */
  char const * password;
  /** The remote host name, with %XX escapes decoded, or an IP literal
      with its brackets, such as "[::1]". Is only NULL for file
      URLs. */
  char const * host;
  /** The :portNumber part or 0. */
  uint16_t port;
  /** The path. For file URLs, this is where the file's name is
      stored, with %XX escapes decoded when the URL has an explicit
      "file:" scheme. */
  char const * path;
  /** The query string, including the '?' prefix. */
  char const * query;
  /** The fragment part, including the '#' prefix. */
  char const * fragment;

  /**
     Private implementation details. fsl_url_parse() allocates this
     buffer a single time and points the other members into the memory
     owned by impl.b. Its approximate allocated size is a handful of
     bytes more than twice the strlen() of this->raw.
  */
  struct { fsl_b b; } impl;
};

/** Initialized-with-defaults fsl_url structure, intended for
    const-copy initialization. */
#define fsl_url_empty_m {                        \
    .raw=0, .scheme=0, .username=0, .password=0, \
    .host=0, .port=0, .path=0, .query=0,         \
    .fragment=0, .impl = {.b=fsl_b_empty_m} \
}

/** Initialized-with-defaults fsl_url structure, intended for
    non-const copy initialization. */
extern const fsl_url fsl_url_empty;

/**
   Attempts to parse zUrl as a URL, filling out u with the
   results.

   It passes u to fsl_url_cleanup2(), with a false 2nd argument,
   before starting.

   Results are undefined if zUrl is NULL.

   On success, returns 0 and populates u. On error, returns
   FSL_RC_OOM, FSL_RC_SYNTAX, or FSL_RC_MISUSE (if zUrl is NULL or
   empty), and it passes u to fsl_url_cleanup() before returning.

   All memory referenced by u's members is invalidated by any of
   the fsl_url APIs. Do not hold copies of pointers to a fsl_url
   member for later use.

   For each missing component of the URL, the corresponding member of
   u will be NULL. A missing port is designated by 0, and a port value
   ouside of the range (1..65535) triggers a syntax error.

   Quirks:

   - It may mis-parse malformed URLs.

   - It does no unescaping of the string. It "could" provide the query
     string in an unescaped form but that would require some
     refactoring.

   - file URLs (in this API) do not support a host name, port, query
     string, or fragment. Everything after the scheme is available via
     u->path.

   - zUrl may be a filesystem path, starting with either '/' or '.',
     in which case it is treated as if it were prefixed with
     "file://".

   - file:/X and file:///X both resolve to /X. file://X, though
     technically illegal[^1] resolves to X.

   - It does not recognize Windows drive letters as such. A URL in the
     form "file:/c:/..." or "file:///c:/..." will be assigned a
     u->path of "/c:/...", and "file:c:/..." will have a u->path of
     "c:/...". In non-file URLs, a drive letter will very probably be
     treated like a hostname with an invalid port (so will fail to
     parse).

   [^1]: https://en.wikipedia.org/wiki/File_URI_scheme
*/
FSL_EXPORT int fsl_url_parse(fsl_url * u, char const * zUrl);

/**
   Flags for use with fsl_url_render().
*/
enum fsl_url_render_e {

  /** Elide the scheme:// prefix. */
  FSL_URL_RENDER_NO_SCHEME = 0x01,

  /** Elide the user name and password. */
  FSL_URL_RENDER_NO_USER = 1<<1,

  /** Elide any password part of the URL. */
  FSL_URL_RENDER_NO_PASSWORD = 1<<2,

  /**
     Render any password part of the URL as some unspecified number of
     "*" characters.
  */
  FSL_URL_RENDER_MASK_PASSWORD = 1<<3,

  /** Elide the query string and fragment. */
  FSL_URL_RENDER_NO_QUERY = 1<<4,

  /** Elide the fragment. */
  FSL_URL_RENDER_NO_FRAGMENT = 1<<5
};

/**
   Appends a rendering of the given parsed url object to the given
   buffer.  The final argument can be used to modify how the rendering
   is done.

   Returns pOut->errCode. If pOut->errCode is non-0 when this is
   called, this call is a no-op.
*/
FSL_EXPORT int fsl_url_render(fsl_url const * u, fsl_b * pOut,
                              fsl_flag32_t flags);

/**
   Equivalent to fsl_url_cleanup2(u, true).
*/
FSL_EXPORT void fsl_url_cleanup(fsl_url * u);

/**
   Frees all memory owned by u, and zeroes it out, but does not free
   u.  If freeBuffer is false then u's internal buffer is also freed
   otherwise it is retained, which will lead to a leak if u is not
   later either passed to fsl_url_cleanup() or to this function with a
   true freeBuffer value.
*/
FSL_EXPORT void fsl_url_cleanup2(fsl_url * u, bool freeBuffer);

/**
   Swaps the contents of the given objects.
*/
FSL_EXPORT void fsl_url_swap(fsl_url * lhs, fsl_url *rhs);

/**
   Parses key-value pairs from u->query. On the initial call, the
   second argument should be a pointer to a call-local NULL value.

   If this returns true:

   - It will have replaced bKey's contents with the
     next query string key, and bVal's contents to its value (if any).

   - It sets `*zCursor` to the next parse position. The intent is that
     the caller pass the same pointer to each call until this function
     returns false.

   It returns false if:

   - No more URL args are found.
   - An allocation error while appending to bKey or bVal.

   Regardless of success or failure, it calls fsl_b_reuse() on
   its output buffers before beginning work.

   The query string is assumed to be URL-encoded and the parsed-out
   keys and values get URL-decoded when adding them to the output
   buffers.

   Example:

   ```
   fsl_b key = fsl_b_empty;
   fsl_b val = fsl_b_empty;
   char const * zTail = 0;
   while( fsl_url_next_query_arg(myUrl, &zTail, &key, &val) ){
     // key holds the key and val might hold a value
     // (else it will be empty)
   }
   fsl_b_clear(&key);
   fsl_b_clear(&val);
   ```

   That example ignores alloc errors which happen during parsing but
   for completeness one should check key.errCode and val.errCode,
   either of which might be FSL_RC_OOM.
*/
FSL_EXPORT bool fsl_url_next_query_arg(fsl_url const * u,
                                       char const **zCursor,
                                       fsl_b * bKey,
                                       fsl_b * bVal);

/**
   Converts the first nBytes bytes from pBytes to hex form, writing
   the result to pOut. pOut must have at least 2*nBytes+1 bytes of
   space, as this function writes 2*nBytes of hex and a NUL
   terminator to it.
*/
FSL_EXPORT void fsl_to_hex(unsigned char const *pBytes,
                           fsl_size_t nBytes, char *pOut);

/**
   Searches for the given word in the given Tcl-style "enum": a list
   of words.

   nWord is the byte length of word, or negative to use fsl_nstrlen().

   nList has two forms: if it's negative then aList MUST be terminated
   with a NULL entry and this function will stop at that entry. If
   nList is positive, aList is assumed to have that many valid,
   non-NULL entries.

   On a match it returns the index of the match.  On no match, returns
   a negative value.

   This is an O(N) scan. It's intended for application-level command
   dispatching, not for use in hot loops. We're assured by those who
   know better that for nList approx. 16-32 this is every bit as
   performant as a binary search would be on all modern systems.
*/
FSL_EXPORT int fsl_enum_search(char const *word, fsl_strlen_t nWord,
                               char const * const *aList, fsl_int_t nList);



#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 does 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_b 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_b 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_b 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/util.h */
/* start of file include/fossil-scm/core.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_CORE_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_CORE_H_INCLUDED
/*
  Copyright 2013-2025 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

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

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

#include <stdbool.h>

/** @file core.h

  This file declares the core SCM-related public APIs.
*/

#include <time.h> /* struct tm, time_t */
#if defined(__cplusplus)
/**
  The fsl namespace is reserved for an eventual C++ wrapper for the API.
*/
namespace fsl {}
extern "C" {
#endif

/**
    An internal helper macro to help localize OOM error reports (which
    are most often side effects of other issues, rather than being
    real OOM cases). It's intended to be used like:

    ```
    void * someAllocedMemory = fsl_malloc(...); // any allocating routine
    if(!someAllocedMemory){
      fsl_report_oom;
      rc = FSL_RC_OOM;
      goto end;
    }
    ```

    or:

    ```
    if(FSL_RC_OOM==fs){ fsl_report_oom; }
    ```

    Note that this macro _may_ expand to encompass multiple commands
    so must never be used as the RHS of an `if` without squiggly
    braces surrounding it (as in the above example).

    This macro is _not_ invoked in _every_ possible OOM case, so
    cannot simply be replaced with abort() to kill the app on OOM.
    For that, apply a custom allocator via fsl_lib_configurable.
*/
#if !defined(fsl_report_oom_impl)
#define fsl_report_oom_impl \
  fprintf(stderr,"OOM @ %s:%d\n", __FILE__, __LINE__)
#endif

/* older name fos fsl_report_oom */
#define FSL__WARN_OOM fsl_report_oom_impl
#define fsl_report_oom fsl_report_oom_impl
#if defined(FSL_DEBUG_CHECK_OOM_RC)
#define fsl_check_oom_rc(RC) if(FSL_RC_OOM==(RC)){fsl_report_oom;}(void)0
#else
#define fsl_check_oom_rc(RC) (void)0
#endif

/**
   @struct fsl_cx

   The main Fossil "context" type. This is the first argument to
   many Fossil library API routines, and holds all state related
   to a checkout and/or repository and/or global fossil configuration
   database(s).

   An instance's lifetime looks something like this:

   ```
   int rc;
   fsl_cx * f = NULL; // ALWAYS initialize to NULL or results are undefined
   rc = fsl_cx_init( &f, NULL );
   assert(!rc);
   rc = fsl_repo_open( f, "myrepo.fsl" );
   ...use the context, and clean up when done...
   fsl_cx_finalize(f);
   ```

   The contents of an fsl_cx instance are strictly private, for use
   only by APIs in this library. Any client-side dependencies on
   them will lead to undefined behaviour at some point.
*/
typedef struct fsl_cx_config fsl_cx_config;
typedef struct fsl_db fsl_db;
typedef struct fsl_stmt fsl_stmt;
//typedef struct fsl__cx fsl_cx;
typedef struct fsl_cx fsl_cx;

/**
   This enum defines type ID tags with which the API tags fsl_db
   instances so that the library can figure out which DB is
   which. This is primarily important for certain queries, which
   need to know whether they are accessing the repo or config db,
   for example.

   As of 2021-10, the fossil context db model has long been, and is
   very, very likely to remain:

   - When a context starts up, it creates a temporary db for use
     as its `main` db.

   - When a repo or checkout db are opened, they are `ATTACH`ed to the
     main db with the names `repo` resp. `ckout`. (Note that those
     differ from the names fossil(1) uses: `repository` and
     `localdb`.)

   A large amount of the library code is written _as if_ the library
   (roughly) followed fossil's model of using separate sqlite3
   objects, even though it does not do so. The reason is historical:
   when starting the libfossil port, it was clear that fossil's
   internal connection juggling was going to be painful for the
   library, so the internal API was shaped to permit two separate
   approaches:

   Approach 1: the first db which gets opened (repo, checkout, or
   config) becomes the `main` db and all others get attached using
   their API-standard alias. That is _mostly_ what fossil does, but it
   leads to fossil sometimes having to "swap" connections by closing
   the db and re-opening it so that the db names are in a state which
   fits the current use. That model led to the creation of this
   enum. However, it also leads to unpredictable database names for
   purposes of queries, as we're never sure (at the client level or
   higher library-level APIs) which db is `main` and which has an
   alias.

   Approach 2: open a temp (or in-memory) db and attach all of the
   others to that using well-defined names.

   The latter has proven to work well enough that returning to the
   first approach seems _extremely_ unlikely at this point. Thus some
   newer library-level code behaves as if the latter model is in effect
   (which it is).

   The long and the short of the above diversion is that APIs like
   fsl_cx_db_repo() and fsl_cx_db_ckout() will always return the same
   database handle, but they can tell whether a given role has been
   attached or not and will fail in their documented ways when the
   role's corresponding database has not yet been attached. e.g.
   `fsl_cx_db_repo()` will return `NULL` if a repo database is not
   attached.

   @see fsl_db_role_name()
   @see fsl_cx_db_file_for_role()
*/
enum fsl_dbrole_e {
/**
   Sentinel "no role" value.
*/
FSL_DBROLE_NONE = 0,
/**
   The global (per user) config db. Analog to fossil's "configdb".
*/
FSL_DBROLE_CONFIG = 0x01,
/**
   The repository db. Analog to fossil's "repository".
*/
FSL_DBROLE_REPO = 0x02,
/**
   The checkout db. Analog to fossil's "localdb".
*/
FSL_DBROLE_CKOUT = 0x04,
/**
   Analog to fossil's "main", which is an alias for the first db
   opened. In this API a fsl_cx instance has a temporary/transient
   main db opened even if it does not have a repository, checkout, or
   config db opened.
*/
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.

   It seems very unlikely that these will ever be used at the level of
   this library. They are a "porting artifact" and retained for the
   time being, but will very likely be removed.
*/
enum fsl_configset_e {
/** Sentinel value. */
FSL_CONFSET_NONE = 0x000000,
/** Style sheet only */
FSL_CONFIGSET_CSS = 0x000001,
/** WWW interface appearance */
FSL_CONFIGSET_SKIN = 0x000002,
/** Ticket configuration */
FSL_CONFIGSET_TKT = 0x000004,
/** Project name */
FSL_CONFIGSET_PROJ = 0x000008,
/** Shun settings */
FSL_CONFIGSET_SHUN = 0x000010,
/** The USER table */
FSL_CONFIGSET_USER = 0x000020,
/** The CONCEALED table */
FSL_CONFIGSET_ADDR = 0x000040,
/** Transfer configuration */
FSL_CONFIGSET_XFER = 0x000080,
/** Everything */
FSL_CONFIGSET_ALL = 0x0000ff,
/** Causes overwrite instead of merge */
FSL_CONFIGSET_OVERWRITE = 0x100000,
/** Use the legacy format */
FSL_CONFIGSET_OLDFORMAT = 0x200000
};
typedef enum fsl_configset_e fsl_configset_e;

/**
   Runtime-configurable flags for a fsl_cx instance.

   @see fsl_cx_flag_set()
   @see fsl_cx_flags_get()
*/
enum fsl_cx_flags_e {
/**
   The "no flags" value. Guaranteed to be 0 and this is the only entry
   in this enum which is guaranteed to have a stable value.
*/
FSL_CX_F_NONE = 0,
/**
   Tells us whether or not we want to calculate R-cards by default.
   Historically they were initially required but eventually made
   optional due largely to their memory costs.
*/
FSL_CX_F_CALC_R_CARD = 0x01,

/**
   When encounting artifact types in the crosslinking phase which
   the library does not currently support crosslinking for, skip over
   them instead of generating an error. For day-to-day use this is,
   perhaps counter-intuitively, generally desirable.

   As of 2021-12-04, crosslinking of all core fossil artifact types is
   supported, so this flag is effectively a no-op until/unless a new
   artifact type is added to fossil.
*/
FSL_CX_F_SKIP_UNKNOWN_CROSSLINKS = 0x02,

/**
   By default, fsl_reserved_fn_check() will fail if the given filename
   is reserved on Windows platforms because such filenames cannot be
   checked out on Windows.  This flag removes that limitation. It
   should only be used, if at all, for repositories which will _never_
   be used on Windows.
*/
FSL_CX_F_ALLOW_WINDOWS_RESERVED_NAMES = 0x04,

/**
   If on (the default) then an internal cache will be used for
   artifact loading to speed up operations which do lots of that.
   Disabling this will save memory but may hurt performance for
   certain operations.
*/
FSL_CX_F_MANIFEST_CACHE = 0x08,

/**
   If on (the default) then fsl_content_get() will use an internal
   cache to speed up loading of repeatedly-fetched artifacts.
   Disabling this can be costly.
*/
FSL_CX_F_BLOB_CACHE = 0x10,

/**
   Internal use only to prevent duplicate initialization of some
   bits.
*/
FSL_CX_F_IS_OPENING_CKOUT = 0x100,

/**
   Default flags for all fsl_cx instances.
*/
FSL_CX_F_DEFAULTS = FSL_CX_F_MANIFEST_CACHE | FSL_CX_F_BLOB_CACHE

};
typedef enum fsl_cx_flags_e fsl_cx_flags_e;

/**
    List of hash policy values. New repositories should generally use
    only SHA3 hashes, but older repos may contain SHA1 hashes (perhaps
    only SHA1), so we have to support those. Repositories may contain
    a mix of hash types.

    Maintenance ACHTUNG: this enum's values must align with those from
    fossil(1) because their integer values are used in the
    `repo.config` table.
*/
enum fsl_hashpolicy_e {
/** Use only SHA1 hashes. */
FSL_HPOLICY_SHA1 = 0,
/** Accept SHA1 hashes but auto-promote to SHA3. */
FSL_HPOLICY_AUTO = 1,
/** Use SHA3 hashes. */
FSL_HPOLICY_SHA3 = 2,
/** Use SHA3 hashes exclusively. */
FSL_HPOLICY_SHA3_ONLY = 3,
/** With this policy, fsl_uuid_is_shunned() will always return true
    for SHA1 hashes, making it "impossible" to get SHA1-hashed content
    into the repository (for a given value of "impossible"). */
FSL_HPOLICY_SHUN_SHA1 = 4
};
typedef enum fsl_hashpolicy_e fsl_hashpolicy_e;


/**
   A macro which invokes its argument (a macro name) to expand to all
   possible values of fsl_rc_e entries. The macro name passed to it is
   invoked once for each entry and passed 3 arguments: the enum
   entry's full name (FSL_RC_...), its integer value, and a help-text
   string.
*/
#define fsl_rc_e_map(E) \
  E(FSL_RC_OK, 0, \
    "The quintessential not-an-error value.")    \
  E(FSL_RC_ERROR, 100, \
    "Generic/unknown error.")                                           \
  E(FSL_RC_NYI, 101, \
    "A placeholder return value for not yet implemented functions.")    \
  E(FSL_RC_OOM, 102, \
    "Out of memory. Indicates that a resource allocation request failed.") \
  E(FSL_RC_MISUSE, 103, \
    "API misuse (invalid args).")                                       \
  E(FSL_RC_RANGE, 104, \
    "Some range was violated (function argument, UTF character, etc.).") \
  E(FSL_RC_ACCESS, 105, \
    "Indicates that access to or locking of a resource was denied "     \
    "by some security mechanism or other.")                             \
  E(FSL_RC_IO, 106, \
    "Indicates an I/O error. Whether it was reading or "                \
    "writing is context-dependent.")                                    \
  E(FSL_RC_NOT_FOUND, 107, \
    "Requested resource not found")                                     \
  E(FSL_RC_ALREADY_EXISTS, 108,                                         \
    "Indicates that a to-be-created resource already exists.")          \
  E(FSL_RC_CONSISTENCY, 109, \
    "Data consistency problem")                                         \
  E(FSL_RC_REPO_NEEDS_REBUILD, 110,                                     \
    "Indicates that the requested repo needs to be rebuilt.")           \
  E(FSL_RC_NOT_A_REPO, 111,                                             \
    "Indicates that the requested repo is not, in fact, a repo. "       \
    "Also used by some APIs to indicate that they require a "           \
    "repository db but none has been opened.")                          \
  E(FSL_RC_REPO_VERSION, 112,                                           \
    "Indicates an attempt to open a too-old or too-new repository db.") \
  E(FSL_RC_DB, 113, \
    "Indicates db-level error (e.g. statement prep failed). In such "   \
    "cases, the error state of the related db handle (fsl_db) or "      \
    "Fossil context (fsl_cx) will be updated to contain more "          \
    "information directly from the db driver.")                         \
  E(FSL_RC_BREAK, 114, \
    "Used by some iteration routines to indicate that "                 \
    "iteration should stop prematurely without an error.")              \
  E(FSL_RC_STEP_ROW, 115, \
    "Indicates that fsl_stmt_step() has fetched a row and "             \
    "the cursor may be used to access the current row state (e.g. using " \
    "fsl_stmt_get_int32() and friends). It is strictly illegal to use " \
    "the fsl_stmt_get_xxx() APIs unless fsl_stmt_step() has returned "  \
    "this code.")                                                       \
  E(FSL_RC_STEP_DONE, 116, \
    "Indicates that fsl_stmt_step() has reached the end of "            \
    "the result set and that there is no row data to process. This is also the " \
    "result for non-fetching queries (INSERT and friends). It is strictly " \
    "illegal to use the fsl_stmt_get_xxx() APIs after fsl_stmt_step() has " \
    "returned this code.")                                              \
  E(FSL_RC_STEP_ERROR, 117, \
    "Indicates that a db-level error occurred "                         \
    "during a fsl_stmt_step() iteration.")                              \
  E(FSL_RC_TYPE, 118,                                                   \
    "Indicates that some data type or logical type is incorrect "       \
    "(e.g. an invalid card type in conjunction with a given fsl_deck).") \
  E(FSL_RC_NOT_A_CKOUT, 119,                                            \
    "Indicates that an operation which requires a checkout does not "   \
    "have a checkout to work on.")                                      \
  E(FSL_RC_REPO_MISMATCH, 120, \
    "Indicates that a repo and checkout do not belong together.")       \
  E(FSL_RC_CHECKSUM_MISMATCH, 121,                                      \
    "Indicates that a checksum comparison failed, possibly indicating " \
    "that corrupted or unexpected data was just read.")                 \
  E(FSL_RC_LOCKED, 122, \
    "Indicates a resource-locking error of some sort, normally a db lock.") \
  E(FSL_RC_CONFLICT, 123,                                               \
    "Indicates that a merge conflict, or some other context-dependent " \
    "type of conflict, was detected.")                                  \
  E(FSL_RC_UNKNOWN_RESOURCE, 124, \
    "This is a special case of FSL_RC_NOT_FOUND, intended specifically " \
    "to differentiate from \"file not found in filesystem\" " \
    "(FSL_RC_NOT_FOUND) and \"fossil does not know about this file\" in " \
    "routines for which both might be an error case. An example is a " \
    "an operation which wants to update a repo file with contents " \
    "from the filesystem - the file might not exist or it might not be " \
    "in the current repo db. " \
    "That said, this can also be used for APIs which search for other " \
    "resources (UUIDs, tickets, etc.), but FSL_RC_NOT_FOUND is already " \
    "fairly well entrenched in those cases and is unambiguous, so this " \
    "code is only needed by APIs for which both cases described above " \
     "might happen." ) \
  E(FSL_RC_SIZE_MISMATCH, 125, \
    "Indicates that a size comparison check failed. " \
    "TODO: remove this if it is not used." )          \
  E(FSL_RC_DELTA_INVALID_SEPARATOR, 126, \
    "Indicates that an invalid separator was encountered while " \
    "parsing a delta." )                                         \
  E(FSL_RC_DELTA_INVALID_SIZE, 127, \
    "Indicates that an invalid size value was encountered while " \
    "parsing a delta." )                                          \
  E(FSL_RC_DELTA_INVALID_OPERATOR, 128, \
    "Indicates that an invalid operator was encountered while parsing " \
    "a delta.")                                             \
  E(FSL_RC_DELTA_INVALID_TERMINATOR, 129, \
    "Indicates that an invalid terminator was encountered while " \
    "parsing a delta.")                                        \
  E(FSL_RC_SYNTAX, 130, \
    "Indicates a generic syntax error in a structural artifact. Some " \
     "types of manifest-releated errors are reported with more specific " \
    "error codes, e.g. FSL_RC_RANGE if a given card type appears too " \
    "often.")                                                          \
  E(FSL_RC_AMBIGUOUS, 131, \
    "Indicates that some value or expression is ambiguous. Typically " \
    "caused by trying to resolve ambiguous symbolic names or hash " \
    "prefixes to their full hashes.")                               \
  E(FSL_RC_NOOP, 132, \
    "Used by fsl_checkin_commit(), and similar operations, to indicate " \
    "that they're failing because they would be no-ops. That would " \
    "normally indicate a \"non-error\", but a condition the caller " \
    "certainly needs to know about.")                                \
  E(FSL_RC_PHANTOM, 133, \
    "A special case of FSL_RC_NOT_FOUND which indicates that the " \
    "requested repository blob could not be loaded because it is a " \
    "phantom. That is, the record is found but its contents are not " \
    "available. Phantoms are blobs which fossil knows should exist, " \
    "because it's seen references to their hashes, but for which it does " \
    "not yet have any content.")                                        \
  E(FSL_RC_UNSUPPORTED, 134, \
    "Indicates that the requested operation is unsupported.")   \
  E(FSL_RC_MISSING_INFO, 135, \
    "Indicates that the requested operation is missing certain required " \
    "information.")                                         \
  E(FSL_RC_DIFF_BINARY, 136, \
    "Special case of FSL_RC_TYPE triggered in some diff APIs, indicating " \
    "that the API cannot diff what appears to be binary data.") \
  E(FSL_RC_DIFF_WS_ONLY, 137, \
    "Triggered by some diff APIs to indicate that only whitespace " \
    "changes we found and the diff was requested to ignore whitespace.") \
  E(FSL_RC_INTERRUPTED, 138, \
    "Intended to be used with fsl_cx_interrupt() by signal handlers " \
    "and UI threads.")                                                \
  E(FSL_RC_WOULD_FORK, 139, \
    "Intended to be used by operations which would cause what is " \
    "presumably an unintended fork. Fossil does not have any issues with " \
    "forking, but practice suggests that most forks (that is, checking " \
    "in to a non-leaf version) are unintentional.")                     \
  E(FSL_RC_CANNOT_HAPPEN, 140, \
    "This is intended only for internal use with fsl__fatal(), to " \
    "report conditions which \"cannot possibly happen\".") \
  E(FSL_RC_TIMEOUT, 141, \
    "Indicates that a context-specific timeout was triggered.") \
  E(FSL_RC_REMOTE, 142, \
    "Indicates that an error was received from a remote during " \
    "syncing.")                                                  \
  E(FSL_RC_SHUNNED, 143, \
    "Indicates that a given blob is in the SHUNNED list.")  \
  E(FSL_RC_end,999, \
    "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.")

/**
   Most functions in this library which return an int return result
   codes from the fsl_rc_e enum.  None of these entries are guaranteed
   to have a specific value across library versions except for
   FSL_RC_OK, which is guaranteed to always be 0 (and the API
   guarantees that no other code shall have a value of zero).

   The only reasons numbers are hard-coded to the values is to
   simplify debugging during development. Clients may use
   fsl_rc_cstr() to get some human-readable (or programmer-readable)
   form for any given value in this enum.
*/
enum fsl_rc_e {

#define E(N,V,H) N = V,
  fsl_rc_e_map(E)
#undef E

};
typedef enum fsl_rc_e fsl_rc_e;

/**
   File permissions flags supported by fossil manifests. Their numeric
   values are a hard-coded part of the Fossil architecture and must
   not be changed. These refer to manifest-level permissions, not
   filesystem-level permissions (though they translate to/from
   filesystem-level meanings at some point).
*/
enum fsl_fileperm_e {
/**
   Indicates a regular, writable file. Fossil has no concept of
   SCM-managed read-only files, nor has a need for such an oddity ever
   come up.
*/
FSL_FILE_PERM_REGULAR = 0,
/** Indicates a regular file with the executable bit set. */
FSL_FILE_PERM_EXE = 0x1,
/**
   Indicates a symlink. Symlinks do not have the executable bit set
   separately on Unix systems.
*/
FSL_FILE_PERM_LINK = 0x2
};
typedef enum fsl_fileperm_e fsl_fileperm_e;

/**
   Returns a "standard" string form for a fsl_rc_e code.  The string
   is primarily intended for debugging purposes.  The returned bytes
   are guaranteed to be static and NUL-terminated. They are not
   guaranteed to contain anything useful for any purposes other than
   debugging and tracking down problems. If passed a code which is
   not in the fsl_rc_e enum, it returns NULL.
*/
FSL_EXPORT char const * fsl_rc_cstr(int rc);

/**
   Returns the value of FSL_LIBRARY_VERSION used to compile the
   library. If this value differs from the value the caller was
   compiled with, Chaos might ensue.

   The API does not yet have any mechanism for determining
   compatibility between library versions and it also currently does
   no explicit checking to disallow incompatible versions.
*/
FSL_EXPORT char const * fsl_library_version(void);

/**
   Returns the SCM-specific version info for libfossil (the hash and
   timestamp of its own source's version).
*/
FSL_EXPORT char const * fsl_library_version_scm(void);

/**
   Returns true if yourLibVersion compares lexically equal to
   FSL_LIBRARY_VERSION, else it returns false. It is intended to be
   passed the FSL_LIBRARY_VERSION string the client code was built
   with.
*/
FSL_EXPORT bool fsl_library_version_matches(char const * yourLibVersion);

/**
   This type, accessible to clients via the ::fsl_lib_configurable
   global, contains configuration-related data for the library which
   can be swapped out by clients. All modifications must be made
   before using any of the library's APIs.
*/
struct fsl_lib_configurable_t {
  /**
     Library-wide allocator. It may be replaced by the client IFF it
     is replaced before the library allocates any memory. The default
     implementation uses the C-standard de/re/allocators.  Modifying
     this member while any memory allocated through it is still "live"
     leads to undefined results. There is an exception: a "read-only"
     middleman proxy which does not change how the memory is allocated
     or intepreted can safely be swapped in or out at any time
     provided the underlying allocator stays the same and the client
     can ensure that there are no thread-related race
     conditions. e.g. it is legal to swap this out with a proxy which
     logs allocation requests and then forwards the call on to the
     original implementation, and it is legal to do so at essentially
     any time. The important thing this that all of the
     library-allocated memory goes through a single underlying
     (de)allocator for the lifetime of the application.
  */
  fsl_allocator allocator;
};
typedef struct fsl_lib_configurable_t fsl_lib_configurable_t;
FSL_EXPORT fsl_lib_configurable_t fsl_lib_configurable;

/**
   SQLite Encryption Extension (SEE) key types for use with
   fsl_see_key_f(). Each of these options corresponds to one
   of the key-entry modes supported by SEE via pragmas,
   e.g. PRAGMA key, PRAGMA textkey, and PRAGMA hexkey.

   See (as it were): https://sqlite.org/see

   As of 2026-10-28, this is deprecated, in that it's not a necessary
   part of the API.
*/
enum fsl_see_keytype_e {
  /** Sentinel value indicating "not an SEE key". */
  FSL_SEE_KEYTYPE_NONE = 0,
  /** Corresponses to (PRAGMA key). */
  FSL_SEE_KEYTYPE_PLAIN = 1,
  /** Corresponses to (PRAGMA hexkey). Binary data to be hex-encoded
      by the library. */
  FSL_SEE_KEYTYPE_BINARY = 2,
  /** Corresponses to (PRAGMA hexkey). Encoded by the client as a
      series of hex digits. */
  FSL_SEE_KEYTYPE_HEXKEY = 3,
  /** Corresponses to (PRAGMA textkey). */
  FSL_SEE_KEYTYPE_TEXTKEY = 4
};
typedef enum fsl_see_keytype_e fsl_see_keytype_e;

/**
   EXPERIMENTAL and subject to change. But it seems to do its job
   reasonably well.

   A callback type for fetching an encryption key for use with the
   SQLite Encryption Extension API. This is only for use in
   SEE-capable builds.

   `pState` is the pointer provided by the client for use here
   (typically via fsl_cx_config::see::pState). It is opaque to the
   library, intended solely for the SEE client's use.

   `zDbFile` is the NUL-terminated name of the db for which the key is
   being requested.

   If a key is available, it must be appended to pOut using
   fsl_b_append() (or equivalent).

   On success, it must return 0. Any non-0 result value is treated by
   the library as failure to open the db, with one exception:
   FSL_RC_UNSUPPORTED indicates that decryption is not supported but
   opening of a database will not fail fatally for this result.
   Instead, if the db really is encrypted, it will fail later when the
   db is first used.

   If it populates pOut then it must set `*keyType` to one of the
   entries from the fsl_see_keytype_e enum, indicating the type of the
   key.

   If the implementation has no key to provide for the db, but does
   not know that to be an error, it should simply return 0 and not add
   any bytes to pOut. It need not set `*keyType` in this case, as the
   library guarantees that it will initially have the value
   FSL_SEE_KEYTYPE_NONE.

   The library guarantees that the pOut->mem memory holding the
   collected key (A) is not copied beyond that necessary for passing
   it to SQLite and (B) is zeroed out immediately after its use (by
   the routine which invokes this callback). It cannot, however, make
   the same guaranty about the SQLite-side memory which holds that
   key.

   The library does not cache the results of these calls and may need
   to call this multiple times for the same database during the life
   of a single fsl_cx. (Ordinarily, though, the SCM databases are
   opened a single time and left that way.)

   A recommended convention, derived from fossil(1), is to name
   encrypted repositories with a suffix of ".efossil". Implementations
   of this callback could use such a convention to determine whether
   or not a key is necessary for the db (something this library cannot
   do on its own[^1]).

   [^1]: 2026-10-28: if we read the first bytes of the db, bypassing
   sqlite, we could assume that files without the standard db header
   are encrypted, but using POSIX APIs to open/close files which
   SQLite uses can mess up their locks.
*/
typedef int (*fsl_see_key_f)(void * pState, const char *zDbFile,
                             fsl_b * pOut, int *keyType);

/**
   Expands to a mapping of all fsl_msg types by invoking
   E(NAME,VALUE,PayloadDescription) for each one. NAME is the suffix
   part of the name, e.g. mask_type instead of
   FSL_MSG_mask_type. VALUE is its integer value. PayloadDescription
   is a human-legible string typically noting the data type of the
   payload.

   Each entry encodes the data type corresponding to the associated
   fsl_msg object's payload member: mask the message type value
   against FSL_MSG_mask_type to get the payload's type.

   The top 8 bits are a single-digit value, not a bitmask.

   This mechanism was added for the sync subsystem and the goal is now
   to replace some of the library's disparate callbacks with this
   mechanism.
*/
#define fsl_msg_map(E)                                     \
  E(INVALID,           0, "Sentinel value")                \
  E(mask_type,         0x7F000000, "Data type mask")       \
  E(mask_reserved,     0x00FFFF00, "Reserved")             \
  E(mask_purpose,      0x000000FF, "Message purpose ID")   \
  E(type_null,         0x01000000, "NULL")                 \
  E(type_string,       0x02000000, "(char const *)")       \
  E(type_buffer,       0x03000000, "(fsl_b const *)") \
  E(type_size,         0x04000000, "(fsl_size_t const *)") \
  E(type_blob,         0x06000000, "(fsl_msg_blob const *)" ) \
  E(type_rebuild,      0x07000000, "(fsl_msg_rebuild const *)" )  \
  E(type_xfer,         0x08000000, "(fsl_msg_xfer const *)" )  \
  E(ERROR,         0x01 | FSL_MSG_type_string, "Error string") \
  E(INFO,          0x02 | FSL_MSG_type_string, "Info string")  \
  E(DEBUG,         0x03 | FSL_MSG_type_string, "Debugging string") \
  E(TMPFILE,       0x04 | FSL_MSG_type_string, "value=name of temp file left over") \
  E(CONNECT,       0x05 | FSL_MSG_type_size, "value=trip number") \
  E(RCV_BLOB,      0x06 | FSL_MSG_type_blob, "Blob received")     \
  E(RCV_MESSAGE,   0x07 | FSL_MSG_type_string, "\"message\" card from remote") \
  E(RCV_CONFIG,    0x08 | FSL_MSG_type_string, "Config group name") \
  E(REBUILD,       0x09 | FSL_MSG_type_rebuild, "(fsl_msg_rebuild const *)") \
  E(XFER,          0x0A | FSL_MSG_type_xfer, "(fsl_msg_xfer const *)") \
  /* TODO: consolidate TXN_X into TXN and pass an info object. */ \
  E(TXN_BEGIN,     0x0B | FSL_MSG_type_size, "value=transaction level") \
  E(TXN_COMMIT,    0x0C | FSL_MSG_type_size, "value=transaction level") \
  E(TXN_ROLLBACK,  0x0D | FSL_MSG_type_size, "value=transaction level") \
  E(VERBOSE,       0x0E | FSL_MSG_type_string, "Info string") \
  E(VERIFY,        0x0F | FSL_MSG_type_size, "value=artifacts left to verify")

/**
   Message type flags Indicators for use with fsl_sc::status,
   fsl_cx_emit(), and friends.
*/
enum fsl_msg_e {
#define E(NAME,VAL,IGNORED) FSL_MSG_ ## NAME = VAL,
  fsl_msg_map(E)
#undef E
};

typedef enum fsl_msg_e fsl_msg_e;

/**
   Message payload type for FSL_MSG_type_blob.
*/
struct fsl_msg_blob {
  char const * hash;
  fsl_int_t size /* negative for phantom blobs */;
};
typedef struct fsl_msg_blob fsl_msg_blob;

/**
   Returns the C-string form of the given sync message type, or NULL
   if e is invalid.
*/
char const * fsl_msg_type_cstr(fsl_msg_e e);

/**
   A "transfer context" type used by many of the sync transfer
   APIs. This type is opaque to client code.
*/
typedef struct fsl_xfer fsl_xfer;

/**
   A message object type for sending synchronous messages to callbacks
   during certain processing steps in the library, the intent
   primarily being for UIs to be able to provide feedback during
   long-running or multi-step operations.
*/
struct fsl_msg {
  /** The type of status message. */
  fsl_msg_e type;

  /**
     An optional bit of informative text. If set, the bytes are owned
     by the library and may be (and likely are) invalidated as soon as
     the message callback returns. The data type depends on this->type
     and it can be interpreted by deciphering fsl_msg_e.
  */
  void const * payload;

  /**
     This message's fsl_cx context, providing the callback with access
     to the associated SCM state.
  */
  fsl_cx * f;
};

typedef struct fsl_msg fsl_msg;

/** fsl_msg instance intended for const-copy initialization. */
#define fsl_msg_empty_m { \
    .type = FSL_MSG_INVALID, .payload = NULL, \
    .f = NULL \
  }

/** fsl_msg instance intended for non-const copy initialization. */
extern const fsl_msg fsl_msg_empty;

/**
   A callback for use with the library's message-passing subsystem, to
   provide feedback during potentially long-running work, in
   particular synchronization with a remote.

   Implementations are passed the a message object and any state
   associated with the callback.

   If the function returns non-0, the operation is aborted and that
   result is propagated back up through the API.  On error, this
   callback is expected to call either of fsl_cx_err_set() or the
   fsl_xfer_error() family of functions and return that code.

   Messages are synchronous - the library must wait on a response from
   this function before continuing. Ergo, clients should not perform
   long work in the status callback (or should do so in a separate
   thread which _does_not_ use msg->f (which is not
   thread-safe)).

   This method is intended primarily for logging or non-interactive
   feedback, with the exception of the ability to return non-0 to
   interrupt the sync. e.g. an implementation could return
   FSL_RC_BREAK in response to an application-side cancel/interrupt
   button being triggered.

   When triggered via a sync operation, the library guarantees that a
   db transaction will be in place when it calls this, a further
   incentive to keep implementations short and fast because the db is
   necessarily locked during that time. The exception is
   FSL_MSG_TMPFILE, which the popen-based channels emit during the
   exchange of a request. Sync commits its transaction before each
   exchange and begins the next one after it, except during a clone
   or inside a transaction the caller opened.
*/
typedef int (*fsl_msg_f)(fsl_msg const * msg, void *state);

/**
   Client callback info for receiving various events during
   fossil sync processing.
*/
struct fsl_msg_listener {
  /** Callback function. */
  fsl_msg_f callback;
  /** State for the final argument to this->callback(). */
  void * state;
};
typedef struct fsl_msg_listener fsl_msg_listener;
#define fsl_msg_listener_empty_m { .callback=0, .state=0 }
extern const fsl_msg_listener fsl_msg_listener_empty;


/**
   An alternative approach to fsl_see_key_f() which is both more
   generic and keeps the library from ever having to lay eyes on the
   encryption key.

   The fsl_cx class uses this as follows:

   Immediately after a db is sqlite3_open()'d, before the library
   connects the db to a fsl_cx instance, the callback of this type set
   in fsl_cx_config::dbOnOpen is called and passed the db handle and
   the fsl_cx_config::dbOnOpen::state. If that callback returns 0 then
   the context continues as normal, otherwise the open is considered
   to have failed. Errors "should" be reported via the db->error
   object. If this function returns non-0 but does not update
   db->error then the library attempts to extract an error message
   from the db handle. Failing that, it will propagate the unadorned
   result code.

   This callback is _really_ only intended for use in setting an
   encryption key on an encrypted database. Implementations are
   strongly encourages to avoid any temptation to perform other
   db-side work here, e.g.  schema validation or manipulation.

   The following operations are very expressly forbidden to
   implementations:

   - Any which require libfossil-level functionality. At the point
     this is called, the pending fsl_cx owner has not yet been
     connected with the database.

   - Using sqlite3_db_config() with the SQLITE_DBCONFIG_MAINDBNAME
     option.  The library aliases "main" to either "repo" or "ckout",
     depending on which db is opened.

   - Closing the db.
*/
typedef int (*fsl_db_on_open_f)(fsl_db *db, void *pState);


/**
   A part of the configuration used by fsl_cx_init() and friends.
*/
struct fsl_cx_config {
  /**
     If true, all SQL which goes through the fossil engine will be
     traced to stdout. This is, of course, only intended for use in
     debugging.

     TODO: replace this with a fsl_outputer.
  */
  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.
  */
  bool sqlPrint;

  /**
     Specifies the default hash policy.
  */
  fsl_hashpolicy_e hashPolicy;

  /**
     Listener for fsl_msg-type events. This is how the library
     provides status updates for potentially long-running operations
     like synchronization.

     Potential TODO is support multiple listeners.
  */
  fsl_msg_listener listener;

  /**
     The output channel for the Fossil instance.

     Reminder to self: if this is not used at the library level then
     consider removing it. This addition may have been a piece of
     unnecessary overengineering. To the best of my recollection, the
     library internals do not use this, but the fcli API does. If that
     is indeed the case, we can move it into that API.
  */
  fsl_outputer output;

  /**
     A hook called when a db is opened, intended primarily for
     supplying a SEE decryption key to it.
  */
  struct {
    /**
       See fsl_db_on_open_f() for the semantics.
    */
    fsl_db_on_open_f callback;
    /**
       Client-defined state for this->callback()'s second argument.
    */
    void * state;
  } dbOnOpen;
};

/**
   fsl_cx_config instance initialized with defaults, intended for
   const-copy initialization.
*/
#define fsl_cx_config_empty_m {     \
    .traceSql = 0,                  \
    .sqlPrint = 0,                  \
    .hashPolicy = FSL_HPOLICY_SHA3, \
    .listener = fsl_msg_listener_empty_m,      \
    .output = {.out=NULL, .state=NULL},        \
    .dbOnOpen = {.callback=NULL, .state=NULL}  \
}

/**
   fsl_cx_config instance initialized with defaults, intended for
   non-const copy initialization.
*/
FSL_EXPORT const fsl_cx_config fsl_cx_config_empty;

/**
   Allocates a new fsl_cx instance, which must eventually
   be passed to fsl_cx_finalize() to clean it up.
   Normally clients do not need this - they can simply pass
   a pointer to NULL as the first argument to fsl_cx_init()
   to let it allocate an instance for them.
*/
FSL_EXPORT fsl_cx * fsl_cx_malloc(void);

/**
   Initializes a fsl_cx instance. tgt must be a pointer to NULL,
   e.g.:

   ```
   fsl_cxt * f = NULL; // NULL is important - see below
   int rc = fsl_cx_init( &f, NULL );
   ```

   It is very important that f be initialized to NULL _or_ to an
   instance which has been properly allocated and empty-initialized
   (e.g. via fsl_cx_malloc()). If *tgt is NULL, this routine
   allocates the context, else it assumes the caller did. If f
   points to unitialized memory then results are undefined.

   If the second parameter is NULL then default implementations are
   used for the context's output routine and other options. If it
   is not NULL then param->allocator and param->output must be
   initialized properly before calling this function. The contents
   of param are bitwise copied by this function and ownership of
   the returned value is transfered to *tgt in all cases except
   one:

   If passed a pointer to a NULL context and this function cannot
   allocate it, it returns FSL_RC_OOM and does not modify *tgt. In
   this one case, ownership of the context is not changed (as there's
   nothing to change!). On any other result (including errors),
   ownership of param's contents are transfered to *tgt and the client
   is responsible for passing *tgt ot fsl_cxt_finalize() when he is
   done with it. Note that (like in sqlite3), *tgt may be valid memory
   even if this function fails, and the caller must pass it to
   fsl_cx_finalize() whether or not this function succeeds unless it
   fails at the initial OOM (which the client can check by seeing if
   (*tgt) is NULL, but only if he set it to NULL before calling this).

   Returns 0 on success, FSL_RC_OOM on an allocation error,
   FSL_RC_MISUSE if (!tgt). If this function fails, it is illegal to
   use the context object except to pass it to fsl_cx_finalize(), as
   explained above.

   @see fsl_cx_finalize()
*/
FSL_EXPORT int fsl_cx_init( fsl_cx ** tgt, fsl_cx_config const * param );

/**
   Frees all memory associated with f, which must have been
   allocated/initialized using fsl_cx_malloc(), fsl_cx_init(), or
   equivalent, or created on the stack and properly initialized (via
   fsl_cx_init() or copy-constructed from fsl_cx_empty).  If it was
   allocated using fsl_cx_malloc(), this function frees f, else the
   memory is owned by someone else and it is not freed.

   This function triggers any finializers set for f's client state
   or output channel.

   This is a no-op if !f and is effectively a no-op if f has no
   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 _previous_ set of flags
   (that is, the state they were in before this call was made).

   @see fsl_cx_flags_get()
*/
FSL_EXPORT fsl_flag32_t fsl_cx_flag_set( fsl_cx * f, fsl_flag32_t flags,
                                         bool enable );

/**
   Returns f's flags.

   @see fsl_cx_flag_set()
*/
FSL_EXPORT fsl_flag32_t fsl_cx_flags_get( fsl_cx const * f );

/**
   Sets the Fossil error state to the given error code and
   fsl_appendf()-style format string/arguments. On success it
   returns the code parameter. It does not return 0 unless code is
   0, and if it returns a value other than code then something went
   seriously wrong (e.g. allocation error: FSL_RC_OOM) or the
   arguments were invalid: !f results in FSL_RC_MISUSE.

   If !fmt then fsl_rc_cstr(code) is used to create the
   error string.

   As a special case, if code is FSL_RC_OOM, no error string is
   allocated (because it would likely fail, assuming the OOM
   is real).

   As a special case, if code is 0 (the non-error value) then fmt is
   ignored and any error state is cleared.
*/
FSL_EXPORT int fsl_cx_err_set( fsl_cx * f, int code, char const * fmt, ... );

/**
   va_list counterpart to fsl_cx_err_set().
*/
FSL_EXPORT int fsl_cx_err_setv( fsl_cx * f, int code, char const * fmt,
                                va_list args );

/**
   Fetches the error state from f. See fsl_error_get() for the semantics
   of the parameters and return value.
*/
FSL_EXPORT int fsl_cx_err_get( fsl_cx * f, char const ** str, fsl_size_t * len );

/**
   Returns f's persistent error code, or 0 if it has no error state.
*/
FSL_EXPORT int fsl_cx_err_code( fsl_cx const * f );


/**
   Returns f's error object. It is owned by f, and its address is
   stable as long as f is valid. It's provided as a semi-formal way
   for not-quite-core code to get access to f->error without having to
   reach into f directly.  It should only be preferred over
   fsl_cx_err_set()/get() when an arbitrary fsl_error object is needed
   for an API (like fsl_b_escape_arg()) and we know we'd like to
   unconditionally propagate that error via f's error state. In such
   cases, using this object can avoid a second allocation to copy the
   error message.
*/
FSL_EXPORT fsl_error const * fsl_cx_err_ec(fsl_cx const * f);

/** Non-const counterpart of fsl_cx_err_ec(). */
FSL_EXPORT fsl_error * fsl_cx_err_e(fsl_cx * f);

/**
   Resets's f's error state, basically equivalent to
   fsl_cx_err_set(f,0,NULL). This may be necessary for apps if they
   rely on looking at fsl_cx_err_get() at the end of their
   app/routine, because error state survives until it is cleared, even
   if the error held there was caught and recovered. This function
   might keep error string memory around for re-use later on.

   This does NOT reset the fsl_cx_interrupted() flag!
*/
FSL_EXPORT void fsl_cx_err_reset(fsl_cx * f);

/**
   Replaces f's error state with the contents of err, taking over
   any memory owned by err (but not err itself). Returns the new
   error state code (the value of err->code before this call) on
   success. The only error case is if !f (FSL_RC_MISUSE). If err is
   NULL then f's error state is cleared and 0 is returned. err's
   error state is cleared by this call.
*/
FSL_EXPORT int fsl_cx_err_set_e( fsl_cx * f, fsl_error * err );

/**
   If f has error state then it outputs its error state to its output
   channel and returns the result of fsl_output(). Returns 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, bool addNewline );

/**
   If db has error state, moves that state into f (without requiring
   any allocation), replacing f's error state. If db has no error
   state, f's error state is left as it is. If db is NULL then f's
   primary db connection is used. Returns FSL_RC_MISUSE if (!db &&
   f-is-not-opened), with the caveat f _always_ has a db connection
   under the current connection architecture. On success it returns
   f's resulting error code (which may be 0).

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

/**
   If rc is not 0, f has no error state, and db's error code is rc,
   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. A db
   error code which differs from rc is assumed to be left over from
   an earlier operation, and is not uplifted, so that it cannot
   replace rc or describe a different failure.

   As a special case, if rc is FSL_RC_OOM, this function has no side
   effects and returns rc. The intention of that is to keep a
   propagated db-level error (which may perhaps be stale by the time
   this is called) from hiding an OOM error.

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

/**
   Outputs the first n bytes of src to f's configured output
   channel. Returns 0 on success, 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.

   Results are undefined if f or src are NULL.

   @see fsl_outputf()
   @see fsl_flush()
*/
FSL_EXPORT int fsl_output( fsl_cx * f, void const * src,
                           fsl_size_t n );

/**
   Flushes f's output channel. Returns 0 on success. If the flush
   routine is NULL then this is a harmless no-op. Results are undefined
   if f is NULL.

   @see fsl_outputf()
   @see fsl_output()
*/
FSL_EXPORT int fsl_flush( fsl_cx * f );

/**
   Uses fsl_appendf() to append formatted output to the channel
   configured for use with fsl_output(). Returns 0 on success, and
   will otherwise return the result of the underlying fsl_cx_format()
   call. (Prior to 2025-08-11, it used fsl_appendf() instead.)

   Results are undefined if f or fmt are NULL or otherwise malformed.

   @see fsl_output()
   @see fsl_flush()
*/
FSL_EXPORT int fsl_outputf( fsl_cx * f, char const * fmt, ... );

/**
   va_list counterpart to fsl_outputf().
*/
FSL_EXPORT int fsl_outputfv( fsl_cx * f, char const * fmt, va_list args );


/**
   A proxy for fsl_appendfv() which pre-processes the format-specifier
   string (zFmt) to replace certain placeholders with information
   about the fsl_cx object. After doing so, it passes on the adjusted
   zFmt to fsl_appendfv().

   Placeholders are in the form {{X}}, where X is one of the words
   listed below. Any unknown X will cause the whole {{X}} to be
   emitted as-is.

   Known X values (with quotes for clarity, but the quotes are not
   part of X):

   - "chkout.dir": gets replaced with the path to the current checkout
     directory, without a trailing slash.

   - "chkout.dir/": as for ckout-dir but with a trailing slash.

   - "repo.db": gets replaced with the path to the current repository
     database.

   - "user.name": gets replaced with fsl_cx_user_guess().

   - "dbname.repo", "dbname.ckout", "bare.repo.NAME",
     "bare.ckout.NAME", "temp.NAME" and "bare.temp.NAME": get replaced
     with the names of the repository's and checkout's schemas, of the
     repository resp. checkout table NAME and of f's own TEMP table
     NAME on f's db connection, as the fsl_db SQL functions do (see
     fsl_db_prepare()). Unlike those, this function never expands
     "{{dbname.ckout}}.NAME" or "{{dbname.repo}}.NAME" as a unit, so
     while f's checkout resp. repository tables are prefixed tables of
     a host's main db (fsl_repo_open_ckout_opt::hostTablePrefix,
     fsl_repo_open_host()), a {{dbname.ckout}} resp. {{dbname.repo}}
     fails with FSL_RC_MISUSE, with f's error state set.

   File and directory names which are empty are emitted as such.

   The parser is not robust enough to attempt to recover from failures
   related to the "{{" and "}}" parts, and malformed tags may cause it
   to skip expansion on the remaining parts of the input (it will be
   passed on as-is, warts and all).

   Returns 0 on success. Returns FSL_RC_OOM if allocation of the
   formatting buffer fails. Else returns the value of the
   fsl_appendfv() call.
*/
FSL_EXPORT int fsl_cx_formatv(fsl_cx * f, fsl_output_f out,
                              void * outState, char const *zFmt,
                              va_list args );

/**
   The elipsis counterpart of fsl_cx_formatv().
*/
FSL_EXPORT int fsl_cx_format(fsl_cx * f, fsl_output_f out,
                             void * outState, char const *zFmt, ... );

/**
   Convenience formof fsl_cx_format() which appends the formatted
   output to tgt.
*/
FSL_EXPORT int fsl_cx_format_buffer(fsl_cx * f, fsl_b * tgt,
                                    char const *zFmt, ... );

/**
   Convenience formof fsl_cx_format() which appends the formatted
   output to tgt.
*/
FSL_EXPORT int fsl_cx_format_FILE(fsl_cx * f, FILE * tgt,
                                  char const *zFmt, ... );


/**
   Sets or clears (if userName is NULL or empty) the default
   repository user name for operations which require one.

   Returns 0 on success, FSL_RC_MISUSE if f is NULL,
   FSL_RC_OOM if copying of the userName fails.

   Example usage:
   ```
   char * u = fsl_user_name_guess();
   int rc = fsl_cx_user_set(f, u);
   fsl_free(u);
   ```

   (Sorry about the extra string copy there, but adding a function
   which passes ownership of the name string seems like overkill.)

   @see fsl_cx_user_guess()
*/
FSL_EXPORT int fsl_cx_user_set( fsl_cx * f, char const * userName );

/**
   If f has a user name set (via fsl_cx_user_set()) then this function
   returns that value. If none has been set, this tries to guess one,
   using the first of:

   - The "default-user" value from the checkout db's vvar table.
   - The user entry from the repo db's user table with id 1.
   - fsl_user_name_guess()

   and then assigns it as f's current user name. Returns NULL only on
   allocation error or if an environment setup error prevents
   detection of the user name. Not having a user name is not normally
   a problem, but trying to create new artifacts will fail if they
   have no user name to apply to their U-cards.

   The returned bytes are owned by f and will be invalidated by
   any future calls to fsl_cx_user_set().

   The user name is, by default, determined automatically when a repo
   or a checkout/repo combination is opened, so client code does not
   normally need to call this.
*/
FSL_EXPORT char const * fsl_cx_user_guess(fsl_cx * f);

/**
   Returns the name set by fsl_cx_user_set(), or NULL if f has no
   default user name set. The returned bytes are owned by f and will
   be invalidated by any future calls to fsl_cx_user_set().

   @see fsl_cx_user_guess()
*/
FSL_EXPORT char const * fsl_cx_user_get( fsl_cx const * f );

/**
   If f is not NULL and has a checkout db opened then this function
   returns its name. The bytes are valid until that checkout db
   connection is closed. If len is not NULL then *len is (on
   success) assigned to the length of the returned string, in
   bytes. The string is NUL-terminated, so fetching the length (by
   passing a non-NULL 2nd parameter) is optional.

   Returns NULL if !f or f has no checkout opened.

   @see fsl_ckout_open_dir()
   @see fsl_cx_ckout_dir_name()
   @see fsl_cx_db_file_config()
   @see fsl_cx_db_file_repo()
*/
FSL_EXPORT char const * fsl_cx_db_file_ckout(fsl_cx const * f,
                                             fsl_size_t * len);

/**
   Equivalent to fsl_ckout_db_file() except that
   it applies to the name of the opened repository db,
   if any. For a repository which is tables of a host's main db
   (fsl_repo_open_host()), that is the host main db's file name.

   @see fsl_cx_db_file_ckout()
   @see fsl_cx_db_file_config()
*/
FSL_EXPORT char const * fsl_cx_db_file_repo(fsl_cx const * f,
                                            fsl_size_t * len);

/**
   Equivalent to fsl_ckout_db_file() except that
   it applies to the name of the opened config db,
   if any.

   @see fsl_cx_db_file_ckout()
   @see fsl_cx_db_file_repo()
*/
FSL_EXPORT char const * fsl_cx_db_file_config(fsl_cx const * f,
                                              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);

/**
   If f has an opened checkout db (from fsl_ckout_open_dir()) then
   this function returns the directory part of the path for the
   checkout, including (for historical and internal convenience
   reasons) a trailing slash. The returned bytes are valid until that
   db connection is closed. If len is not NULL then *len is (on
   success) assigned to the length of the returned string, in bytes.
   The string is NUL-terminated, so fetching the length by passing a
   non-NULL 2nd parameter is optional.

   Returns NULL if !f or f has no checkout opened.

   @see fsl_ckout_open_dir()
   @see fsl_ckout_db_file()
*/
FSL_EXPORT char const * fsl_cx_ckout_dir_name(fsl_cx const * f,
                                              fsl_size_t * len);

/**
   Returns a handle to f's main db (which may or may not have any
   relationship to the repo/checkout/config databases - that's
   unspecified!), or NULL if f has no opened repo or checkout db.  The
   returned object is owned by f and the client MUST NOT do any of the
   following:

   - Close the db handle.

   - Use transactions without using fsl_db_txn_begin()
   and friends.

   - Fiddle with the handle's internals. Doing so might confuse its
   owning context.

   Clients MAY add new user-defined functions, use the handle with
   fsl_db_prepare(), and other "mundane" db-related tasks.

   The global config db uses a separate db handle accessible via
   fsl_cx_db_config().

   @see fsl_cx_db_repo()
   @see fsl_cx_db_ckout()
   @see fsl_cx_db_config()
*/
FSL_EXPORT fsl_db * fsl_cx_db( fsl_cx * 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 );

/**
   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 );

/**
   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);

/**
   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);

/**
   Returns true if the given context has a checkout opened, else
   false.

   There is no counterpart fsl_cx_has_repo() for the simple reason
   that we've never needed one. Having a checkout implies having a
   repo, as a checkout is always opened with its repo db counterpart.

   @see fsl_needs_ckout()
*/
FSL_EXPORT bool fsl_cx_has_ckout(fsl_cx const * f );

/**
   Opens the given database file as f's configuration database.

   If f already has a config database opened then:

   1) If passed a NULL dbName or dbName is an empty string then this
   function returns 0 without side-effects.

   2) If passed a non-NULL/non-empty dbName, any existing config db is
   closed before opening the named one. The database is created and
   populated with an initial schema if needed.

   If no config db is opened and dbName is NULL or empty then it uses
   a default db name, "probably" under the user's home directory (see
   fsl_config_global_preferred_name()). To get the name of the
   database after it has been opened/attached, use
   fsl_cx_db_file_config().

   Returns 0 on success. On error, f's error state describes the
   failure and the result is non-0, including:

   - FSL_RC_NOT_FOUND or FSL_RC_TYPE if dbName is NULL or empty and
     no home directory can be determined (see
     fsl_config_global_preferred_name()).

   - The result of fsl_config_close() if a config db is opened and
     cannot be closed.

   - A db-related code if the database cannot be created or opened.
     A database file which exists but is read-only is opened, and
     attempts to change settings in it then fail.

   Results are undefined if f is NULL or not properly initialized.

   @see fsl_cx_db_config()
   @see fsl_config_close()
   @see fsl_config_global_preferred_name()
*/
FSL_EXPORT int fsl_config_open( fsl_cx * f, char const * dbName );

/**
   Closes/detaches the database connection opened by
   fsl_config_open(). If the config db is not opened, this
   is a harmless no-op. Note that it does not propagate db-closing
   errors because there is no sensible recovery strategy from
   such cases.

   This operation only fails if the config db is opened and has
   an active transaction, in which case f's error state is updated
   to reflect that cause of the error.

   ACHTUNG: it is imperative that any prepared statements compiled
   against the config db be finalized before closing the db. Any
   statements prepared using fsl_db_prepare_cached() against the
   config db will be automatically finalized by the closing process.

   Potential TODO: if a transaction is pending, force a rollback and
   close the db anyway. If we do that, this function will change to
   return void.

   @see fsl_cx_db_config()
   @see fsl_config_open()
*/
FSL_EXPORT int fsl_config_close( fsl_cx * f );

/**
   If f has an opened configuration db then its handle is returned,
   else 0 is returned.

   For API consistency's sake, the db handle's "MAIN" name is aliased
   to fsl_db_role_name(FSL_DBROLE_CONFIG).

   @see fsl_config_open()
   @see fsl_config_close()
*/
FSL_EXPORT fsl_db * fsl_cx_db_config( fsl_cx * f );

/**
   Convenience form of fsl_db_prepare() which uses f's main db.
   Returns 0 on success. On preparation error, any db error state is
   uplifted from the db object to the fsl_cx object.  Returns
   FSL_RC_RANGE if !*sql.

   Results are undefined if f or sql are NULL or otherwise
   invalid.
*/
FSL_EXPORT int fsl_cx_prepare( fsl_cx * f, fsl_stmt * tgt,
                               char const * sql, ... );

/**
   va_list counterpart of fsl_cx_prepare().
*/
FSL_EXPORT int fsl_cx_preparev( fsl_cx * f, fsl_stmt * tgt,
                                char const * sql, va_list args );

/**
   Convenience form of fsl_db_prepare_cached() which uses f's main db.
   Returns 0 on success. On preparation error, any db error state is
   uplifted from the db object to the fsl_cx object.  Returns
   FSL_RC_RANGE if !*sql.

   Results are undefined if f or sql are NULL or otherwise
   invalid.
*/
FSL_EXPORT int fsl_cx_prepare_cached( fsl_cx * f, fsl_stmt ** tgt,
                                      char const * sql, ... );

/**
   va_list counterpart of fsl_cx_prepare_cached().
*/
FSL_EXPORT int fsl_cx_preparev_cached( fsl_cx * f, fsl_stmt ** tgt,
                                       char const * sql, va_list args );

/**
   Convenience form of fsl_db_exec() which uses f's main db handle.
   Returns 0 on success. On statement preparation or execution error,
   the db's error state is uplifted into f and that result is
   returned. Results are undefined if f or sql are NULL or otherwise
   invalid.
*/
FSL_EXPORT int fsl_cx_exec( fsl_cx * f, char const * sql, ... );

/**
   va_list counterpart of fsl_cx_exec().
*/
FSL_EXPORT int fsl_cx_execv( fsl_cx * f, char const * sql, va_list args );

/**
   The fsl_db_exec_multi() counterpart of fsl_cx_exec(). Results are
   undefined if f or sql are NULL or otherwise invalid.
*/
FSL_EXPORT int fsl_cx_exec_multi( fsl_cx * f, char const * sql, ... );

/**
   va_list counterpart of fsl_cx_exec_multi().
*/
FSL_EXPORT int fsl_cx_exec_multiv( fsl_cx * f, char const * sql,
                                   va_list args );

/**
   Wrapper around fsl_db_last_insert_id() which uses f's main
   database. Returns -1 if !f or f has no opened db.

   @see fsl_cx_db()
*/
FSL_EXPORT fsl_id_t fsl_cx_last_insert_id(fsl_cx * f);


/**
   Works similarly to fsl_stat(), except that zName must refer to a
   path under f's current checkout directory. Note that this stats
   local files, not repository-level content.

   If relativeToCwd is true then the filename is
   resolved/canonicalized based on the current working directory (see
   fsl_getcwd()), otherwise f's current checkout directory is used as
   the virtual root. This makes a subtle yet important difference in
   how the name is resolved. Applications taking input from users
   (e.g. CLI apps) will normally want to resolve from the current
   working dir (assuming the filenames were passed in from the
   CLI). In a GUI environment, where the current directory is likely
   not the checkout root, resolving based on the checkout root
   (i.e. relativeToCwd=false) is probably saner.

   Returns 0 on success. Errors include, but are not limited to:

   - FSL_RC_MISUSE if !zName.

   - FSL_RC_NOT_A_CKOUT if f has no opened checkout.

   - If fsl_is_simple_pathname(zName) returns false then
   fsl_ckout_filename_check() is used to normalize the name. If
   that fails, its failure code is returned.

   - As for fsl_stat().

   See fsl_stat() for more details regarding the tgt parameter.

   Symlinks are handled as fossil(1) handles checkout files: if
   fsl_cx_allows_symlinks() is true, a symlink is stat()ed itself
   and reported as FSL_FSTAT_TYPE_LINK. If it is false, the link is
   followed, so the result describes whatever it points to, and a
   dangling link fails with FSL_RC_NOT_FOUND. Either way, a symlink
   in the name's directory part is followed. fsl_stat() takes an
   explicit flag for callers which need one behaviour regardless of
   that setting.

   @see fsl_cx_stat2()
*/
FSL_EXPORT int fsl_cx_stat( fsl_cx * f, bool relativeToCwd,
                            char const * zName, fsl_fstat * 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
   absolute path is written to nameOut, otherwise a
   checkout-relative path is written.

   Returns 0 on success. On stat() error, nameOut is not updated,
   but after stat()'ing, allocation of memory for nameOut's buffer
   may fail.

   If zName ends with a trailing slash, that slash is retained in
   nameOut.

   Symlinks are resolved, or not, as described for fsl_cx_stat().

   @see fsl_cx_stat()
*/
FSL_EXPORT int fsl_cx_stat2( fsl_cx * f, bool relativeToCwd,
                             char const * zName,
                             fsl_fstat * tgt,
                             fsl_b * 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.

   Note that this does not save the option in the config database
   (repo-level "case-sensitive" boolean config option). It arguably
   should, and this behavior may change in the future.

   @see fsl_cx_is_case_sensitive()
*/
FSL_EXPORT void fsl_cx_case_sensitive_set(fsl_cx * f, bool caseSensitive);

/**
   Returns true if f is set for case-sensitive filename
   handling, else false. This setting is cached when a repository
   is opened, but passing true for the second argument forces the
   config option to be re-loaded from the repository db.
   Results are undefined if !f.

   When the repository does not set "case-sensitive", the default is
   false on Windows, Cygwin and macOS and true elsewhere, as in
   fossil(1). Case-insensitive comparison folds only the ASCII letters
   A to Z, as fossil(1)'s does.

   @see fsl_cx_case_sensitive_set()
*/
FSL_EXPORT bool fsl_cx_is_case_sensitive(fsl_cx *  const f, bool forceRecheck);

/**
   Compares two strings, represumably filenames, using either
   fsl_strcmp() or fsl_stricmp(), depending on f's filename
   case-sensitivity setting.
*/
FSL_EXPORT int fsl_cx_filename_cmp(fsl_cx * f, char const * z1, char const *z2);

/**
   If f is set to use case-sensitive filename handling,
   returns a pointer to an empty string, otherwise a pointer
   to the string "COLLATE nocase" is returned.
   Results are undefined if f is NULL. The returned bytes
   are static.

   @see fsl_cx_case_sensitive_set()
   @see fsl_cx_is_case_sensitive()
*/
FSL_EXPORT char const * fsl_cx_filename_collation(fsl_cx const * f);

/**
   Invokes macro E with 2 arguments one time for each of the core
   fsl_satype_e entries. Argument 1 is the entry's name (identifier)
   and argument 2 is its value (integer).
*/
#define fsl_satype_e_map(E) \
  E(FSL_SATYPE_INVALID, -1/** Sentinel value used for some error
                              reporting.*/)                    \
  E(FSL_SATYPE_ANY, 0/** Sentinel value used to mark a deck as being
                         "any" type. This is a placeholder on a deck's
                         way to completion. */) \
  E(FSL_SATYPE_CHECKIN, 1/** Indicates a "manifest" artifact (a checkin
                             record). */)                               \
  E(FSL_SATYPE_CLUSTER, 2/** Indicates a "cluster" artifact. These
                             are used during synchronization. */)   \
  E(FSL_SATYPE_CONTROL, 3/** Indicates a "control" artifact (a tag
                             change).*/) \
  E(FSL_SATYPE_WIKI, 4/** Indicates a "wiki" artifact. */) \
  E(FSL_SATYPE_TICKET, 5/** Indicates a "ticket" artifact. */) \
  E(FSL_SATYPE_ATTACHMENT, 6/** Indicates an "attachment" artifact
                                (used in the ticketing subsystem). */)  \
  E(FSL_SATYPE_TECHNOTE, 7/** Indicates a technote (formerly
                                "event") artifact (kind of like a blog
                                entry). */) \
  E(FSL_SATYPE_FORUMPOST, 8/** Indicates a forum post artifact (a
                               close relative of wiki pages).*/)

/**
   An enumeration of the types of structural artifacts used by
   Fossil. The numeric values of all entries before FSL_SATYPE_count,
   with the exception of FSL_SATYPE_INVALID, are a hard-coded part of
   the Fossil db architecture and must never be changed. Any after
   FSL_SATYPE_count are libfossil extensions.
*/
enum fsl_satype_e {
#define E(N,V) N = V,
  fsl_satype_e_map(E)
#undef E
  /**
     The number of non-pseudo artifact types in this enum.  It is used
     to size arrays and must have a value of the last entry in
     fsl_satype_e_map() plus 1.
  */
  FSL_SATYPE_count,

  /**  @deprecated
       Historical (deprecated) name for FSL_SATYPE_TECHNOTE.
  */
  FSL_SATYPE_EVENT = FSL_SATYPE_TECHNOTE,

  /**
     A pseudo-type for use with fsl_sym_to_rid() which changes the
     behavior of checkin lookups to return the RID of the start of the
     branch rather than the tip, with the caveat that the results are
     unspecified if the given symbolic name refers to multiple
     branches.

     fsl_satype_event_cstr() returns the same as FSL_SATYPE_CHECKIN for
     this entry.

     This entry IS NOT VALID for most APIs which require a fsl_satype_e
     value.
  */
  FSL_SATYPE_BRANCH_START = 100
};
typedef enum fsl_satype_e fsl_satype_e;

/**
   Returns some arbitrary but distinct string for the given
   fsl_satype_e. The returned bytes are static and
   NUL-terminated. Intended primarily for debugging and informative
   purposes, not actual user output.
*/
FSL_EXPORT char const * fsl_satype_cstr(fsl_satype_e t);

/**
   For a given artifact type, it returns the key string used in the
   event.type db table. Returns NULL if passed an unknown value or
   a type which is not used in the event table, otherwise the
   returned bytes are static and NUL-terminated.

   The returned strings for a given type are as follows:

   - FSL_SATYPE_ANY returns "*"
   - FSL_SATYPE_CHECKIN and FSL_SATYPE_BRANCH_START return "ci"
   - FSL_SATYPE_WIKI returns "w"
   - FSL_SATYPE_TAG returns "g"
   - FSL_SATYPE_TICKET returns "t"
   - FSL_SATYPE_EVENT returns "e"

   The other control artifact types do not have representations
   in the event table, and NULL is returned for them.

   All of the returned values can be used in comparison clauses in
   queries on the event table's 'type' field (but use GLOB instead
   of '=' so that the "*" returned by FSL_ATYPE_ANY can match).
   For example, to get the comments from the most recent 5 commits:

   ```
   SELECT
   datetime(mtime),
   coalesce(ecomment,comment),
   user
   FROM event WHERE type='ci'
   ORDER BY mtime DESC LIMIT 5;
   ```

   Where 'ci' in the SQL is the non-NULL return value from this
   function. When escaping this value via fsl_b_appendf() (or
   anything functionally similar), use the %%q/%%Q format
   specifiers to escape it.
*/
FSL_EXPORT char const * fsl_satype_event_cstr(fsl_satype_e t);

/**
   A collection of bitmaskable values indicating categories
   of fossil-standard glob sets. These correspond to the following
   configurable settings:

   ignore-glob, crnl-glob, binary-glob
*/
enum fsl_glob_category_e{
/** Sentinel entry. */
FSL_GLOBS_INVALID = 0,
/** Corresponds to the ignore-glob config setting. */
FSL_GLOBS_IGNORE = 0x01,
/** Corresponds to the crnl-glob config setting. */
FSL_GLOBS_CRNL = 0x02,
/** Corresponds to the binary-glob config setting. */
FSL_GLOBS_BINARY = 0x04,
/** A superset of all config-level glob categories. */
FSL_GLOBS_ANY = 0xFF
/*
  Potential TODO: add FSL_GLOBS_CURRENT_OP for use with SQL UDFs. The
  idea would be that SCM operations which could make use of
  op-specific glob lists, e.g., checkin/add/merge, could set a custom
  glob set as the current one and then access it via their SQL using
  `fsl_glob('_', ...)` or some such.
*/
};
typedef enum fsl_glob_category_e fsl_glob_category_e;

/**
   Checks one or more of f's configurable glob lists to see if str
   matches one of them. If it finds a match, it returns a pointer to
   the matching glob (as per fsl_glob_list_matches()), the bytes
   of which are owned by f and may be invalidated via modification
   or reloading of the underlying glob list. In generally the return
   value can be used as a boolean - clients generally do not need
   to know exactly which glob matched.

   gtype specifies the glob list(s) to check in the form of a
   bitmask of fsl_glob_category_e values. Note that the order of the
   lists is unspecified, so if that is important for you then be
   sure that gtype only specifies one glob list
   (e.g. FSL_GLOBS_IGNORE) and call it again (e.g. passing
   FSL_GLOBS_BINARY) if you need to distinguish between those two
   cases.

   str must be a non-NULL, non-empty empty string.

   Returns NULL !str, !*str, gtype does not specify any known
   glob list(s), or no glob match is found.

   Performance is, abstractly speaking, horrible, because we're
   comparing arbitrarily long lists of glob patterns against an
   arbitrary string. That said, it's fast enough for our purposes.
*/
FSL_EXPORT char const * fsl_cx_glob_matches( fsl_cx * f, int gtype,
                                             char const * str );

/**
   Converts a well-known fossil glob list configuration key to
   a fsl_glob_category_e value:

   - "ignore-glob" = FSL_GLOBS_IGNORE
   - "binary-glob" = FSL_GLOBS_BINARY
   - "crnl-glob" = FSL_GLOBS_CRNL
   - Anything else = FSL_GLOBS_INVALID

   To simplify this function's use via an SQL-accessible UDF, the
   `*-glob` names may be passed in without their `-glob` suffix,
   e.g. `"ignore"` instead of `"ignore-glob"`.
*/
FSL_EXPORT fsl_glob_category_e fsl_glob_name_to_category(char const * str);

/**
   Fetches f's glob list of the given category. If forceReload is true
   then the context will check whether the list has had any content
   added to its source since it was initially loaded.

   On success, returns 0 and assigns `*tgt` to the list (noting that
   it may be empty). On error `*tgt` is not modified.

   Returns FSL_RC_RANGE if gtype is not one of FSL_GLOBS_IGNORE,
   FSL_GLOBS_CRNL, or FSL_GLOBS_BINARY. Returns FSL_RC_OOM if there is
   an allocation error during list reloading. May return lower-level
   result codes from the filesystem or db layer if loading a given
   list fails.
*/
FSL_EXPORT int fsl_cx_glob_list( fsl_cx * f,
                                 fsl_glob_category_e gtype,
                                 fsl_list ** tgt,
                                 bool forceReload );

/**
   Sets f's hash policy and returns the previous value. If f has a
   repository db open then the setting is stored there and any error
   in setting it is placed into f's error state but otherwise ignored
   for purposes of this call.

   If p is FSL_HPOLICY_AUTO *and* the current repository contains any
   SHA3-format hashes, the policy is interpreted as FSL_HPOLICY_SHA3.

   This value is a *suggestion*, and may be trumped by various
   conditions, in particular in repositories containing older (SHA1)
   hashes.
*/
FSL_EXPORT fsl_hashpolicy_e fsl_cx_hash_policy_set(fsl_cx *f, fsl_hashpolicy_e p);

/**
   Returns f's current hash policy.
*/
FSL_EXPORT fsl_hashpolicy_e fsl_cx_hash_policy_get(fsl_cx const*f);

/**
   Returns a human-friendly name for the given policy, or NULL for an
   invalid policy value. The returned strings are the same ones used
   by fossil's hash-policy command.
*/
FSL_EXPORT char const * fsl_hash_policy_name(fsl_hashpolicy_e p);

/**
   Hashes all of pIn, appending the hash to pOut. Returns 0 on succes,
   FSL_RC_OOM if allocation of space in pOut fails. The hash algorithm
   used depends on the given fossil context's current hash policy and
   the value of the 2nd argument.

   If the 2nd argument is false, the hash is performed per the first
   argument's current hash policy. If the 2nd argument is true, the
   hash policy is effectively inverted. e.g. if the context prefers
   SHA3 hashes, the alternate form will use SHA1.

   Returns FSL_RC_UNSUPPORTED, without updating f's error state, if
   the hash is not possible due to conflicting values for the policy
   and its alternate. e.g. a context with policy FSL_HPOLICY_SHA3_ONLY
   will refuse to apply an SHA1 hash. Whether or not this result can
   be ignored is context-dependent, but it normally can be. This
   result is only possible when the 2nd argument is true.

   Returns 0 on success.
*/
FSL_EXPORT int fsl_cx_hash_buffer( const fsl_cx * f, bool useAlternate,
                                   fsl_b const * pIn,
                                   fsl_b * pOut);
/**
   The file counterpart of fsl_cx_hash_buffer(), behaving exactly the
   same except that its data source is a file and it may return
   various error codes from fsl_b_fill_from_filename(), in which
   case it updates f's error state with the file's name. Note that
   the contents of the file, not its name, are hashed.
*/
FSL_EXPORT int fsl_cx_hash_filename( fsl_cx * f, bool useAlternate,
                                     const char * zFilename, fsl_b * pOut);

/**
   Works like fsl_getcwd() but updates f's error state on error and
   appends the current directory's name to the given buffer. Returns 0
   on success.
*/
FSL_EXPORT int fsl_cx_getcwd(fsl_cx * f, fsl_b * pOut);

/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_txn_level(), or 0 if f has no db opened.

   @see fsl_cx_db()
*/
FSL_EXPORT int fsl_cx_txn_level(fsl_cx * f);
/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_txn_begin().
*/
FSL_EXPORT int fsl_cx_txn_begin(fsl_cx * f);
/**
   Like fsl_cx_txn_begin(), but also takes the write lock on each db
   in roles, a mask of FSL_DBROLE_REPO and FSL_DBROLE_CKOUT, which is
   attached and which the transaction has not write-locked already, as
   fossil(1)'s BEGIN IMMEDIATE does. Start every transaction which will
   write the repository or checkout db with this.

   fsl_cx_txn_begin() starts a deferred transaction. When a deferred
   transaction which has read a db then writes it while another
   connection holds that db's write lock, SQLite returns SQLITE_BUSY at
   once, without calling the busy handler, since waiting could
   deadlock, and the write fails with FSL_RC_LOCKED. A transaction
   which takes the lock before it reads waits in the busy handler for
   the other writer instead. Inside a transaction which has already
   read a db without write-locking it, taking that db's lock can still
   fail at once.

   On error, this ends the transaction level it began and updates f's
   error state.
*/
FSL_EXPORT int fsl_cx_txn_begin_write(fsl_cx * f, int roles);
/**
   Returns the same as passing fsl_cx_db() and the 2nd/3rd arguments
   to fsl_db_txn_end_v2() and propagates any db errors from that
   operation into f.
*/
FSL_EXPORT int fsl_cx_txn_end_v2(fsl_cx * f, bool keepSavepoint,
                                 bool bubbleRollback);

#if 0
/* Legacy behavior. */
#define fsl_cx_txn_end(F, RollbackMode) \
  fsl_cx_txn_end_v2((F), !(RollbackMode), !!(RollbackMode))
#else
/* What we probably should have been doing instead but
   now breaks stuff. */
#define fsl_cx_txn_end(F, RollbackMode) \
  fsl_cx_txn_end_v2((F), !(RollbackMode), false)
#endif
/**
   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().

   The 2nd argument bitwise copied into f's internal confirmer
   object. If the 2nd argument is NULL, f's confirmer is cleared,
   which will cause fsl_cx_confirm() to use certain default responses
   (see that function for details).

   If the final argument is not NULL then the previous confirmer is
   bitwise copied to it.

   @see fsl_confirm_callback_f
   @see fsl_cx_confirm()
   @see fsl_cx_confirmer_get()
*/
FSL_EXPORT void fsl_cx_confirmer(fsl_cx * f,
                                 fsl_confirmer const * newConfirmer,
                                 fsl_confirmer * prevConfirmer);
/**
   Stores a bitwise copy of f's current confirmer object into *dest. Can
   be used to save the confirmer before temporarily swapping it out.

   @see fsl_cx_confirmer()
*/
FSL_EXPORT void fsl_cx_confirmer_get(fsl_cx const * f, fsl_confirmer * dest);

/**
   If fsl_cx_confirmer() was used to install a confirmer callback in f
   then this routine calls that confirmer and returns its result code
   and its answer via *outAnswer. If no confirmer is currently
   installed, it responds with default answers, depending on the
   eventId:

   - FSL_CEVENT_OVERWRITE_MOD_FILE: FSL_CRESPONSE_NEVER

   - FSL_CEVENT_OVERWRITE_UNMGD_FILE: FSL_CRESPONSE_NEVER

   - FSL_CEVENT_RM_MOD_UNMGD_FILE: FSL_CRESPONSE_NEVER

   - FSL_CEVENT_MULTIPLE_VERSIONS: FSL_CRESPONSE_CANCEL

   Those are not 100% set in stone and are up for reconsideration.

   If a confirmer has been installed, this function does not modify
   outAnswer->response if the installed confirmer does not. Thus
   routines should set it to some acceptable default/sentinel value
   before calling this, to account for callbacks which ignore the
   given detail->eventId.

   If a confirmer callback responds with FSL_CRESPONSE_ALWAYS or
   FSL_CRESPONSE_NEVER, the code which is requesting confirmation must
   honor that by *NOT* calling the callback again for the current
   processing step of that eventId. e.g. if a loop asks for
   confirmation of FSL_CEVENT_RM_MOD_FILE and any response is one of
   the above, that one loop must not ask for confirmation again, and
   must instead accept that response for future queries within the
   same logical library operation (e.g. one checkout-update
   cycle). This is particularly important for applications which
   interactively present the question to the user for confirmation so
   that users have a way to *not* get spammed with a confirmation
   message showing up for each and every one of an arbitrary number of
   confirmations.

   @see fsl_confirm_callback_f
   @see fsl_cx_confirmer()
*/
FSL_EXPORT int fsl_cx_confirm(fsl_cx * f, fsl_confirm_detail const * detail,
                              fsl_confirm_response *outAnswer);

/**
   Sets f's is-interrupted flag and, if the 3rd argument is not NULL,
   its error state. The is-interrupted flag is separate from f's
   normal error state and is _not_ cleared by fsl_cx_err_reset(). To
   clear the interrupted flag, call this function with values of 0 and
   NULL for the 2nd and 3rd arguments, respectively. This flag is
   _not_ fetched by fsl_cx_err_get() but:

   1) If this function is passed a non-NULL 3rd argument, then the
   normal error state, as well as the is-interrupted flag, is updated
   and can be fetched normally via fsl_cx_err_get(). However...

   2) It is possible for any error message provided via this routine
   to be overwritten or reset by another routine before the
   interrupted flag can be acted upon, whereas the interrupted flag
   itself can only be modified by this routine.

   Returns its 2nd argument on success or FSL_RC_OOM if given a
   formatted string and allocation of it fails. In either case, the
   interrupted flag, as returned by fsl_cx_interrupted(), is _always_
   assigned to the passed-in code.

   If passed a code of 0, the is-interrupted flag is reset but the
   general error state is not modified.

   Results are undefined if this function is called twice concurrently
   with the same fsl_cx object. i.e. all calls for a given fsl_cx must
   come from a single thread. Results are also undefined if it is
   called while f is in its finalization phase (typically during
   application shutdown).

   ACHTUNG: this is new as of 2021-11-18 and is not yet widely honored
   within the API.

   Library maintenance notes:

   - Long-running actions which honor this flag should, if it is set,
   clear it before returning its error code. Also, they should prefer
   to pass on non-interruption errors if one has been set set, in
   addition to clearing the interruption flag. Only routines which
   honor this flag, or top-most routines in the application, should
   ever clear this flag.

   @see fsl_cx_interrupted()
   @see fsl_cx_interruptv()
*/
FSL_EXPORT int fsl_cx_interrupt(fsl_cx * f, int code,
                                const char * fmt, ...);

/**
   The va_list counterpart of fsl_cx_interrupt().
*/
FSL_EXPORT int fsl_cx_interruptv(fsl_cx * f, int code, char const * fmt, va_list args);

/**
   If f's is-interrupted flag is set, this function returns its
   value. Note that there is inherently a race condition when calling
   fsl_cx_interrupt() (to set the flag) from another thread (e.g. a
   UI thread while showing a progress indicator).
*/
FSL_EXPORT int fsl_cx_interrupted(fsl_cx const * f);

/**
   Returns true if f has the "allow-symlinks" repo-level configuration
   option set to a truthy value, else returns false. That setting is
   cached to avoid performing a db lookup on each call, but passing
   true for the second argument causes the repository to be
   re-checked.
*/
FSL_EXPORT bool fsl_cx_allows_symlinks(fsl_cx * f, bool forceRecheck);

/**
   Closes any opened repository and/or checkout database(s) opened by
   f, freeing any associated resources and clearing out f's current
   user name. Returns 0 on success or if no dbs are opened (noting
   that this does NOT close the separate global configuration db: see
   fsl_config_close()). Returns FSL_RC_MISUSE if the opened SCM db(s)
   have an opened transaction, but that behaviour may change in the
   future to force a rollback and close the database(s).
*/
FSL_EXPORT int fsl_close_scm_dbs(fsl_cx * f);

/**
   Shorthand for calling both fsl_close_scm_dbs() and, if it succeeds,
   fsl_config_close(). Returns the result of the former if it fails,
   else returns the result of the latter.
*/
FSL_EXPORT int fsl_close_dbs(fsl_cx * f);

/**
   Extracts the "last-sync-url" entry from f's repository
   configuration and appends it to tgt. On success, returns 0. Returns
   FSL_RC_NOT_A_REPO if f has no opened repository, FSL_RC_NOT_FOUND
   if the repository has no such entry, else the result of
   fsl_config_get_buffer(). On error, f's error state describes the
   problem.
*/
FSL_EXPORT int fsl_cx_last_sync_url(fsl_cx * f, fsl_b *tgt);

/**
   Flags for use with fsl_buildinfo().
*/
enum fsl_buildinfo_e {
  FSL_BUILDINFO_VERSION,
  FSL_BUILDINFO_VERSION_HASH,
  FSL_BUILDINFO_VERSION_TIMESTAMP,
  FSL_BUILDINFO_CONFIG_TIMESTAMP
};

/**
   Fetches the piece of library-level build information specified by
   its argument. If no such info is available, NULL is returned.
*/
FSL_EXPORT char const * fsl_buildinfo(enum fsl_buildinfo_e what);

/**
   If both where and where->callback are not NULL, msg is passed to
   where->callback and its result is returned, else this is a no-op
   and 0 is returned.

   Results are undefined if msg is NULL or either argument is
   improperly populated.
*/
FSL_EXPORT int fsl_msg_emit(fsl_msg const * msg,
                            fsl_msg_listener const * where);

/**
   If f has a fsl_msg listener, a fsl_msg composed from the given type
   and payload is passed to the the listener and its result is
   returned, else this is a no-op and 0 is returned. Results are
   undefined if the data type of p does not match that described for
   the given type.
*/
FSL_EXPORT int fsl_cx_emit(fsl_cx * const f, fsl_msg_e type, void const * p);

/**
   va_list counterpart of fsl_cx_emit() which emits a
   fsl_appendf()-formatted message as a string or a buffer, depending
   on the message type.

   It may (and does) fatally fail if passed a message type for which
   (type & FSL_MSG_mask_type) is not one of FSL_MSG_type_string or
   FSL_MSG_type_buffer.
*/
FSL_EXPORT int fsl_cx_emitfv(fsl_cx * f, fsl_msg_e type, char const * zFmt,
                             va_list args);

/** Elipsis counterpart of fsl_cx_emitfv(). */
FSL_EXPORT int fsl_cx_emitf(fsl_cx *f, fsl_msg_e type, char const * zFmt, ...);

/**
   Replace's f's current fsl_msg listener with a bitwise copy of
   pNew. If pOld is not NULL then a bitwise copy of the previous
   listener is written there.
*/
FSL_EXPORT void fsl_cx_listener_replace(fsl_cx * f, fsl_msg_listener const *pNew,
                                        fsl_msg_listener * pOld);

/**
   Borrows a buffer from f's buffer recycling pool, allocating one if
   needed. It returns NULL only on allocation error. If f is currently
   flagged with a FSL_RC_OOM error state when this is called, it
   becomes a no-op and NULL is returned. Similarly, if allocation
   fails, f's error state is set.

   This transfers ownership of the buffer to the caller, who is
   obligated to eventually do ONE of the following:

   - Pass it to fsl_cx_b_return() with the same f argument.

   - Pass it to fsl_b_clear() then fsl_free().

   The purpose of this function is a memory reuse optimization.  Much,
   perhaps even most, libfossil-using code uses transient buffers
   something or other and this gives them a way to reuse buffers.

   It is not recommended to use this for buffers which invariably take
   over ownership of the underlying memory, e.g. by returning it as a
   (char*) to a caller, because that defeats the purpose of this
   cache: re-using the buffer memory (as distinct from the fsl_b
   instances themselves). Such (mis)uses might end up stealing 2mb of
   otherwise reusable memory to return a short string like a user name
   or some such.

   Potential TODO: How this pool optimizes (or not) buffer allotment
   is an internal detail. Maybe add an argument which provides a hint
   about the buffer usage.

   Example usage:

   @code
   fsl_b * const b = fsl_cx_b_borrow(f, false);
   if( !b ) return FSL_RC_OOM;
   ... use b...
   fsl_cx_b_return(f, b);
   @endcode
*/
FSL_EXPORT fsl_b * fsl_cx_b_borrow(fsl_cx *f);

/**
   Returns a buffer borrowed from fsl_cx_b_borrow(), transferring
   ownership back to f. Passing a non-NULL b which was not returned
   by fsl_cx_b_borrow() invokes undefined behavior (possibly delayed
   until the list is cleaned up). To simplify usage, b may be NULL.

   After calling this, b must be considered "freed" - it must not be
   used again. This function is free (as it were) to immediately free
   the object's memory instead of recycling it.
*/
FSL_EXPORT void fsl_cx_b_return(fsl_cx *f, fsl_b *b);

/**
   Works exactly like fsl_cx_b_return() except that if b is not NULL
   and b->capacity>0 then the first b->capacity bytes of b->mem are
   zeroed out before the buffer is returned to the pool.
*/
FSL_EXPORT void fsl_cx_b_return_wipe(fsl_cx *f, fsl_b *b);


#if 0
/**
   DO NOT USE - not yet tested and ready.

   Returns the result of either localtime(clock) or gmtime(clock),
   depending on f:

   - If f is NULL, returns localtime(clock).

   - If f has had its FSL_CX_F_LOCALTIME_GMT flag set (see
   fsl_cx_flag_set()) then returns gmtime(clock), else
   localtime(clock).

   If clock is NULL, NULL is returned.

   fsl_cx instances default to using UTC for everything, which is the
   opposite of fossil(1).
*/
FSL_EXPORT struct tm * fsl_cx_localtime( fsl_cx const * f, const time_t * clock );

/**
   Equivalent to fsl_cx_localtime(NULL, clock).
*/
FSL_EXPORT struct tm * fsl_localtime( const time_t * clock );

/**
   DO NOT USE - not yet tested and ready.

   This function passes (f, clock) to fsl_cx_localtime(),
   then returns the result of mktime(3) on it. So...
   it adjusts a UTC Unix timestamp to either the same UTC
   local timestamp or to the local time.
*/
FSL_EXPORT time_t fsl_cx_time_adj(fsl_cx const * f, time_t clock);
#endif

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif /* ORG_FOSSIL_SCM_FSL_CORE_H_INCLUDED */
/* end of file include/fossil-scm/core.h */
/* start of file include/fossil-scm/db.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_DB_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_DB_H_INCLUDED
/*
  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-FileType: Code

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


  ******************************************************************************
  This file declares public APIs for working with fossil's database
  abstraction layer.
*/

/*
  We don't _really_ want to include sqlite3.h at this point, but if we
  do not then we have to typedef the sqlite3 struct here and that
  breaks when client code includes both this file and sqlite3.h.
*/

#if defined(__cplusplus)
extern "C" {
#endif

#if 0
/* We can't do this because it breaks when clients include both
   this header and sqlite3.h. Is there a solution which lets us
   _not_ include sqlite3.h from this file and also compiles when
   clients include both?
*/
#if !defined(SQLITE_OK)
typedef struct sqlite3 sqlite3;
#endif
#endif

/**
   Flags for use with fsl_db_open() and friends.
*/
enum fsl_db_open_flags_e {
/**
   The "no flags" value.
*/
FSL_DB_OPEN_NONE = 0,

/**
   Flag for fsl_db_open() specifying that the db should be opened
   in read-only mode.
*/
FSL_DB_OPEN_RO = 0x01,

/**
   Flag for fsl_db_open() specifying that the db should be opened
   in read-write mode, but should not create the db if it does
   not already exist.
*/
FSL_DB_OPEN_RW = 0x02,

/**
   Flag for fsl_db_open() specifying that the db should be opened in
   read-write mode, creating the db if it does not already exist.

   ACHTUNG: this flag propagates from an OPEN'd db handle to the
   ATTACH SQL command run via that handle, such that ATTACHing a
   non-existing db file will fail if the FSL_DB_OPEN_CREATE flag is
   _not_ used. Historically (prior to 2022-01-01), fsl_db_open() would
   automatically apply this flag to DBs named ":memory:" or ""
   (unnamed temp dbs), but that ended up causing a full day of
   confusion, hair-pulling, and bug-hunting when lib-level code was
   migrated from an anonymous temp db to a "real" db and ATTACH
   suddenly failed. As of 2022-01-01, fsl_db_open() always takes the
   open-mode flags as provided by the client, regardless of the DB
   name, and never automatically rewrites them to include
   FSL_DB_OPEN_CREATE.
*/
FSL_DB_OPEN_CREATE = 0x04,

/**
   Shorthand for RW+CREATE flags.
*/
FSL_DB_OPEN_RWC = FSL_DB_OPEN_RW | FSL_DB_OPEN_CREATE,

/**
   Currently unused. It "should" be used to tell fsl_repo_open_xxx()
   to confirm that the db is a repository, but how to propagate
   that through the corresponding APIs is not currently clear.
*/
FSL_DB_OPEN_SCHEMA_VALIDATE = 0x20,

/**
   Used by fsl_db_open() to to tell the underlying db connection to
   trace all SQL to stdout. This is often useful for testing,
   debugging, and learning about what's going on behind the scenes.
*/
FSL_DB_OPEN_TRACE_SQL = 0x40
};

/**
   A level of indirection to "hide" the actual db driver
   implementation from the public API. It uses SQLite3 but this gives
   us a comforting level of abstraction.

   Sidebar: at the time this code was originally written, sqlite4 was
   in an experimental stage to explore a new storage engine which, it
   was hoped, would speed up sqlite considerably. It ended up never
   leaving that stage because the performance gains of the storage
   engine did not justify such a significant upheaval. Even so,
   sqlite4 "might" come around sometime within the lifetime of this
   project, so it behooves us to abstract away this type from the
   public API.
*/
typedef sqlite3 fsl_db_t;

/**
   Bitmasks for use with fsl_db_event_e.
*/
enum fsl_db_event_mask_e {
  FSL_DB_EVENT_mask_reserved     = 0x7ffff000,

  /**
     Describes a data type for fsl_db_event::payload.
  */
  FSL_DB_EVENT_mask_payload      = 0x00000f00,

  /** (fsl_b const *) payload. */
  FSL_DB_EVENT_payload_buffer    = 0x00000100,

  /**
     All concrete message IDs are masked with this.
  */
  FSL_DB_EVENT_mask_id           = 0x000000ff,

  /**
     Convenience entry for use with fsl_db_event_listener().
  */
  FSL_DB_EVENT_listen_all        = FSL_DB_EVENT_mask_id
};

/**
   A map of fsl_db_event types.
*/
#define fsl_db_event_map(E)          \
  E(FSL_DB_EVENT_BEGIN,        0x01) \
  E(FSL_DB_EVENT_COMMIT,       0x02) \
  E(FSL_DB_EVENT_ROLLING_BACK, 0x04) \
  E(FSL_DB_EVENT_ROLLED_BACK,  0x08) \
  E(FSL_DB_EVENT_CLOSING,      0x10) \
  E(FSL_DB_EVENT_TRACE_SQL,    0x20  \
    | FSL_DB_EVENT_payload_buffer    \
    /*unexpanded SQL*/)              \
  E(FSL_DB_EVENT_TRACE_SQLX,   0x40  \
    | FSL_DB_EVENT_payload_buffer    \
    /*expanded SQL*/)

/**
   A flag type for use with fsl_db_event_f() implementations.
*/
enum fsl_db_event_e {
#define E(X,V) X = V,
  fsl_db_event_map(E)
#undef E
};
typedef enum fsl_db_event_e fsl_db_event_e;

/**
   Convenience FSL_DB_EVENT_... entries which cannot be defined until
   after fsl_db_event_e is.
*/
enum fsl_db_event_mask2_e {
  /** Mask of the IDs of transaction-specific events. */
  FSL_DB_EVENT_group_txn = FSL_DB_EVENT_mask_id
  & (FSL_DB_EVENT_BEGIN | FSL_DB_EVENT_COMMIT
     | FSL_DB_EVENT_ROLLING_BACK | FSL_DB_EVENT_ROLLED_BACK),
  /** Mask of the IDs of SQL tracing events. */
  FSL_DB_EVENT_group_sql_trace = FSL_DB_EVENT_mask_id
  & (FSL_DB_EVENT_TRACE_SQL
     | FSL_DB_EVENT_TRACE_SQLX)
};

/**
   An "event" message type for use with fsl_db.
*/
struct fsl_db_event {
  /**
     The event-firing db.
  */
  fsl_db * db;
  /**
     The event listener state.
  */
  void * state;
  /**
     A message-type-specific payload. Its native type is encoded in
     this->type.
  */
  void const * payload;
  /**
     Event type.
  */
  fsl_db_event_e type;
  /**
     The db's current savepoint level (because most events deal with
     transactions and this info has proven useful in downstream code).
     This will usually have a value of 1 or higher, the exception
     being FSL_DB_EVENT_CLOSING, where a that level is 0.
  */
  int savepointLevel;
};
typedef struct fsl_db_event fsl_db_event;

/**
   An event callback for fsl_db objects, primarily for communicating
   on-transaction-start/end. Each fsl_db instance may have a single
   one of these installed and it gets called via at various points to
   fire well-defined events.

   When the docs below refer to BEGIN and COMMIT, they're actually
   referring to their SAVEPOINT counterparts. That's partly
   historical, from a time when this API uses BEGIN/COMMIT, but it's
   also thought to be clearer terminology here.

   Doc references below to fsl_db_txn_begin() and fsl_db_txn_end()
   also imply their v2 variants.

   ev->state holds the state registered with the callback in
   fsl_db_event_listener().

   ev->type explains the nature of the event:

   - FSL_DB_EVENT_CLOSING is fired early on in fsl_db_close(). If
   closing is forced to roll back savepoints, those events are fired
   first and their result codes are ignored. The result of this event
   is likewise also ignored. Though the callback may (technically
   speaking) still perform db operations, it must never start a new
   transaction (unless it also closes it before returning) nor may it
   close the db object. If either of those conditions is violated,
   results are undefined. This event is _not_ fired when a DETACH'ing
   database, as this API does not have any insight into when ATTACH
   and DETACH are used.

   - FSL_DB_TXN_BEGIN is passed immediately after fsl_db_txn_begin()
   starts the transaction. If this function returns non-0, the
   transaction is _immediately_ rolled back but the rollback event is
   not triggered for this particular failure. Unless the starting of a
   new transaction level actually fails, the callback's return value
   because the result of fsl_db_txn_begin().

   - FSL_DB_TXN_COMMIT is called immediately before fsl_db_txn_end()
   runs COMMIT on the db. If it returns non-0, the pending COMMIT is
   replaced with a ROLLBACK and that result code becomes the result of
   fsl_db_txn_end().  The rollback events are _not_ triggered in this
   case.

   - FSL_DB_TXN_ROLLING_BACK is called immediately before
   fsl_db_txn_end() runs ROLLBACK on the db. If it returns non-0 but
   the SQL-level succeeds, its result becomes the result of
   fsl_db_txn_end(), but it does not cancel the pending db-side
   ROLLBACK.  Only one of FSL_DB_TXN_COMMIT or FSL_DB_TXN_ROLLING_BACK
   is invoked for a given call to fsl_db_txn_end(). If
   FSL_DB_TXN_COMMIT returns non-zero, no FSL_DB_TXN_ROLLING_BACK
   invocation is made.

   - FSL_DB_TXN_ROLLED_BACK is called immediately after
   fsl_db_txn_end() has run a ROLLBACK. If this function returns non-0
   but both the the SQL-level rollback and the FSL_DB_TXN_ROLLING_BACK
   event succeededsucceeded, this event's result becames the result
   value of fsl_db_txn_end().

   To summarize, priority of determining which error code to return
   from fsl_db_txn_end(), in combination with the potential for errors
   when submitting the resulting SQL to commit/roll back, are:

   - Commit: COMMIT event (this callback) -> SQLite step()

   - Rollback: ROLLING_BACK event -> SQLite step() -> ROLLBACK event

   This hook is NOT called for IMPLICIT transactions. It is only
   called for explicit calls to fsl_db_txn_begin(), fsl_db_txn_end(),
   and fsl_db_rollback_force(). Clients must never execute SQL-level
   (BEGIN, COMMIT, ROLLBACK, SAVEPOINT) calls on fsl_db instances or
   they risk getting it out of sync. There are exceptions where
   they're safe but, generically speaking, they're not.

   @see fsl_db_event_listener()
*/
typedef int (*fsl_db_event_f)(fsl_db_event const * e);

/**
   Db handle wrapper class. Each instance wraps a single sqlite
   database handle. Though this type's interface is not opaque, it is
   never legal for clients to directly manipulate the members.

   Fossil is built upon sqlite3, but this abstraction is intended to
   hide that, insofar as possible, from clients so as to simplify an
   eventual port from v3 to v4. Clients should avoid relying on the
   underlying db being sqlite (or at least not rely on a specific
   version), but may want to register custom functions with the driver
   (or perform similar low-level operations) and the option is left
   open for them to access that handle via the fsl_db::dbh member. In
   practice, library clients do not ever need to use the underlying
   sqlite API.

   When sqlite is compiled into libfossil (configure
   --with-sqlite=tree, which is the default), the
   shared library does not export sqlite's API. A client which calls
   sqlite3_*() on fsl_db::dbh must then link against the static
   library, or use a libfossil built against the same shared sqlite
   library as the client, so that one sqlite implementation owns each
   handle.

   @see fsl_db_open();
   @see fsl_db_close();
   @see fsl_stmt
*/
struct fsl_db {

  /**
     Underlying db driver handle.
  */
  fsl_db_t * dbh;

  /**
     Holds error state from the underlying driver.  fsl_db and
     fsl_stmt operations which fail at the driver level "should"
     update this state to include error info from the driver.
     fsl_cx APIs which fail at the DB level uplift this (using
     fsl_error_swap()) so that they can pass it on up the call chain.
  */
  fsl_error error;

  /**
     Holds the file name used when opening this db. Might not refer to
     a real file (e.g. might be ":memory:" or "" (similar to
     ":memory:" but may swap to temp storage).

     Design note: we currently hold the name as it is passed to the
     db-open routine, without canonicalizing it. That is very possibly
     a mistake, as it makes it impossible to properly compare the name
     to another arbitrary checkout-relative name for purposes of
     fsl_reserved_fn_check(). For purposes of fsl_cx we currently
     (2021-03-12) canonicalize db's which we fsl_db_open(), but not
     those which we ATTACH (which includes the repo and checkout
     dbs). We cannot reasonably canonicalize the repo db filename
     because it gets written into the checkout db so that the checkout
     knows where to find the repository. History has shown that that
     path needs to be stored exactly as a user entered it, which is
     often relative.

     Memory is owned by this object.
  */
  char * filename;

  /**
     Holds the database name for use in creating queries.
     Might or might not be set/needed, depending on
     the context.

     Memory is owned by this object.
  */
  char * name;
  /**
     Describes what role(s) this db connection plays in fossil (if
     any). This is a bitmask of fsl_dbrole_e values, and a db
     connection may have multiple roles. This is only used by the
     fsl_cx-internal API.
  */
  fsl_flag16_t role;

  /**
     Private implementation details.
  */
  struct {
    /**
       Debugging/test counter. Closing a db with opened statements
       might assert() or trigger debug output when the db is closed.
    */
    int openStatementCount;

    /**
       Internal flags.
    */
    fsl_flag32_t flags;

    struct {
      /** Event listener callback. */
      fsl_db_event_f f;
      /** Impl-specific state for f. */
      void * state;
      /**
         The FSL_DB_EVENT_mask_id-masked part of event IDs to
         fire the callback for.
      */
      fsl_flag32_t maskIds;
      /** Older-style (pre-fsl_db_event) trace output channel. */
      FILE * fpTrace;
    } event;

    /** Transaction-related state. */
    struct {
      /** Counter for fsl_db_txn_begin/end(). */
      int level;
      /** Prepared statements for SAVEPOINT management. */
      sqlite3_stmt * sSavepoint;
      /** Prepared statements for SAVEPOINT RELEASE. */
      sqlite3_stmt * sRelease;
      /** Prepared statements for ROLLBACK TO SAVEPOINT. */
      sqlite3_stmt * sRollback;
    } txn;

    /** State for use with fsl_db_prepare_cached(). */
    struct {

      /**
         An internal cache of "static" queries - those which do not rely
         on call-time state unless that state can be bind()ed. Holds a
         linked list of (fsl_stmt*) instances, managed by the
         fsl_db_prepare_cached() and fsl_stmt_cached_yield() APIs.

         @see fsl_db_prepare_cached()
      */
      fsl_stmt * head;
    } stCache;
    /**
       Internal buffer to reduce reallocations caused via
       fsl_db_prepare_cached(), fsl_db_see_check(),
       and perhaps other internals.
    */
    fsl_b buffer;

    /**
       A marker which tells fsl_db_close() whether or not
       fsl_db_malloc() allocated this instance (in which case
       fsl_db_close() will fsl_free() it) or not (in which case it
       does not fsl_free() it).
    */
    void const * allocStamp;

    /**
       For a fsl_cx's main db: the connection's registry of the
       contexts using it, the context owning this db, its id there,
       and, where they differ from fsl_db_role_name()'s, the names of
       its repository and checkout schemas. Library-internal.

       zCkoutPrefix is set while the checkout's tables are tables of
       the host's main db named with that prefix
       (fsl_repo_open_ckout_opt::hostTablePrefix), in which case
       zCkout is "main". Likewise zRepoPrefix and zRepo for the
       repository's tables (fsl_repo_open_host()).
    */
    struct {
      void * reg;
      void * cx;
      unsigned id;
      char * zRepo;
      char * zCkout;
      char * zCkoutPrefix;
      char * zRepoPrefix;
    } share;
  } impl;
};
/**
   Empty-initialized fsl_db structure, intended for const-copy
   initialization.
*/
#define fsl_db_empty_m {       \
  .dbh = NULL,                 \
  .error = fsl_error_empty_m,  \
  .filename = NULL,            \
  .name = NULL,                \
  .role = 0,                   \
  .impl = {                    \
    .openStatementCount = 0,   \
    .flags = 0,                \
    .event = {                 \
      .f=NULL,                 \
      .state=NULL,             \
      .maskIds=0,              \
      .fpTrace=NULL            \
    },                         \
    .txn = {                   \
      .level = 0,              \
      .sSavepoint=NULL,        \
      .sRelease=NULL,          \
      .sRollback=NULL          \
    },                         \
    .stCache = {               \
      .head = NULL             \
    },                         \
    .buffer = fsl_b_empty_m, \
    .allocStamp = NULL,        \
    .share = {                 \
      .reg = NULL, .cx = NULL, .id = 0, \
      .zRepo = NULL, .zCkout = NULL,    \
      .zCkoutPrefix = NULL,             \
      .zRepoPrefix = NULL               \
    }                          \
  }                            \
}

/**
   Empty-initialized fsl_db structure, intended for copy
   initialization.
*/
FSL_EXPORT const fsl_db fsl_db_empty;

/**
   If db is not NULL then this function returns its name (the one used
   to fsl_db_open() it). The bytes are valid until the db connection
   is closed or until someone mucks with db->filename. If len is not
   NULL then *len is (on success) assigned to the length of the
   returned string, in bytes. The string is NUL-terminated, so
   fetching the length (by passing a non-NULL 2nd parameter) is
   optional but sometimes useful to eliminate a downstream call to
   fsl_strlen().

   Results are undefined if db is NULL or was improperly initialized.
   Will return NULL if db was properly initialized (via copying
   fsl_db_empty) but has not yet been opened.
*/
FSL_EXPORT char const * fsl_db_filename(fsl_db const * db, fsl_size_t * len);

typedef sqlite3_stmt fsl_stmt_t;
/**
   Represents a prepared statement handle.
   Intended usage:

   ```
   fsl_stmt st = fsl_stmt_empty;
   int rc = fsl_db_prepare( db, &st, "..." );
   if(rc){ // Error!
   assert(!st.stmt);
   // db->error might hold driver-level error details.
   }else{
   // use st and eventually finalize it:
   fsl_stmt_finalize( &st );
   }
   ```


   Script binding implementations can largely avoid exposing the
   statement handle (and its related cleanup ordering requirements)
   to script code. They need to have some mechanism for binding
   values to SQL (or implement all the escaping themselves), but
   that can be done without exposing all of the statement class if
   desired. For example, here's some hypothetical script code:

   ```
   var st = db.prepare(".... where i=:i and x=:x");
   // st is-a Statement, but we need not add script bindings for
   // the whole Statement.bind() API. We can instead simplify that
   // to something like:
   try {
   st.exec( {i: 42, x: 3} )
   // or, for a SELECT query:
   st.each({
   bind{i:42, x:3},
   rowType: 'array', // or 'object'
   callback: function(row,state,colNames){ print(row.join('\t')); },
   state: {...callback function state...}
   });
   } finally {
   st.finalize();
   // It is critical that st gets finalized before its DB, and
   // that'shard to guaranty if we leave st to the garbage collector!
   }
   // see below for another (less messy) alternative
   ```

   Ideally, script code should not have direct access to the
   Statement because managing lifetimes can be difficult in the
   face of flow-control changes caused by exceptions (as the above
   example demonstrates). Statements can be completely hidden from
   clients if the DB wrapper is written to support it. For example,
   in pseudo-JavaScript that might look like:

   ```
   db.exec("...where i=? AND x=?", 42, 3);
   db.each({sql:"select ... where id<?", bind:[10],
   rowType: 'array', // or 'object'
   callback: function(row,state,colNames){ print(row.join('\t')); },
   state: {...arbitrary state for the callback...}
   });
   ```
*/
struct fsl_stmt {
  /**
     The db which prepared this statement.
  */
  fsl_db * db;

  /**
     Underlying db driver-level statement handle. Clients should
     not rely on the specify concrete type if they can avoid it, to
     simplify an eventual port from sqlite3 to sqlite4.
  */
  fsl_stmt_t * stmt;

  /**
     Describes the database(s) used by this statement handle, in the
     form of a bitmask of fsl_dbrole_e values. This is a bit of a
     kludge used to allow the internals to flush cached statements
     from the fossil global config db when detaching that database.
     Code which requires this to be set must set it itself and must
     set it correctly. Hypothetically, no client-level code requires
     it but _some_ libfossil-internal code does.
  */
  fsl_flag16_t role;

  /**
     The SQL used to prepare this statement. We keep this, rather than
     simply fetching the SQL on demand, only for facilitate
     fsl_db_prepare_cached(). But since we have it, and it might be
     interesting, in client code, it's a public part of the interface.
  */
  fsl_b sql;

  /**
     The number of times this statement has fetched a row via
     fsl_stmt_step(). This is primarily intended for use by
     fsl_stmt_each_f() implementations so that they can keep track of
     when to emit a header (or similar pre-first-row setup).
  */
  fsl_size_t rowCount;

  /**
     Private implementation details.
  */
  struct {

    /**
       Internal state flags.
    */
    fsl_flag16_t flags;

    /**
       Internal use only: counts the number of times this query has
       been resolved as cached via fsl_db_prepare_cached().
    */
    uint32_t cachedHits;

    /**
       For _internal_ use in creating linked lists. Clients _must_not_
       modify this field.
    */
    fsl_stmt * next;

    /**
       A marker which tells fsl_stmt_finalize() whether or not
       fsl_stmt_malloc() allocated this instance (in which case
       fsl_stmt_finalize() will fsl_free() it) or not (in which case
       it does not free() it).
    */
    void const * allocStamp;
  } impl;
};

/**
   Empty-initialized fsl_stmt instance, intended for use as an
   in-struct initializer.
*/
#define fsl_stmt_empty_m {    \
  .db = NULL,                 \
  .stmt = NULL,               \
  .role = 0,                  \
  .sql = fsl_b_empty_m,  \
  .rowCount = 0,              \
  .impl = {                   \
    .flags = 0,               \
    .cachedHits = 0,          \
    .next = NULL,             \
    .allocStamp = NULL        \
  }                           \
}

/**
   Empty-initialized fsl_stmt instance, intended for
   copy-constructing.
*/
FSL_EXPORT const fsl_stmt fsl_stmt_empty;

/**
   Allocates a new, cleanly-initialized fsl_stmt instance using
   fsl_malloc(). The returned pointer must eventually be passed to
   fsl_stmt_finalize() to free it (whether or not it is ever passed
   to fsl_db_prepare()).

   Returns NULL on allocation error.
*/
FSL_EXPORT fsl_stmt * fsl_stmt_malloc(void);


/**
   Behaves like fsl_error_get(), using the db's underlying error
   state. Results are undefined if !db.
*/
FSL_EXPORT int fsl_db_err_get( fsl_db const * db,
                               char const ** msg, fsl_size_t * len );

/**
   Resets any error state in db, but might keep the string
   memory allocated for later use.
*/
FSL_EXPORT void fsl_db_err_reset( fsl_db * db );

/**
   Prepares an SQL statement for execution. On success it returns
   0, populates tgt with the statement's state, and the caller is
   obligated to eventually pass tgt to fsl_stmt_finalize(). tgt
   must have been cleanly initialized, either via allocation via
   fsl_stmt_malloc() or by copy-constructing fsl_stmt_empty
   resp. fsl_stmt_empty_m (depending on the context).

   On error non-0 is returned and tgt is not modified. If
   preparation of the statement fails at the db level then
   FSL_RC_DB is returned f's error state (fsl_cx_err_get())
   "should" contain more details about the problem. Returns
   FSL_RC_MISUSE if !db, !callback, or !sql. Returns
   FSL_RC_NOT_FOUND if db is not opened. Returns FSL_RC_RANGE if
   !*sql.

   The sql string and the following arguments get routed through
   fsl_appendf(), so any formatting options supported by that
   routine may be used here. In particular, the %%q and %%Q
   formatting options are intended for use in escaping SQL for
   routines such as this one.

   Before that, the placeholders {{dbname.repo}} and {{dbname.ckout}}
   in the sql string (not in the values formatted into it) are
   replaced with the names of the repository's and checkout's
   schemas, as in "SELECT uuid FROM {{dbname.repo}}.blob";
   {{temp.NAME}} with the TEMP table NAME of db's context ("temp.NAME"
   for the first context on db's connection, "temp.fslN_NAME" for the
   Nth); and
   {{bare.temp.NAME}} with that table's bare name, without the "temp."
   schema, for where SQLite wants one, as in
   "CREATE INDEX {{temp.x_idx}} ON {{bare.temp.x}}(a)"; and
   {{bare.ckout.NAME}} and {{bare.repo.NAME}} with the checkout resp.
   repository table NAME without its schema, for the same uses, e.g.
   "ON {{bare.ckout.vmerge}}".

   A context's checkout tables may instead be tables of a host's main
   db whose names have a prefix P
   (fsl_repo_open_ckout_opt::hostTablePrefix). Then
   "{{dbname.ckout}}.NAME" as a whole becomes main."PNAME",
   {{bare.ckout.NAME}} becomes "PNAME", and a {{dbname.ckout}} which
   is not followed by ".NAME" (NAME being of [A-Za-z0-9_] characters)
   is an error (FSL_RC_MISUSE), since it cannot name a prefixed
   table. The same goes for the repository's tables, with
   {{dbname.repo}} and {{bare.repo.NAME}}, while they are prefixed
   tables of a host's main db (fsl_repo_open_host()). Without a
   prefix, the expansions are as described above, e.g. "ckout.NAME"
   and "NAME". Other text in double braces is left as is. The same applies to every fsl_db
   function which takes SQL in this form, e.g. fsl_db_prepare_cached(),
   fsl_db_exec() and fsl_db_exec_multi().

   Compatibility note: in sqlite, empty SQL code evaluates
   successfully but with a NULL statement. This API disallows empty
   SQL because it uses NULL as a "no statement" marker and because
   empty SQL is arguably not a query at all.

   Tips:

   - fsl_stmt_col_count() can be used to determine whether a
   statement is a fetching query (fsl_stmt_col_count()>0) or not
   (fsl_stmt_col_count()==0) without having to know the contents
   of the query.

   - fsl_db_prepare_cached() can be used to cache often-used or
   expensive-to-prepare queries within the context of their parent
   db handle.
*/
FSL_EXPORT int fsl_db_prepare( fsl_db * db, fsl_stmt * tgt,
                               char const * sql, ... );

/**
   va_list counterpart of fsl_db_prepare().
*/
FSL_EXPORT int fsl_db_preparev( fsl_db * db, fsl_stmt * tgt,
                                char const * sql, va_list args );

/**
   A special-purpose variant of fsl_db_prepare() which caches
   statements based on their SQL code. This works very much like
   fsl_db_prepare() and friends except that it can return the same
   statement (via *st) multiple times (statements with identical
   SQL are considered equivalent for caching purposes). Clients
   need not explicitly pass the returned statement to
   fsl_stmt_finalize() - the db holds these statements and will
   finalize them when it is closed. It is legal to pass them to
   finalize, in which case they will be cleaned up immediately but
   that also invalidates _all_ pointers to the shared instances.

   If client code does not call fsl_stmt_finalize(), it MUST pass
   the statement pointer to fsl_stmt_cached_yield(st) after is done
   with it. That makes the query available for use again with this
   routine. If a cached query is not yielded via
   fsl_stmt_cached_yield() then this routine will return
   FSL_RC_ACCESS on subsequent requests for that SQL to prevent
   that recursive (mis)use of the statement causes problems.

   This routine is intended to be used in oft-called routines
   where the cost of re-creating statements on each execution could
   be prohibitive (or at least a bummer).

   Returns 0 on success, FSL_RC_MISUSE if any arguments are
   invalid. On error, *st is not written to.  On other errors
   db->error might be updated with more useful information.  See the
   Caveats section below for more details.

   Its intended usage looks like:

   ```
   fsl_stmt * st = NULL;
   int rc = fsl_db_prepare_cached(myDb, &st, "SELECT ...");
   if(rc) { assert(!st); ...error... }
   else {
   ...use it, and _be sure_ to yield it when done:...
   fsl_stmt_cached_yield(st);
   }
   ```

   Though this function allows a formatted SQL string, caching is
   generally only useful with statements which have "static" SQL,
   i.e. no call-dependent values embedded within the SQL. It _can_,
   however, contain bind() placeholders which get reset for each
   use. Note that fsl_stmt_cached_yield() resets the statement, so
   most uses of cached statements do not require that the client
   explicitly reset cached statements (doing so is harmless,
   however).

   Caveats:

   Cached queries must not be used in contexts where recursion might
   cause the same query to be returned from this function while it is
   being processed at another level in the execution stack. Results
   would be undefined. Caching is primarily intended for often-used
   routines which bind and fetch simple values, and not for queries
   which bind large inlined values or might invoke recursion. Because
   of the potential for recursive breakage, this function flags
   queries it doles out and requires that clients call
   fsl_stmt_cached_yield() to un-flag them for re-use. It will return
   FSL_RC_ACCESS if an attempt is made to (re)prepare a statement for
   which a fsl_stmt_cached_yield() is pending, and db->error will be
   populated with a (long) error string describing the problem and
   listing the SQL which caused the collision/misuse. Such SQL can
   often be disambiguated by adding a \%s, wrapped in a C-style
   comment, to the end and passing `__func__` as its value (which is
   also useful for debugging in conjunction with SQL tracing).

   Design note: for the recursion/parallel use case we "could"
   reimplement this to dole out a new statement (e.g. by appending
   " -- a_number" to the SQL to bypass the collision) and free it in
   fsl_stmt_cached_yield(), but that (A) gets uglier than it needs
   to be and (B) is not needed unless/until we really need cached
   queries in spots which would normally break them. The whole
   recursion problem is still theoretical at this point but could
   easily affect small, often-used queries without recursion.

   @see fsl_db_stmt_cache_clear()
   @see fsl_stmt_cached_yield()
*/
FSL_EXPORT int fsl_db_prepare_cached( fsl_db * db, fsl_stmt ** st,
                                      char const * sql, ... );

/**
   The va_list counterpart of fsl_db_prepare_cached().
*/
FSL_EXPORT int fsl_db_preparev_cached( fsl_db * db, fsl_stmt ** st,
                                       char const * sql, va_list args );

/**
   "Yields" a statement which was prepared with
   fsl_db_prepare_cached(), such that that routine can once again
   use/re-issue that statement. Statements prepared this way must be
   yielded in order to prevent that recursion causes
   difficult-to-track errors when a given cached statement is used
   concurrently in different code contexts.

   If st is not NULL then this also calls fsl_stmt_reset() and
   fsl_stmt_clear_bindings() on the statement.

   Returns 0 on success, FSL_RC_MISUSE if !st or if st does not
   appear to have been doled out from fsl_db_prepare_cached().

   @see fsl_db_prepare_cached()
   @see fsl_db_stmt_cache_clear()
*/
FSL_EXPORT int fsl_stmt_cached_yield( fsl_stmt * st );

/**
   If stmt is NULL, returns 0 without side-effects, otherwise this
   frees all memory associated with stmt but does not free stmt unless
   it was allocated by fsl_stmt_malloc() (these objects are normally
   stack-allocated). Returns a FSL_RC_... form of whatever
   sqlite3_finalize() returns.

   If finalization fails (returns non-0) then the error state of
   stmt->db is updated unless it already has error state, in which
   case that is retained. This function's result code is that of the
   finalization, not such a pending/propagating error. That is: it is
   possible for this to succeed but stmt->db to still have pending
   error state.

   It is legal and harmless to pass a given object to this function
   multiple times.

   Prior to 2026-10-28: (A) this function returned FSL_RC_MISUSE if
   stmt==0. (B) it returned 0 regardless of the sqlite3_finalize()
   result due to the programmer's ignorance regarding the subtleties
   of statement finalization result codes.
*/
FSL_EXPORT int fsl_stmt_finalize( fsl_stmt * stmt );

/**
   "Steps" the given SQL cursor one time. The return values
   FSL_RC_STEP_ROW and FSL_RC_STEP_DONE are both success cases, the
   former indicating that one row has been fetched and the latter
   indicating that either no rows are left to fetch or the statement
   is a non-fetching query. On error some other non-zero code will be
   returned.  On a db error this will update the underlying db's error
   state.  This function increments stmt->rowCount by 1 if it returns
   FSL_RC_STEP_ROW.

   Returns FSL_RC_MISUSE if !stmt or stmt has not been prepared.

   It is only legal to call the fsl_stmt_g_xxx() and
   fsl_stmt_get_xxx() functions if this functon returns
   FSL_RC_STEP_ROW. FSL_RC_STEP_DONE is returned upon successfully
   ending iteration or if there is no iteration to perform
   (e.g. typically an UPDATE or INSERT, but see the next paragraph).

   Though the historical definition of non-fetching query was pretty
   clear, the addition of the RETURNING keyword to sqlite3's dialect
   means that even an INSERT or DELETE can return data.

   @see fsl_stmt_reset()
   @see fsl_stmt_reset2()
   @see fsl_stmt_each()
*/
FSL_EXPORT int fsl_stmt_step( fsl_stmt * stmt );

/**
   A callback interface for use with fsl_stmt_each() and
   fsl_db_each(). It will be called one time for each row fetched,
   passed the statement object and the state parameter passed to
   fsl_stmt_each() resp. fsl_db_each().  If it returns non-0 then
   iteration stops and that code is returned UNLESS it returns
   FSL_RC_BREAK, in which case fsl_stmt_each() stops iteration and
   returns 0. i.e. implementations may return FSL_RC_BREAK to
   prematurly end iteration without causing an error.

   This callback is not called for non-fetching queries or queries
   which return no results, though it might (or might not) be
   interesting for it to do so, passing a NULL stmt for that case.

   stmt->rowCount can be used to determine how many times the
   statement has called this function. Its counting starts at 1.

   It is strictly illegal for a callback to pass stmt to
   fsl_stmt_step(), fsl_stmt_reset(), fsl_stmt_finalize(), or any
   similar routine which modifies its state. It must only read the
   current column data (or similar metatdata, e.g. column names)
   from the statement, e.g. using fsl_stmt_g_int32(),
   fsl_stmt_get_text(), or similar.
*/
typedef int (*fsl_stmt_each_f)( fsl_stmt * stmt, void * state );

/**
   Calls the given callback one time for each result row in the
   given statement, iterating over stmt using fsl_stmt_step(). It
   applies no meaning to the callbackState parameter, which gets
   passed as-is to the callback. See fsl_stmt_each_f() for the
   semantics of the callback.

   Returns 0 on success. Returns FSL_RC_MISUSE if !stmt or
   !callback. If the callback returns non-0 (other than
   FSL_RC_BREAK), that code is returned. If stepping the statement
   fails, the code from fsl_stmt_step() is returned and stmt's db
   holds the error details.
*/
FSL_EXPORT int fsl_stmt_each( fsl_stmt * stmt, fsl_stmt_each_f callback,
                              void * callbackState );

/**
   Resets the given statement, analog to sqlite3_reset(). Should be
   called one time between fsl_stmt_step() iterations when running
   multiple INSERTS, UPDATES, etc. via the same statement. If
   resetRowCounter is true then the statement's row counter
   (st->rowCount) is also reset to 0, else it is left
   unmodified. (Most use cases don't use the row counter.)

   Returns 0 on success, FSL_RC_MISUSE if stmt has not been prepared
   or has not been cleanly initialized via copying from fsl_stmt_empty
   or fsl_stmt_empty_m, FSL_RC_DB if the underlying reset fails (in
   which case the error state of the stmt->db handle is updated to
   contain the error information).

   @see fsl_stmt_db()
   @see fsl_stmt_reset()
*/
FSL_EXPORT int fsl_stmt_reset2( fsl_stmt * stmt, bool resetRowCounter );

/**
   Equivalent to fsl_stmt_reset2(stmt, false).
*/
FSL_EXPORT int fsl_stmt_reset( fsl_stmt * stmt );

/**
   Clears memory associtated with any bindings on this statement.
   This is a no-op if stmt is not prepared.
*/
FSL_EXPORT void fsl_stmt_clear_bindings(fsl_stmt * stmt);

/**
   Returns the db handle which prepared the given statement, or
   NULL if stmt has not been prepared.
*/
FSL_EXPORT fsl_db * fsl_stmt_db( fsl_stmt * stmt );

/**
   Returns the SQL string used to prepare the given statement, or NULL
   if stmt has not been prepared. If len is not NULL then *len is set
   to the length of the returned string (which is NUL-terminated). The
   returned bytes are owned by stmt and are invalidated when it is
   finalized.
*/
FSL_EXPORT char const * fsl_stmt_sql( fsl_stmt * stmt,
                                      fsl_size_t * len );

/**
   Returns the name of the given 0-based result column index, or
   NULL if !stmt, stmt is not prepared, or index is out out of
   range. The returned bytes are owned by the statement object and
   may be invalidated shortly after this is called, so the caller
   must copy the returned value if it needs to have any useful
   lifetime guarantees. It's a bit more complicated than this, but
   assume that any API calls involving the statement handle might
   invalidate the column name bytes.

   The API guarantees that the returned value is either NULL or
   NUL-terminated.

   @see fsl_stmt_param_count()
   @see fsl_stmt_col_count()
*/
FSL_EXPORT char const * fsl_stmt_col_name(fsl_stmt * stmt, int index);

/**
   Returns the result column count for the given statement, or -1 if
   !stmt or it has not been prepared. Note that this value is cached
   when the statement is created. Note that non-fetching queries
   (e.g. INSERT and UPDATE) have a column count of 0 unless they have
   a RETURNING clause. Some non-SELECT constructs, e.g. PRAGMA
   table_info(tname) and INSERT/UPDATE/DELETE with a RETURNING clause,
   behave like a SELECT and have a positive column count.

   @see fsl_stmt_param_count()
   @see fsl_stmt_col_name()
*/
FSL_EXPORT int fsl_stmt_col_count( fsl_stmt const * stmt );

/**
   Returns the bound parameter count for the given statement, or -1
   if !stmt or it has not been prepared. Note that this value is
   cached when the statement is created.

   @see fsl_stmt_col_count()
   @see fsl_stmt_col_name()
*/
FSL_EXPORT int fsl_stmt_param_count( fsl_stmt const * stmt );

/**
   Returns the index of the given named parameter for the given
   statement, or -1 if !stmt or stmt is not prepared.
*/
FSL_EXPORT int fsl_stmt_param_index( fsl_stmt * stmt, char const * param);

/**
   Binds NULL to the given 1-based parameter index.  Returns 0 on
   succcess. Sets the DB's error state on error.
*/
FSL_EXPORT int fsl_stmt_bind_null( fsl_stmt * stmt, int index );

/**
   Equivalent to fsl_stmt_bind_null_name() but binds to
   a named parameter.
*/
FSL_EXPORT int fsl_stmt_bind_null_name( fsl_stmt * stmt, char const * param );

/**
   Binds v to the given 1-based parameter index.  Returns 0 on
   succcess. Sets the DB's error state on error.
*/
FSL_EXPORT int fsl_stmt_bind_int32( fsl_stmt * stmt, int index, int32_t v );

/**
   Equivalent to fsl_stmt_bind_int32() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_int32_name( fsl_stmt * stmt, char const * param, int32_t v );

/**
   Binds v to the given 1-based parameter index.  Returns 0 on
   succcess. Sets the DB's error state on error.
*/
FSL_EXPORT int fsl_stmt_bind_int64( fsl_stmt * stmt, int index, int64_t v );

/**
   Equivalent to fsl_stmt_bind_int64() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_int64_name( fsl_stmt * stmt, char const * param, int64_t v );

/**
   Binds v to the given 1-based parameter index.  Returns 0 on
   succcess. Sets the Fossil context's error state on error.
*/
FSL_EXPORT int fsl_stmt_bind_double( fsl_stmt * stmt, int index, double v );

/**
   Equivalent to fsl_stmt_bind_double() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_double_name( fsl_stmt * stmt, char const * param, double v );

/**
   Binds v to the given 1-based parameter index.  Returns 0 on
   succcess. Sets the DB's error state on error.
*/
FSL_EXPORT int fsl_stmt_bind_id( fsl_stmt * stmt, int index, fsl_id_t v );

/**
   Equivalent to fsl_stmt_bind_id() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_id_name( fsl_stmt * stmt, char const * param, fsl_id_t v );

/**
   Binds the first n bytes of v as text to the given 1-based bound
   parameter column in the given statement. If makeCopy is true then
   the binding makes an copy of the data. Set makeCopy to false ONLY
   if you KNOW that the bytes will outlive the binding.

   Returns 0 on success. On error stmt's underlying db's error state
   is updated, hopefully with a useful error message.
*/
FSL_EXPORT int fsl_stmt_bind_text( fsl_stmt * stmt, int index,
                                   char const * v, fsl_int_t n,
                                   bool makeCopy );

/**
   Equivalent to fsl_stmt_bind_text() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_text_name( fsl_stmt * stmt, char const * param,
                                        char const * v, fsl_int_t n,
                                        bool makeCopy );
/**
   Binds the first n bytes of v as a blob to the given 1-based bound
   parameter column in the given statement. See fsl_stmt_bind_text()
   for the semantics of the makeCopy parameter and return value.
*/
FSL_EXPORT int fsl_stmt_bind_blob( fsl_stmt * stmt, int index,
                                   void const * v, fsl_size_t len,
                                   bool makeCopy );

/**
   Equivalent to fsl_stmt_bind_blob() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_blob_name( fsl_stmt * stmt, char const * param,
                                        void const * v, fsl_int_t len,
                                        bool makeCopy );

/**
   Gets an integer value from the given 0-based result set column,
   assigns *v to that value, and returns 0 on success.

   Returns FSL_RC_RANGE if index is out of range for stmt, FSL_RC_MISUSE
   if stmt has no result columns.
*/
FSL_EXPORT int fsl_stmt_get_int32( fsl_stmt * stmt, int index, int32_t * v );

/**
   Gets an integer value from the given 0-based result set column,
   assigns *v to that value, and returns 0 on success.

   Returns FSL_RC_RANGE if index is out of range for stmt, FSL_RC_MISUSE
   if stmt has no result columns.
*/
FSL_EXPORT int fsl_stmt_get_int64( fsl_stmt * stmt, int index, int64_t * v );

/**
   The fsl_id_t counterpart of fsl_stmt_get_int32(). Depending on
   the sizeof(fsl_id_t), it behaves as one of fsl_stmt_get_int32()
   or fsl_stmt_get_int64().
*/
FSL_EXPORT int fsl_stmt_get_id( fsl_stmt * stmt, int index, fsl_id_t * v );

/**
   Convenience form of fsl_stmt_get_id() which returns the value
   directly but cannot report errors. It returns -1 on error, but
   that is not unambiguously an error value.
*/
FSL_EXPORT fsl_id_t fsl_stmt_g_id( fsl_stmt * stmt, int index );

/**
   Convenience form of fsl_stmt_get_int32() which returns the value
   directly but cannot report errors. It returns 0 on error, but
   that is not unambiguously an error.
*/
FSL_EXPORT int32_t fsl_stmt_g_int32( fsl_stmt * stmt, int index );

/**
   Convenience form of fsl_stmt_get_int64() which returns the value
   directly but cannot report errors. It returns 0 on error, but
   that is not unambiguously an error.
*/
FSL_EXPORT int64_t fsl_stmt_g_int64( fsl_stmt * stmt, int index );

/**
   Convenience form of fsl_stmt_get_double() which returns the value
   directly but cannot report errors. It returns 0 on error, but
   that is not unambiguously an error.
*/
FSL_EXPORT double fsl_stmt_g_double( fsl_stmt * stmt, int index );

/**
   Convenience form of fsl_stmt_get_text() which returns the value
   directly but cannot report errors. It returns NULL on error, but
   that is not unambiguously an error because it also returns NULL
   if the column contains an SQL NULL value. If outLen is not NULL
   then it is set to the byte length of the returned string.
*/
FSL_EXPORT char const * fsl_stmt_g_text( fsl_stmt * stmt, int index, fsl_size_t * outLen );

/**
   Gets double value from the given 0-based result set column,
   assigns *v to that value, and returns 0 on success.

   Returns FSL_RC_RANGE if index is out of range for stmt, FSL_RC_MISUSE
   if stmt has no result columns.
*/
FSL_EXPORT int fsl_stmt_get_double( fsl_stmt * stmt, int index, double * v );

/**
   Gets a string value from the given 0-based result set column,
   assigns *out (if out is not NULL) to that value, assigns *outLen
   (if outLen is not NULL) to *out's length in bytes, and returns 0
   on success. Ownership of the string memory is unchanged - it is owned
   by the statement and the caller should immediately copy it if
   it will be needed for much longer.

   Returns FSL_RC_RANGE if index is out of range for stmt,
   FSL_RC_MISUSE if stmt has no result columns. Returns FSL_RC_OOM if
   fetching the text from the underlying statement handle fails due to
   an allocation error.
*/
FSL_EXPORT int fsl_stmt_get_text( fsl_stmt * stmt, int index, char const **out,
                                  fsl_size_t * outLen );

/**
   The Blob counterpart of fsl_stmt_get_text(). Identical to that
   function except that its output result (3rd paramter) type
   differs, and it fetches the data as a raw blob, without any sort
   of string interpretation.

   Returns FSL_RC_RANGE if index is out of range for stmt,
   FSL_RC_MISUSE if stmt has no result columns. Returns FSL_RC_OOM if
   fetching the text from the underlying statement handle fails due to
   an allocation error.
*/
FSL_EXPORT int fsl_stmt_get_blob( fsl_stmt * stmt, int index, void const **out, fsl_size_t * outLen );

/**
   Executes multiple SQL statements, ignoring any results they might
   collect. Returns 0 on success, non-0 on error.  On error
   db->error might be updated to report the problem.
*/
FSL_EXPORT int fsl_db_exec_multi( fsl_db * db, const char * sql, ...);

/**
   va_list counterpart of db_exec_multi().
*/
FSL_EXPORT int fsl_db_exec_multiv( fsl_db * db, const char * sql, va_list args);

/**
   Executes a single SQL statement, skipping over any results it may
   have. Returns 0 on success. On error db's error state may be
   updated. Note that this function translates FSL_RC_STEP_DONE and
   FSL_RC_STEP_ROW to 0. For cases where those particular result codes
   are significant, use fsl_db_prepare() and fsl_stmt_step() (for
   which this function is just a proxy).
*/
FSL_EXPORT int fsl_db_exec( fsl_db * db, char const * sql, ... );

/**
   va_list counterpart of fs_db_exec().
*/
FSL_EXPORT int fsl_db_execv( fsl_db * db, char const * sql, va_list args );

/**
   Begins a transaction on the given db.

   This API historically used pseudo-nested transactions based off of
   BEGIN/COMMIT.  As of 2025-08-09 it uses SAVEPOINTs instead. The
   difference is subtle but was a necessary change for the libfossil
   SCM pieces to be able to behave sensibly in some cases. These docs
   use the term "transaction" to mean "savepoint".

   Returns FSL_RC_MISUSE if !db or the db is not connected, else the
   result of the underlying db call(s).

   Transactions are an easy way to implement "dry-run" mode for
   some types of applications. For example:

   ```
   bool dryRunMode = ...;
   fsl_db_txn_begin(db);
   ...do your stuff...
   fsl_db_txn_end_v2(db, !dryRunMode, false);
   ```

   Here's a tip for propagating error codes when using
   transactions:

   ```
   ...
   if(rc) fsl_db_txn_end_v2(db, false, possiblyTrue);
   else rc = fsl_db_txn_end_v2(db, true, false);
   ```

   That ensures that we propagate rc in the face of a rollback but we
   also capture the rc for a commit (which might yet fail).

   Sidebar: this API, prior to 2025-08, used pseudo-nested
   transactions directly ported from fossil(1) (essentially a
   reference-counted BEGIN/END block, with each level representing one
   reference count point). As of 2025-08 it exclusively uses sqlite3's
   SAVEPOINT[^1] feature, which is essentially nested transactions.
   This change enables better support for dry-run modes and more
   flexible non-fatal-to-the-transaction error handling. e.g. we can
   fail certain opertations, e.g. lookup of a resources, without
   inherently invalidating the whole transaction stack.

   [^1]: https://sqlite.org/lang_savepoint.html
*/
FSL_EXPORT int fsl_db_txn_begin(fsl_db * db);

/**
   Equivalent to fsl_db_txn_end_v2(db, true, false).
*/
FSL_EXPORT int fsl_db_txn_commit(fsl_db * db);

/**
   Equivalent to fsl_db_txn_end_v2(db, false, true), noting that the
   final value of true there is for historical API compatibility and
   will be changed to false if we can get away with it elsewhere.
*/
FSL_EXPORT int fsl_db_txn_rollback(fsl_db * db);

#if 0
/**
   Forces a rollback of any pending transaction in db, regardless of
   the internal transaction begin/end counter. Returns FSL_RC_MISUSE
   if db is not opened, else returns the value of the underlying
   ROLLBACK call. This also re-sets/frees any transaction-related
   state held by db (e.g. db->beforeCommit).  Use with care, as this
   mucks about with db state in a way which is not all that pretty and
   it may confuse downstream code.

   Returns 0 on success.

   Never, ever use this. In 12+ years it has never proven necessary to
   use this function, and doing so can easily lead to a mismatch in
   transaction-using code and the transaction stack level.
*/
FSL_EXPORT int fsl_db_rollback_force(fsl_db * db);
#endif

/**
   Decrements the transaction counter incremented by
   fsl_db_txn_begin() and commits or rolls back the
   savepoint if the counter goes to 0.

   The behavior of keepSavepoint depends on the transaction depth:

   - If this is not the top-most savepoint, it is "released" (applied)
     if keepSavepoint is true or rolled back if keepSavepoint false,
     and that resulting db result code is returned. A value of true
     releases this savepoint regardless of the bubbleRollback flag
     (see below).

   - If this is the top-most savepoint then keepSavepoint will be
     considered to be false if bubbleRollback is true or if any call
     to this function in the same top-level transaction stack flag has
     passed true for that argument.

   If bubbleRollback is true, or any call to this function within the
   same top-level savepoint passed true as the bubbleRollback
   argument, the transaction is put into a persistent will-rollback
   mode.  In this mode, individual savepoints can still be applied by
   passing true as the second argument, but when the final one is
   popped, the whole thing will be rolled back instead of applied.

   To reiterate: if db fsl_db_txn_begin() is used in a nested manner
   and bubbleRollback is true for any one of the nested calls, then
   that value will be remembered, such that the downstream calls to
   this function within the same transaction will behave as if
   bubbleRollback were true even if they pass false for the third
   argument.

   Achtung: the bubbleRollback==true behavior is, as of 2025-08,
   considered "legacy" and should no longer be used, but much code
   still currently expects that behavior.

   The distinction been whether retaining a savepoint should put the
   transaction into a persistent rollback state is primarily of
   interest to operations which implement "dry-run" mode.  For
   dry-run, keepSavepoint should always ben false, while
   bubbleRollback should be true if the operation failed in a way
   which could impact further operations in the same transaction.

   Returns FSL_RC_MISUSE if db is not opened, 0 if the transaction
   counter is above 0, else the result of the (potentially many)
   underlying database operations.
*/
FSL_EXPORT int fsl_db_txn_end_v2(fsl_db * db, bool keepSavepoint,
                                 bool bubbleRollback);

/**
   Equivalent to fsl_db_txn_end_v2(DB, !DOROLLBACK, !!DOROLLBACK),
   which mimics the historical behavior of this API.
*/
#define fsl_db_txn_end(DB,DOROLLBACK) \
  fsl_db_txn_end_v2((DB), !(DOROLLBACK), !!(DOROLLBACK))

/**
   Returns the given db's current transaction depth. If the value is
   negative, its absolute value represents the depth but indicates
   that a rollback is pending. If it is positive, the transaction is
   still in a "good" state. If it is 0, no transaction is active.
*/
FSL_EXPORT int fsl_db_txn_level(fsl_db * db);

/**
   Runs the given SQL query on the given db and returns true if the
   query returns any rows, else false. Returns 0 for any error as
   well.
*/
FSL_EXPORT bool fsl_db_exists(fsl_db * db, char const * sql, ... );

/**
   va_list counterpart of fsl_db_exists().
*/
FSL_EXPORT bool fsl_db_existsv(fsl_db * db, char const * sql, va_list args );

/**
   Runs the given SQL query on the given db and sets *rv to true if
   the query returns any rows, else false.

   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_exists2(fsl_db * db, bool * rv,
                              char const * sql, ... );

/**
   va_list counterpart of fsl_db_exists2().
*/
FSL_EXPORT int fsl_db_exists2v(fsl_db * db, bool * rv,
                               char const * sql, va_list args );

/**
   Runs a fetch-style SQL query against DB and returns the first
   column of the first result row via *rv. If the query returns no
   rows, *rv is not modified. The intention is that the caller sets
   *rv to his preferred default (or sentinel) value before calling
   this.

   The format string (the sql parameter) accepts all formatting
   options supported by fsl_appendf().

   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, ... );

/**
   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);

/**
   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, ... );

/**
   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, ... );

/**
   va_list counterpart of fsl_db_get_int64().
*/
FSL_EXPORT int fsl_db_get_int64v( fsl_db * db, int64_t * rv,
                       char const * sql, va_list args);

/**
   Convenience form of fsl_db_get_int64() 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 int64_t fsl_db_g_int64( fsl_db * db, int64_t defaultValue,
                            char const * sql, ... );


/**
   The fsl_id_t counterpart of fsl_db_get_int32(). See that function
   for the semantics.
*/
FSL_EXPORT int fsl_db_get_id( fsl_db * db, fsl_id_t * rv,
                   char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_id().
*/
FSL_EXPORT int fsl_db_get_idv( fsl_db * db, fsl_id_t * rv,
                    char const * sql, va_list args);

/**
   Convenience form of fsl_db_get_id() 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 fsl_id_t fsl_db_g_id( fsl_db * db, fsl_id_t defaultValue,
                      char const * sql, ... );


/**
   The fsl_size_t counterpart of fsl_db_get_int32(). See that
   function for the semantics. If this function would fetch a
   negative value, it returns FSL_RC_RANGE and *rv is not modified.
*/
FSL_EXPORT int fsl_db_get_size( fsl_db * db, fsl_size_t * rv,
                     char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_size().
*/
FSL_EXPORT int fsl_db_get_sizev( fsl_db * db, fsl_size_t * rv,
                      char const * sql, va_list args);

/**
   Convenience form of fsl_db_get_size() 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 fsl_size_t fsl_db_g_size( fsl_db * db,
                                     fsl_size_t defaultValue,
                                     char const * sql, ... );


/**
   The double counterpart of fsl_db_get_int32(). See that function
   for the semantics.
*/
FSL_EXPORT int fsl_db_get_double( fsl_db * db, double * rv,
                                  char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_double().
*/
FSL_EXPORT int fsl_db_get_doublev( fsl_db * db, double * rv,
                                   char const * sql, va_list args);

/**
   Convenience form of fsl_db_get_double() 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 double fsl_db_g_double( fsl_db * db, double defaultValue,
                                   char const * sql, ... );

/**
   The C-string counterpart of fsl_db_get_int32(). On success *rv
   will be set to a dynamically allocated string copied from the
   first column of the first result row. If rvLen is not NULL then
   *rvLen will be assigned the byte-length of that string. If no
   row is found, *rv is set to NULL and *rvLen (if not NULL) is set
   to 0, and 0 is returned. Note that NULL is also a legal result
   (an SQL NULL translates as a NULL string), The caller must
   eventually free the returned string value using fsl_free().
*/
FSL_EXPORT int fsl_db_get_text( fsl_db * db, char ** rv, fsl_size_t * rvLen,
                                char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_text().
*/
FSL_EXPORT int fsl_db_get_textv( fsl_db * db, char ** rv, fsl_size_t * rvLen,
                      char const * sql, va_list args );

/**
   Convenience form of fsl_db_get_text() which returns the value
   directly but provides no way of checking for errors. On error,
   or if no result is found, NULL is returned. The returned string
   must eventually be passed to fsl_free() to free it.  If len is
   not NULL then if non-NULL is returned, *len will be assigned the
   byte-length of the returned string.
*/
FSL_EXPORT char * fsl_db_g_text( fsl_db * db, fsl_size_t * len,
                      char const * sql,
                      ... );

/**
   The Blob counterpart of fsl_db_get_text(). Identical to that
   function except that its output result (2nd paramter) type
   differs, and it fetches the data as a raw blob, without any sort
   of string interpretation. The returned *rv memory must
   eventually be passed to fsl_free() to free it. If len is not
   NULL then on success *len will be set to the byte length of the
   returned blob. If no row is found, *rv is set to NULL and *rvLen
   (if not NULL) is set to 0, and 0 is returned. Note that NULL is
   also a legal result (an SQL NULL translates as a NULL string),
*/
FSL_EXPORT int fsl_db_get_blob( fsl_db * db, void ** rv, fsl_size_t * len,
                     char const * sql, ... );


/**
   va_list counterpart of fsl_db_get_blob().
*/
FSL_EXPORT int fsl_db_get_blobv( fsl_db * db, void ** rv, fsl_size_t * stmtLen,
                      char const * sql, va_list args );

/**
   Convenience form of fsl_db_get_blob() which returns the value
   directly but provides no way of checking for errors. On error,
   or if no result is found, NULL is returned.
*/
FSL_EXPORT void * fsl_db_g_blob( fsl_db * db, fsl_size_t * len,
                      char const * sql,
                      ... );
/**
   Similar to fsl_db_get_text() and fsl_db_get_blob(), but writes
   its result to tgt, appending its results to the given buffer.

   If asBlob is true then the underlying BLOB API is used to
   populate the buffer, else the underlying STRING/TEXT API is
   used.  For many purposes there will be no difference, but if you
   know you might have binary data, be sure to pass a true value
   for asBlob to avoid any potential encoding-related problems.

   Results are undefined if any pointer argument is NULL. Returns
   FSL_RC_MISUSE if the SQL is an empty string.
*/
FSL_EXPORT int fsl_db_get_buffer( fsl_db * db, fsl_b * tgt,
                                  bool asBlob, char const * sql,
                                  ... );

/**
   va_list counterpart of fsl_db_get_buffer().
*/
FSL_EXPORT int fsl_db_get_bufferv( fsl_db * db, fsl_b * tgt,
                                   bool asBlob, char const * sql,
                                   va_list args );


/**
   Expects sql to be a SELECT-style query which (potentially)
   returns a result set. For each row in the set callback() is
   called, as described for fsl_stmt_each(). Returns 0 on success.
   The callback is _not_ called for queries which return no
   rows. If clients need to know if rows were returned, they can
   add a counter to their callbackState and increment it from the
   callback.

   Returns FSL_RC_MISUSE if db is not opened, !callback,
   !sql. Returns FSL_RC_RANGE if !*sql.
*/
FSL_EXPORT int fsl_db_each( fsl_db * db, fsl_stmt_each_f callback,
                            void * callbackState, char const * sql, ... );

/**
   va_list counterpart to fsl_db_each().
*/
FSL_EXPORT int fsl_db_eachv( fsl_db * db, fsl_stmt_each_f callback,
                             void * callbackState, char const * sql, va_list args );


/**
   Returns the given Julian date value formatted as an ISO8601
   string (with a fractional seconds part if msPrecision is true,
   else without it).  Returns NULL if !db, db is not connected, j
   is less than 0, or on allocation error. The returned memory must
   eventually be freed using fsl_free().

   If localTime is true then the value is converted to the local time,
   otherwise it is not.

   @see fsl_db_unix_to_iso8601()
   @see fsl_julian_to_iso8601()
   @see fsl_iso8601_to_julian()
*/
FSL_EXPORT char * fsl_db_julian_to_iso8601( fsl_db * db, double j,
                                            bool msPrecision, bool localTime );

/**
   Returns the given Julian date value formatted as an ISO8601
   string (with a fractional seconds part if msPrecision is true,
   else without it).  Returns NULL if !db, db is not connected, j
   is less than 0, or on allocation error. The returned memory must
   eventually be freed using fsl_free().

   If localTime is true then the value is converted to the local time,
   otherwise it is not.

   @see fsl_db_julian_to_iso8601()
   @see fsl_julian_to_iso8601()
   @see fsl_iso8601_to_julian()
*/
FSL_EXPORT char * fsl_db_unix_to_iso8601( fsl_db * db, fsl_time_t j,
                                          bool localTime );


/**
   Returns the current time in Julian Date format. Returns a negative
   value if !db or db is not opened.
*/
FSL_EXPORT double fsl_db_julian_now(fsl_db * db);

/**
   Uses the given db to convert the given time string to Julian Day
   format. If it cannot be converted, a negative value is returned.
   The str parameter can be anything suitable for passing to sqlite's:

   SELECT julianday(str)

   Note that this routine will escape str for use with SQL - the
   caller must not do so.

   @see fsl_julian_to_iso8601()
   @see fsl_iso8601_to_julian()
*/
FSL_EXPORT double fsl_db_string_to_julian(fsl_db * db, char const * str);

/**
   Opens the given db file and populates db with its handle.  db
   must have been cleanly initialized by copy-initializing it from
   fsl_db_empty (or fsl_db_empty_m) or by allocating it using
   fsl_db_malloc(). Failure to do so will lead to undefined
   behaviour.

   openFlags may be a mask of FSL_DB_OPEN_xxx values, but not all are
   used/supported here. If FSL_DB_OPEN_CREATE is _not_ set in
   openFlags and dbFile does not exist, it will return
   FSL_RC_NOT_FOUND. The existence of FSL_DB_OPEN_CREATE in the flags
   will cause this routine to try to create the file if needed. If
   conflicting flags are specified (e.g. FSL_DB_OPEN_RO and
   FSL_DB_OPEN_RWC) then which one takes precedence is unspecified and
   possibly unpredictable. If openFlags is 0 then FSL_DB_OPEN_RO is
   assumed.

   This routine normally looks for the given file before attempting to
   open it and will update db's error state if the file cannot be
   found. Those checks are skipped if (1) openFlags has the
   FSL_DB_OPEN_CREATE bit set, (2) dbName is empty (indicating a
   nameless temporary database), (3) the string contains a ":" in any
   byte position, in which case it is assumed to be a URL-style name
   or ":memory:". The exception to (3) is on Windows platforms, where
   it recognize drive letter prefixes in the form "X:".

   See this page for the differences between ":memory:" and "":

   https://www.sqlite.org/inmemorydb.html

   This routine does not handle URL-style file names.

   Returns FSL_RC_MISUSE if !db, !dbFile, or if db->dbh is not NULL
   (i.e. if it is already opened or its memory was default-initialized
   (use fsl_db_empty to cleanly copy-initialize new stack-allocated
   instances).

   On error db->dbh will be NULL, but db->error might contain error
   details.

   Regardless of success or failure, db should be passed to
   fsl_db_close() to free up all memory associated with it. It is
   not closed automatically by this function because doing so cleans
   up the error state, which the caller will presumably want to
   have.

   @see fsl_db_close()
   @see fsl_db_prepare()
   @see fsl_db_malloc()
*/
FSL_EXPORT int fsl_db_open( fsl_db * db, char const * dbFile,
                            fsl_flag32_t openFlags );

/**
   Closes the given db handle and frees any resources owned by
   db. This function is a no-op if db is NULL.

   If db was allocated using fsl_db_malloc() (as determined by
   examining db->allocStamp) then this routine also fsl_free()s it,
   otherwise it is assumed to either be on the stack or part of a
   larger struct and is not freed, but any resources it allocated are
   freed.

   If db has any pending transactions, they are rolled back by this
   function before a FSL_DB_EVENT_CLOSING event is fired.
*/
FSL_EXPORT void fsl_db_close( fsl_db * db );

/**
   If db is an opened db handle, this registers a debugging
   function with the db which traces all SQL to the given FILE
   handle. If outStream is NULL then tracing events will be
   emitted via FSL_DB_EVENT_TRACE_SQLX instead.

   If expandedSql is true then it uses sqlite3_expanded_sql() to
   expand each traced statement, else it uses unexpanded SQL (which is
   much faster).

   If outStream is not NULL then tracing will go there, otherwise it
   will go out via a FSL_DB_EVENT_TRACE_SQL or FSL_DB_EVENT_TRACE_SQLX
   event (depending on the value of expandedSql). Ownership of
   outStream is not modified by this call and outStream must outlive
   its association with db.

   This is a no-op if db is closed.

   This mechanism is only intended for debugging and exploration of
   how Fossil works. Tracing is often as easy way to ensure that a
   given code block is getting run.

   TODOs:

   - Expand this API to take a client-side callback and state
   object, rather than a FILE pointer.

   - Provide a toggle for the tracing level: with and without
   "expanded" SQL. Expanding the SQL to include its bound values is
   far more expensive (but also far more informative).
*/
FSL_EXPORT void fsl_db_sqltrace_enable( fsl_db * db, FILE * outStream,
                                        bool expandSql);

/**
   Returns the row ID of the most recent insertion,
   or -1 if !db, db is not connected, or 0 if no inserts
   have been performed.
*/
FSL_EXPORT fsl_id_t fsl_db_last_insert_id(fsl_db * db);

/**
   Returns non-0 (true) if the database (which must be open) table
   identified by zTableName has a column named zColName
   (case-sensitive), else returns 0.
*/
FSL_EXPORT bool fsl_db_table_has_column( fsl_db * db,
                                         char const *zTableName,
                                         char const *zColName );

/**
   If a db name has been associated with db then it is returned,
   otherwise NULL is returned. A db has no name by default, but
   fsl_cx-used ones get their database name assigned to them
   (e.g. "main" for the main db).
*/
FSL_EXPORT char const * fsl_db_name(fsl_db const * db);

/**
   Returns a db name string for the given fsl_db_role value. The
   string is static, guaranteed to live as long as the app.  It
   returns NULL if passed FSL_DBROLE_NONE or some value out of range
   for the enum.
*/
FSL_EXPORT const char * fsl_db_role_name(enum fsl_dbrole_e r);

/**
   Allocates a new fsl_db instance(). Returns NULL on allocation
   error. Note that fsl_db instances can often be used from the
   stack - allocating them dynamically is an uncommon case necessary
   for script bindings.

   Achtung: the returned value's allocStamp member is used for
   determining if fsl_db_close() should free the value or not.  Thus
   if clients copy over this value without adjusting allocStamp back
   to its original value, the library will likely leak the instance.
   Been there, done that.
*/
FSL_EXPORT fsl_db * fsl_db_malloc(void);

/**
   The fsl_stmt counterpart of fsl_db_malloc(). See that function
   for when you might want to use this and a caveat involving the
   allocStamp member of the returned value. fsl_stmt_finalize() will
   free statements created with this function.
*/
FSL_EXPORT fsl_stmt * fsl_stmt_malloc(void);

/**
   ATTACHes the file zDbName to db using the database name zLabel
   (which gets quoted as an SQL identifier). Returns 0 on
   success. Returns FSL_RC_MISUSE if any argument is NULL or any
   string argument starts with a NUL byte, else it returns the result
   of fsl_db_exec() which attaches the db. On db-level errors db's
   error state will be updated.
*/
FSL_EXPORT int fsl_db_attach(fsl_db * db, const char *zDbName,
                             const char *zLabel);

/**
   The converse of fsl_db_detach(). Must be passed the same arguments
   which were passed as the 1st and 3rd arguments to fsl_db_attach().
   Returns 0 on success, FSL_RC_MISUSE if !db, !zLabel, or !*zLabel,
   else it returns the result of the underlying fsl_db_exec()
   call.
*/
FSL_EXPORT int fsl_db_detach(fsl_db * db, const char *zLabel);

/**
   Binds f to a db handle owned by a host application, such as a
   program which loads libfossil as a SQLite extension. It must be
   called before a repository or checkout is opened, and returns
   FSL_RC_MISUSE otherwise.

   While bound, opening a repository or checkout ATTACHes it to dbh
   under the usual schema names ("repo" and "ckout") instead of
   opening a connection of its own. All of libfossil's work then runs
   in dbh's transaction, as SAVEPOINTs nested in any transaction the
   host has open. Closing it DETACHes it, and never closes dbh. The
   host must keep dbh open until then.

   Several contexts may be bound to one dbh. A context gets the usual
   schema names unless dbh already has schemas of those names (e.g.
   another context's), in which case it gets "repo_2", "ckout_2", and
   so on. Each context after the first
   to join the connection also gets TEMP table and savepoint names of
   its own, which carry its place in that order. Their transactions
   nest in dbh's: a context must end each of its transaction levels
   before any other context's which began outside it, and is refused
   (FSL_RC_MISUSE) otherwise. A context closed while another's
   transaction is inside its own (closing belongs outside of any
   transaction) leaves its savepoints open in dbh's transaction, and,
   as SQLite cannot DETACH there, its schemas attached, for the host
   to end and DETACH. The SQL functions libfossil adds act for
   the context whose statement calls them, and for the host's own SQL,
   for the first of the contexts still bound; closing the last one
   removes them. The host's SQL which names no schema reaches the
   repository attached first.

   Opening fails if:

   - dbh is a connection libfossil opened for a context of its own,
   - dbh has PRAGMA foreign_keys=ON,
   - a table in a schema SQLite searches first (temp, main, or one
     attached earlier, other than another context's) has the name of
     one of the opened db's tables, so that the host's SQL which names
     no schema would use that table in place of fossil's, or
   - a repository and a checkout would both be opened and dbh's main
     db is not a file, e.g. ":memory:". A check-in writes both in one
     transaction, which SQLite can only commit atomically if it is in a
     super-journal. Super-journals can only contain DELETE mode dbs.

   Unlike on a connection libfossil opens itself, libfossil does not
   change dbh's busy timeout, WAL checkpoint, or foreign_keys settings,
   install a commit hook, or define now() or regexp() on it.

   Opening and closing must happen outside of any transaction, as
   SQLite requires for ATTACH and DETACH.

   Pass NULL to unbind (only while nothing is opened).

   @see fsl_cx_host_db_closing()
*/
FSL_EXPORT int fsl_cx_host_db( fsl_cx * f, fsl_db_t * dbh );

/**
   Tells f that its host db handle is being closed and can no longer
   run SQL, e.g. from a virtual table's xDisconnect method during
   sqlite3_close(). A following fsl_cx_finalize() or fsl_close_dbs()
   then finalizes libfossil's statements without running DETACH, which
   lets the host's close succeed.
*/
FSL_EXPORT void fsl_cx_host_db_closing( fsl_cx * f );

/**
   Registers libfossil's SQLite extension on db: the SQL functions
   fsl_open(), fsl_close(), fsl_commit(), fsl_tag(), fsl_sync(),
   fsl_clone(), fsl_checkout(), fsl_update(), fsl_merge(),
   fsl_status(), fsl_add(), fsl_rm(), fsl_mv() and fsl_revert(), which
   run libfossil on db itself through fsl_cx_host_db(). Its signature
   matches what sqlite3_auto_extension() expects, so a program which
   links libfossil can register it for every new connection with:

   ```
   sqlite3_auto_extension((void(*)(void))fsl_sqlext_init);
   ```

   pApi is unused. It returns a SQLite result code. On error, if
   pzErrMsg is not NULL, *pzErrMsg is set to a message which the
   caller must free with sqlite3_free(). src/sqlext.c documents the SQL
   functions.
*/
FSL_EXPORT int fsl_sqlext_init(fsl_db_t * db, char ** pzErrMsg,
                               sqlite3_api_routines const * pApi);

/**
   Expects fmt to be a SELECT-style query. For each row in the
   query, the first column is fetched as a string and appended to
   the tgt list.

   Returns 0 on success, FSL_RC_MISUSE if !fmt or fmt is empty, or any
   number of potential FSL_RC_OOM or db-related errors.

   Results rows with a NULL value (resulting from an SQL NULL) are
   added to the list as NULL entries.

   Each entry appended to the list is a (char *) which must
   be freed using fsl_free(). To easiest way to clean up
   the list and its contents is:

   ```
   fsl_list_visit_free(tgt,...);
   ```

   On error the list may be partially populated.

   Complete example:

   ```
   fsl_list li = fsl_list_empty;
   int rc = fsl_db_select_slist(db, &li,
            "SELECT uuid FROM blob WHERE rid<20");
   if(!rc){
     fsl_size_t i;
     for(i = 0;i < li.used; ++i){
       char const * uuid = (char const *)li.list[i];
       fsl_fprintf(stdout, "UUID: %s\n", uuid);
     }
   }
   fsl_list_visit_free(&li, 1);
   ```

   Of course fsl_list_visit() may be used to traverse the list as
   well, as long as the visitor expects (char [const]*) list
   elements.
*/
FSL_EXPORT int fsl_db_select_slist( fsl_db * db, fsl_list * tgt,
                                    char const * fmt, ... );

/**
   The va_list counterpart of fsl_db_select_slist().
*/
FSL_EXPORT int fsl_db_select_slistv( fsl_db * db, fsl_list * tgt,
                                     char const * fmt, va_list args );

/**
   Returns n bytes of random lower-case hexidecimal characters
   using the given db as its data source, plus a terminating NUL
   byte. The returned memory must eventually be freed using
   fsl_free(). Returns NULL if !n, db is not opened, or on a db-level error.
*/
FSL_EXPORT char * fsl_db_random_hex(fsl_db * db, fsl_size_t n);

/**
   Returns the "number of database rows that were changed or inserted
   or deleted by the most recently completed SQL statement" (to quote
   the underlying APIs). Returns 0 if db is not opened.

   See: https://sqlite.org/c3ref/changes.html
*/
FSL_EXPORT int fsl_db_changes_recent(fsl_db * db);

/**
   Returns "the number of row changes caused by INSERT, UPDATE or
   DELETE statements since the database connection was opened" (to
   quote the underlying APIs). Returns 0 if db is not opened.

   See; https://sqlite.org/c3ref/total_changes.html
*/
FSL_EXPORT int fsl_db_changes_total(fsl_db * db);

/**
   Initializes the given database file. zFilename is the name of
   the db file. It is created if needed, but any directory
   components are not created. zSchema is the base schema to
   install.  The following arguments may be (char const *) SQL
   code, each of which gets run against the db after the main
   schema is called.  The variadic argument list MUST end with NULL
   (0), even if there are no non-NULL entries.

   Returns 0 on success.

   On error, if err is not NULL then it is populated with any error
   state from the underlying (temporary) db handle.
*/
FSL_EXPORT int fsl_db_init( fsl_error * err, char const * zFilename,
                 char const * zSchema, ... );

/**
   A fsl_stmt_each_f() impl, intended primarily for debugging, which
   simply outputs row data in tabular form via fsl_output(). The
   state argument must be a valid fsl_cx pointer. On
   the first row, the column names are output.

   Achtung: this function's expectations were changed on 2024-09-16:
   prior to this, stmt's db handle had access to a fsl_cx instance,
   but that was factored out. It now requires the state argument to be
   a fsl_cx.
*/
FSL_EXPORT int fsl_stmt_each_f_dump( fsl_stmt * 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.
   For FSL_DBROLE_CKOUT and FSL_DBROLE_REPO, zTable is the name of a
   checkout resp. repository table, which is looked up with its prefix
   if those tables are prefixed tables of a host's main db
   (fsl_repo_open_ckout_opt::hostTablePrefix, fsl_repo_open_host()).

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

/**
   The elipsis counterpart of fsl_stmt_bind_fmtv().
*/
FSL_EXPORT int fsl_stmt_bind_fmt( fsl_stmt * st, char const * fmt, ... );

/**
    Binds a series of values using a formatting string.

    The string may contain the following characters, each of which
    refers to the next argument in the args list:

    '-': binds a NULL and expects a NULL placeholder
         in the argument list (for consistency's sake).

    'i': binds an int32

    'I': binds an int64

    'R': binds a fsl_id_t ('R' as in 'RID' or 'ROWID')

    'f': binds a double

    's': binds a (char const *) as text or NULL. See below.

    'S': binds a (char const *) as a blob or NULL. See below.

    'b': binds a (fsl_b const *) as text or NULL. See below.

    'B': binds a (fsl_b const *) as a blob or NULL. See below.

    ' ': spaces are allowed for readability and are ignored.

    '^': An optional modifier for "sSbB". See below.

    Returns 0 on success, any number of other FSL_RC_xxx codes on
    error.

    About the sSbB bindings:

    - If their argument is NULL they bind as SQL NULL.

    - 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 this call. Thus results are undefined if
      such an argument's memory is invalidated before the statement is
      done with it. The default behavior can be overridden by adding
      the character '^' immediately after the "sSbB" entry (with no
      intervening spaces), which will tell it to make a copy of the
      content. e.g. "ss^i" would bind one string without making a
      copy, then one string with a copy, then an int32.

    Example:

    ```
    int rc = fsl_stmt_bind_fmt(&stmt, "ss^i", "hello", "world", (int32_t)12);
    ```

    Note the cast on the final argument to ensure that it's of the
    proper size for the 'i' type.
*/
FSL_EXPORT int fsl_stmt_bind_fmtv( fsl_stmt * st, char const * fmt,
                                   va_list args );

/**
   Works like fsl_stmt_bind_fmt() but:

   1) It calls fsl_stmt_reset() before binding the arguments.

   2) If binding succeeds then it steps the given statement a single
      time.

   3) If the result is _NOT_ FSL_RC_STEP_ROW then it also resets the
      statement before returning. It does not do so for
      FSL_RC_STEP_ROW because doing so would make it impossible to
      fetch the current row's data.

   Returns the result of the underlying step() call. It never returns
   0.

   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 only legal if FSL_RC_STEP_ROW was the result). This is also why
   it cannot reset the statement if that result is returned.
*/
FSL_EXPORT int fsl_stmt_bind_stepv_v2( fsl_stmt * st, char const * fmt,
                                       va_list args );

/**
   The elipsis counterpart of fsl_stmt_bind_step_v2().
*/
FSL_EXPORT int fsl_stmt_bind_step_v2( fsl_stmt * st, char const * fmt, ... );

/**
   Works exactly like fsl_stmt_bind_stepv_v2() except that it returns
   0 if stepping results in FSL_RC_STEP_DONE. That behavior is legacy
   and now consider to have been a poor design decision, but those
   semantics are currently heavily relied on throughout the library.

   To re-iterate: this routine NEVER returns FSL_RC_STEP_DONE. We say
   that because some folks (🙋‍♂️) keep breaking things by checking for
   that code instead of 0. That's why fsl_stmt_bind_step_v2() was
   introduced.
*/
FSL_EXPORT int fsl_stmt_bind_stepv( fsl_stmt * st, char const * fmt,
                                      va_list args );

/**
   The elipsis counterpart of fsl_stmt_bind_step().
*/
FSL_EXPORT int fsl_stmt_bind_step( fsl_stmt * st, char const * fmt, ... );

/**
   Sets the on-transaction hook for the given db, overwriting any
   prior one.  To clear the hook, pass NULL for the 2nd and 3rd
   arguments.

   The final argument specifies what events type to look for.  It may
   be an OR of any FSL_DB_EVENT_... events. Use
   FSL_DB_EVENT_listen_all to listen to all events. The stored mask is
   bitwise ANDed against FSL_DB_EVENT_mask_id, so only the concrete
   message IDs are recorded here.

   Achtung: fsl_cx instances install this hook on database handles
   they manage, so never call this on such a handle.
*/
FSL_EXPORT void fsl_db_event_listener( fsl_db * db, fsl_db_event_f f,
                                       void * pState, fsl_flag32_t mask);

/**
   Returns true if db is opened and sqlite3_db_readonly() returns 0
   for it, else returns false. If zSchema is NULL then "main" is
   assumed.
*/
FSL_EXPORT bool fsl_db_is_writeable( fsl_db * db, char const *zSchema );

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif /* ORG_FOSSIL_SCM_FSL_DB_H_INCLUDED */
/* end of file include/fossil-scm/db.h */
/* start of file include/fossil-scm/hash.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_HASH_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_HASH_H_INCLUDED
/*
  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-FileType: Code

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

  *****************************************************************************
  This file declares public APIs relating to hashing.
*/

#if defined(__cplusplus)
extern "C" {
#endif

/**
   Various set-in-stone constants used by the API.
*/
enum fsl_hash_constants {
/**
   The length, in bytes, of a hex-format SHA1 hash string.
*/
FSL_STRLEN_SHA1 = 40,
/**
   The length, in bytes, of a hex-format SHA3-256 hash string.
*/
FSL_STRLEN_K256 = 64,
/**
   The length, in bytes, of a hex-format MD5 hash string.
*/
FSL_STRLEN_MD5 = 32,

/** Minimum length of a full fossil UUID. */
FSL_UUID_STRLEN_MIN = FSL_STRLEN_SHA1,
/** Maximum length of a full fossil UUID. */
FSL_UUID_STRLEN_MAX = FSL_STRLEN_K256
};

/**
   Unique IDs for hash types supported by fossil.
*/
enum fsl_hash_types_e {
/** Invalid hash type. */
FSL_HTYPE_ERROR = 0,
/** SHA1. */
FSL_HTYPE_SHA1 = 1,
/** SHA3-256. */
FSL_HTYPE_K256 = 2
};
typedef enum fsl_hash_types_e fsl_hash_types_e;

typedef struct fsl_md5_cx fsl_md5_cx;
typedef struct fsl_sha1_cx fsl_sha1_cx;
typedef struct fsl_sha3_cx fsl_sha3_cx;

/**
   The hash string of the initial MD5 state. Used as an
   optimization for some places where we need an MD5 but know it
   will not hash any data.

   Equivalent to what the md5sum command outputs for empty input:

   ```
   # md5sum < /dev/null
   d41d8cd98f00b204e9800998ecf8427e  -
   ```
*/
#define FSL_MD5_INITIAL_HASH "d41d8cd98f00b204e9800998ecf8427e"

/**
   Holds state for MD5 calculations. It is intended to be used like
   this:

   ```
   unsigned char digest[FSL_STRLEN_MD5/2];
   char hex[FSL_STRLEN_MD5+1];
   fsl_md5_cx cx = fsl_md5_cx_empty;
   // alternately: fsl_md5_init(&cx);
   ...call fsl_md5_update(&cx,...) any number of times to
   ...incrementally calculate the hash.
   fsl_md5_final(&cx, digest); // ends the calculation
   fsl_md5_digest_to_base16(digest, hex);
   // digest now contains the raw 16-byte MD5 digest.
   // hex now contains the 32-byte MD5 + a trailing NUL
   ```
*/
struct fsl_md5_cx {
  int isInit;
  uint32_t buf[4];
  uint32_t bits[2];
  unsigned char in[64];
};

/**
   A filled-with-defaults fsl_md5_cx instance appropriate for
   const-copy initialization. Instances must either be
   copy-initialized from this instance or they must be
   passed to fsl_md5_init() before they are used.
*/
#define fsl_md5_cx_empty_m {                                  \
    1/*isInit*/,                                              \
    {/*buf*/0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 }, \
    {/*bits*/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,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}}

/**
   Equivalent to fsl_md5_cx_empty_m but suitable for non-const
   copy initialization.
*/
FSL_EXPORT const fsl_md5_cx fsl_md5_cx_empty;

/**
   Initializes the given context pointer. It must not be NULL.  This
   must be the first routine called on any fsl_md5_cx instances.
   Alternately, copy-constructing from fsl_md5_cx_empty has the same
   effect.

   @see fsl_md5_update()
   @see fsl_md5_final()
*/
FSL_EXPORT void fsl_md5_init(fsl_md5_cx *cx);

/**
   Updates cx's state to reflect the addition of the data specified by
   the range (buf, buf+len]. Neither cx nor buf may be NULL. This may
   be called an arbitrary number of times between fsl_md5_init() and
   fsl_md5_final().

   @see fsl_md5_init()
   @see fsl_md5_final()
*/
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
   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);

/**
   Converts an md5 digest value (from fsl_md5_final()'s 2nd
   parameter) to a 32-byte (FSL_STRLEN_MD5) CRC string plus a
   terminating NUL byte. i.e.  zBuf must be at least
   (FSL_STRLEN_MD5+1) bytes long.

   @see fsl_md5_final()
*/
FSL_EXPORT void fsl_md5_digest_to_base16(unsigned char const *digest,
                                         char *zBuf);

/**
   The md5 counterpart of fsl_sha1sum_buffer(), identical in
   semantics except that its result is an MD5 hash instead of an
   SHA1 hash and the resulting hex string is FSL_STRLEN_MD5 bytes
   long plus a terminating NUL.
*/
FSL_EXPORT int fsl_md5sum_buffer(fsl_b const *pIn, fsl_b *pCksum);

/**
   The md5 counterpart of fsl_sha1sum_cstr(), identical in
   semantics except that its result is an MD5 hash instead of an
   SHA1 hash and the resulting string is FSL_STRLEN_MD5 bytes long
   plus a terminating NUL.
*/
FSL_EXPORT char *fsl_md5sum_cstr(const char *zIn, fsl_int_t len);

/**
   The MD5 counter part to fsl_sha1sum_stream(), with identical
   semantics except that the generated hash is an MD5 string
   instead of SHA1.
*/
FSL_EXPORT int fsl_md5sum_stream(fsl_input_f src, void * srcState, fsl_b *pCksum);

/**
   Reads all input from src() and passes it through fsl_md5_update(cx,...).
   Returns 0 on success, FSL_RC_MISUSE if !cx or !src. If src returns
   a non-0 code, that code is returned from here.
*/
FSL_EXPORT int fsl_md5_update_stream(fsl_md5_cx *cx, fsl_input_f src, void * srcState);

/**
   Equivalent to fsl_md5_update(cx, b->mem, b->used). Results are undefined
   if either pointer is invalid or NULL.
*/
FSL_EXPORT void fsl_md5_update_buffer(fsl_md5_cx *cx, fsl_b const * b);

/**
   Passes the first len bytes of str to fsl_md5_update(cx). If len
   is less than 0 then fsl_strlen() is used to calculate the
   length.  Results are undefined if either pointer is invalid or
   NULL. This is a no-op if !len or (len<0 && !*str).
*/
FSL_EXPORT void fsl_md5_update_cstr(fsl_md5_cx *cx, char const * str, fsl_int_t len);

/**
   A fsl_md5_update_stream() proxy which updates cx to include the
   contents of the given file.

   Returns 0 on success and FSL_RC_MISUSE if !cx or !fname. If the
   file cannot be opened it returns fsl_errno_to_rc() of the
   resulting errno, with FSL_RC_IO as the default. A read error gives
   FSL_RC_IO.
*/
FSL_EXPORT int fsl_md5_update_filename(fsl_md5_cx *cx, char const * fname);

/**
   The MD5 counter part to fsl_sha1sum_filename(), with identical
   semantics except that the generated hash is an MD5 string
   instead of SHA1.
*/
FSL_EXPORT int fsl_md5sum_filename(const char *zFilename, fsl_b *pCksum);


typedef void(*fsl_sha1h_collision_callback)(uint64_t, const uint32_t*, const uint32_t*, const uint32_t*, const uint32_t*);
/**
   Holds state for SHA1 calculations. It is intended to be used
   like this:

   ```
   unsigned char digest[FSL_STRLEN_SHA1/2]
   char hex[FSL_STRLEN_SHA1+1];
   fsl_sha1_cx cx;
   fsl_sha1_init(&cx); // REQUIRED, unlike its md5 counterpart

   ...call fsl_sha1_update(&cx,...) any number of times to
   ...incrementally calculate the hash.

   fsl_sha1_final(&cx, digest); // ends the calculation
   fsl_sha1_digest_to_base16(digest, hex);

   // digest now contains the raw 20-byte SHA1 digest.
   // hex now contains the 40-byte SHA1 + a trailing NUL
   ```
*/
struct fsl_sha1_cx {
  uint64_t total;
  uint32_t ihv[5];
  unsigned char buffer[64];
  int found_collision;
  int safe_hash;
  int detect_coll;
  int ubc_check;
  int reduced_round_coll;
  fsl_sha1h_collision_callback callback;
  uint32_t ihv1[5];
  uint32_t ihv2[5];
  uint32_t m1[80];
  uint32_t m2[80];
  uint32_t states[80][5];
};
/**
   fsl_sha1_cx instance intended for in-struct copy initialization.
*/
#define fsl_sha1_cx_empty_m {0}

/**
   fsl_sha1_cx instance intended for copy initialization. For build
   config portability, the copied-to object must still be passed to
   fsl_sha1_init() to initialize it.
*/
FSL_EXPORT const fsl_sha1_cx fsl_sha1_cx_empty;

/**
   Initializes the given context with the initial SHA1 state.  This
   must be the first routine called on an SHA1 context, and passing
   this context to other SHA1 routines without first having passed
   it to this will lead to undefined results.

   @see fsl_sha1_update()
   @see fsl_sha1_final()
*/
FSL_EXPORT void fsl_sha1_init(fsl_sha1_cx *context);

/**
   Updates the given context to include the hash of the first len
   bytes of the given data.

   @see fsl_sha1_init()
   @see fsl_sha1_final()
*/
FSL_EXPORT void fsl_sha1_update( fsl_sha1_cx *context, void const *data, fsl_size_t len);

/**
   Add padding and finalizes the message digest. If digest is not NULL
   then it writes 20 bytes of digest to the 2nd parameter. This
   function returns non-0 if a collision is detected while hashing. If
   no collision is detected, it returns 0.

   @see fsl_sha1_update()
   @see fsl_sha1_digest_to_base16()
*/
FSL_EXPORT int fsl_sha1_final(fsl_sha1_cx *context, unsigned char * digest);

/**
   A convenience form of fsl_sha1_final() which writes
   FSL_STRLEN_SHA1+1 bytes (hash plus terminating NUL byte) to the
   2nd argument and returns a (const char *)-type cast of the 2nd
   argument.
*/
FSL_EXPORT const char * fsl_sha1_final_hex(fsl_sha1_cx *context, char * zHex);

/**
   Convert a digest into base-16.  digest must be at least 20 bytes
   long and hold an SHA1 digest. zBuf must be at least (FSL_STRLEN_SHA1
   + 1) bytes long, to which FSL_STRLEN_SHA1 characters of
   hexidecimal-form SHA1 hash and 1 NUL byte will be written.

   @see fsl_sha1_final()
*/
FSL_EXPORT void fsl_sha1_digest_to_base16(unsigned char const *digest,
                                          char *zBuf);

/**
   Computes the SHA1 checksum of pIn and stores the resulting
   checksum in the buffer pCksum.  pCksum's memory is re-used if is
   has any allocated to it. pCksum may == pIn, in which case this
   is a destructive operation (replacing the hashed data with its
   hash code).

   Return 0 on success, FSL_RC_OOM if (re)allocating pCksum fails.
*/
FSL_EXPORT int fsl_sha1sum_buffer(fsl_b const *pIn, fsl_b *pCksum);

/**
   Works like fsl_sha1sum_buffer() except that it appends the hash to
   the target buffer, rather than re-using the whole target. It is
   legal for both arguments to refer to the same object.
*/
FSL_EXPORT int fsl_sha1sum_buffer2(fsl_b const *pIn, fsl_b *pCksum);

/**
   Computes the SHA1 checksum of the first len bytes of the given
   string.  If len is negative then zIn must be NUL-terminated and
   fsl_strlen() is used to find its length. The result is a
   FSL_UUID_STRLEN-byte string (+NUL byte) returned in memory
   obtained from fsl_malloc(), so it must be passed to fsl_free()
   to free it. If NULL==zIn or !len then NULL is returned.
*/
FSL_EXPORT char *fsl_sha1sum_cstr(const char *zIn, fsl_int_t len);

/**
   Consumes all input from src and calculates its SHA1 hash. The
   result is set in pCksum (its contents, if any, are overwritten,
   not appended to). Returns 0 on success. Returns FSL_RC_MISUSE if
   !src or !pCksum. It keeps consuming input from src() until that
   function reads fewer bytes than requested, at which point EOF is
   assumed. If src() returns non-0, that code is returned from this
   function.
*/
FSL_EXPORT int fsl_sha1sum_stream(fsl_input_f src, void * srcState, fsl_b *pCksum);


/**
   A fsl_sha1sum_stream() wrapper which calculates the SHA1 of
   given file.

   Returns FSL_RC_MISUSE if !zFilename or !pCksum. If the file cannot
   be opened it returns fsl_errno_to_rc() of the resulting errno,
   with FSL_RC_IO as the default, so a missing file gives
   FSL_RC_NOT_FOUND and a permissions failure FSL_RC_ACCESS. Else it
   returns as per fsl_sha1sum_stream(), which gives FSL_RC_IO for a
   read error. This function has no error object, so callers which
   report the failure must name the file themselves.

   TODO: the v1 impl has special behaviour for symlinks which this
   function lacks. For that support we need a variant of this
   function which takes a fsl_cx parameter (for the allow-symlinks
   setting).
*/
FSL_EXPORT int fsl_sha1sum_filename(const char *zFilename, fsl_b *pCksum);

/**
   Reads all input from src() and passes it through fsl_sha1_update(cx,...).
   Returns 0 on success, FSL_RC_MISUSE if !cx or !src. If src returns
   a non-0 code, that code is returned from here.
*/
FSL_EXPORT int fsl_sha1sum_update_stream(fsl_sha1_cx *ctx, fsl_input_f src,
                                         void * srcState);

/**
   Legal values for SHA3 hash sizes, in bits: an increment of 32 bits
   in the inclusive range (128..512).

   The hexidecimal-code size, in bytes, of any given bit size in this
   enum is the bit size/4.
*/
enum fsl_sha3_hash_size {
/** Sentinel value. Must be 0. */
FSL_SHA3_INVALID = 0,
FSL_SHA3_128 = 128, FSL_SHA3_160 = 160, FSL_SHA3_192 = 192,
FSL_SHA3_224 = 224, FSL_SHA3_256 = 256, FSL_SHA3_288 = 288,
FSL_SHA3_320 = 320, FSL_SHA3_352 = 352, FSL_SHA3_384 = 384,
FSL_SHA3_416 = 416, FSL_SHA3_448 = 448, FSL_SHA3_480 = 480,
FSL_SHA3_512 = 512,
/* Default SHA3 flavor */
FSL_SHA3_DEFAULT = 256
};

/**
   Type for holding SHA3 processing state. Each instance must be
   initialized with fsl_sha3_init(), populated with fsl_sha3_update(),
   and "sealed" with fsl_sha3_end().

   Sample usage:

   ```
   fsl_sha3_cx cx;
   fsl_sha3_init(&cx, FSL_SHA3_DEFAULT);
   fsl_sha3_update(&cx, memory, lengthOfMemory);
   fsl_sha3_end(&cx);
   printf("Hash = %s\n", (char const *)cx.hex);
   ```

   After fsl_sha3_end() is called cx.hex contains the hex-string forms
   of the digest. fsl_sha3_update() may be called an arbitrary number
   of times to feed in chunks of memory (e.g. to stream in arbitrarily
   large data).
*/
struct fsl_sha3_cx {
    union {
        uint64_t s[25];         /* Keccak state. 5x5 lines of 64 bits each */
        unsigned char x[1600];  /* ... or 1600 bytes */
    } u;
    unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
    unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
    unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
    enum fsl_sha3_hash_size size; /* Size of the hash, in bits. */
    unsigned char hex[132]; /* Hex form of final digest: 56-128 bytes
                               plus terminating NUL. */
};

/**
   If the given number is a valid fsl_sha3_hash_size value, its enum
   entry is returned, else FSL_SHA3_INVALID is returned.

   @see fsl_sha3_init()
*/
FSL_EXPORT enum fsl_sha3_hash_size fsl_sha3_hash_size_for_int(int);

/**
   Initialize a new hash. The second argument specifies the size of
   the hash in bits. Results are undefined if cx is NULL or sz is not
   a valid positive value.

   After calling this, use fsl_sha3_update() to hash data and
   fsl_sha3_end() to finalize the hashing process and generate a digest.
*/
FSL_EXPORT void fsl_sha3_init2(fsl_sha3_cx *cx, enum fsl_sha3_hash_size sz);

/**
   Equivalent to fsl_sha3_init2(cx, FSL_SHA3_DEFAULT).
*/
FSL_EXPORT void fsl_sha3_init(fsl_sha3_cx *cx);

/**
   Updates cx's state to include the first len bytes of data.

   If cx is NULL results are undefined (segfault!). If mem is not
   NULL then it must be at least n bytes long. If n is 0 then this
   function has no side-effects.

   @see fsl_sha3_init()
   @see fsl_sha3_end()
*/
FSL_EXPORT void fsl_sha3_update( fsl_sha3_cx *cx, void const *data, unsigned int len);

/**
   To be called when SHA3 hashing is complete: finishes the hash
   calculation and populates cx->hex with the final hash code in
   hexidecimal-string form. Returns the binary-form digest value,
   which refers to cx->size/8 bytes of memory which lives in the cx
   object. After this call cx->hex will be populated with cx->size/4
   bytes of lower-case ASCII hex codes plus a terminating NUL byte.

   Potential TODO: change fsl_sha1_final() and fsl_md5_final() to use
   these same return semantics.

   @see fsl_sha3_init()
   @see fsl_sha3_update()
*/
FSL_EXPORT unsigned char const * fsl_sha3_end(fsl_sha3_cx *cx);

/**
   SHA3-256 counterpart of fsl_sha1_digest_to_base16(). digest must be at least
   32 bytes long and hold an SHA3 digest. zBuf must be at least (FSL_STRLEN_K256+1)
   bytes long, to which FSL_STRLEN_K256 characters of
   hexidecimal-form SHA3 hash and 1 NUL byte will be written

   @see fsl_sha3_end().
*/
FSL_EXPORT void fsl_sha3_digest_to_base16(unsigned char const *digest,
                                          char *zBuf);
/**
   SHA3 counter part of fsl_sha1sum_buffer().
*/
FSL_EXPORT int fsl_sha3sum_buffer(fsl_b const *pIn, fsl_b *pCksum);
/**
   SHA3 counter part of fsl_sha1sum_cstr().
*/
FSL_EXPORT char *fsl_sha3sum_cstr(const char *zIn, fsl_int_t len);
/**
   SHA3 counterpart of fsl_sha1sum_stream().
*/
FSL_EXPORT int fsl_sha3sum_stream(fsl_input_f src, void * srcState,
                                  fsl_b *pCksum);
/**
   SHA3 counterpart of fsl_sha1sum_filename().
*/
FSL_EXPORT int fsl_sha3sum_filename(const char *zFilename, fsl_b *pCksum);

/**
   Expects zHash to be a full-length hash value of one of the
   fsl_hash_types_t-specified types, and nHash to be the length, in
   bytes, of zHash's contents (which must be the full hash length, not
   a prefix). If zHash can be validated as a hash, its corresponding
   hash type is returned, else FSL_HTYPE_ERROR is returned.
*/
FSL_EXPORT fsl_hash_types_e fsl_validate_hash(const char *zHash,
                                              fsl_size_t nHash);

/**
   Expects (zHash, nHash) to refer to a full hash (of a supported
   content hash type) of pIn's contents. This routine hashes pIn's
   contents and, if it compares equivalent to zHash then the ID of the
   hash type is returned.  On a mismatch, FSL_HTYPE_ERROR is returned.
*/
FSL_EXPORT fsl_hash_types_e fsl_verify_blob_hash(fsl_b const * pIn,
                                                 const char *zHash, int nHash);

/**
   Returns a human-readable name for the given hash type, or its
   second argument h is not a supported hash type.
 */
FSL_EXPORT const char * fsl_hash_type_name(fsl_hash_types_e h,
                                           const char *zUnknown);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_HASH_H_INCLUDED */
/* end of file include/fossil-scm/hash.h */
/* start of file include/fossil-scm/repo.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_REPO_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_REPO_H_INCLUDED
/*
  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-FileType: Code

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

/** @file repo.h

    repo.h declares APIs specifically dealing with repository-db-side
    state, as opposed to specifically checkout-side state or
    non-content-related APIs.
*/


#if defined(__cplusplus)
extern "C" {
#endif

typedef struct fsl_card_F fsl_card_F;
typedef struct fsl_card_J fsl_card_J;
typedef struct fsl_card_Q fsl_card_Q;
typedef struct fsl_card_T fsl_card_T;
typedef struct fsl_checkin_opt fsl_checkin_opt;
typedef struct fsl_deck fsl_deck;
typedef struct fsl_uperm fsl_uperm;

/**
   Opens the given db file name as f's repository. Returns 0 on
   success. On error it sets f's error state and returns that code
   unless the error was FSL_RC_MISUSE (which indicates invalid
   arguments and it does not set the error state).

   Returns FSL_RC_ACCESS if f already has an opened repo db (use
   fsl_repo_close() or fsl_ckout_close() to close it).

   Returns FSL_RC_NOT_FOUND if repoDbFile is not found, as this
   routine cannot create a new repository db.

   Returns FSL_RC_NOT_A_REPO if repoDbFile is not an SQLite database
   or lacks the tables of a repository schema (the same check
   fossil(1) applies), in which case it is not left opened.

   Results are undefined if any argument is NULL.

   When a repository is opened, the fossil-level user name
   associated with f (if any) is overwritten with the default user
   from the repo's login table (the one with uid=1). Thus
   fsl_cx_user_get() may return a value even if the client has not
   called fsl_cx_user_set().

   It would be nice to have a parameter specifying that the repo
   should be opened read-only. That's not as straightforward as it
   sounds because of how the various dbs are internally managed
   (via one db handle). Until then, the permissions of the
   underlying repo file will determine how it is opened. i.e. a
   read-only repo will be opened read-only.


   Potentially interesting side-effects:

   - On success this re-sets several bits of f's configuration to
   match the repository-side settings.

   @see fsl_repo_create()
   @see fsl_repo_close()
   @see fsl_close_scm_dbs()
*/
FSL_EXPORT int fsl_repo_open( fsl_cx * f, char const * repoDbFile/*, char readOnlyCurrentlyIgnored*/ );

/**
   Opens as f's repository the repository whose tables are tables of
   the main db of f's host db handle (fsl_cx_host_db()) with names
   starting with zPrefix, e.g. "fslrepo_lib_" for main.fslrepo_lib_blob
   and so on, as made by fsl_repo_create() with
   fsl_repo_create_opt::hostTablePrefix or by fsl_repo_import().
   Nothing is ATTACHed, and the host's own tables, including any named
   like repository tables without the prefix, are not touched. One
   host db can so hold several repositories, each with a prefix of its
   own, beside working copies (fsl_repo_open_ckout_opt::hostTablePrefix)
   and the host's own tables, and a host transaction can span all of
   them.

   The prefix must match [A-Za-z_][A-Za-z0-9_]*, so that the prefixed
   names are identifiers without quoting, and must not start with
   "sqlite_" (in any case), else FSL_RC_RANGE. Since some repository
   tables are only created when first used (e.g. the forum's), the
   prefix is the repository's namespace: it may neither be the start
   of another repository's or working copy's prefix nor start with
   one, ignoring case, else FSL_RC_ALREADY_EXISTS. That holds for the
   prefixes of the other contexts on that handle, for those of the
   repositories and working copies recorded in the main db (see
   fsl_repo_open_ckout_opt::hostTablePrefix; a repository is a P with
   tables Pblob and Pconfig, the latter with a 'content-schema' row),
   and for the names of the SQLite extension's working copies, which
   start with "fslfiles_", "fslclock_" and "fslwc_". The prefix must
   be spelled as the tables are, including case, else FSL_RC_MISUSE
   with the stored spelling in the error message, since SQLite's GLOB,
   which picks the repository's tables (e.g. for fsl_repo_export()),
   does not ignore case.

   Returns FSL_RC_ACCESS if f already has an opened repository,
   FSL_RC_MISUSE if f is not bound to a host db handle,
   FSL_RC_UNSUPPORTED if the host's main db is not a file, and
   FSL_RC_NOT_A_REPO if the main db lacks the prefixed tables of a
   repository (the same check as fsl_repo_open()'s). Otherwise it
   behaves like fsl_repo_open().

   The host db's settings are left as they are: its application_id is
   not set, its journal mode and synchronous setting are not changed
   (fsl_repo_journal_mode_set() fails), and a check-in to a checkout
   whose tables are in the same db needs no particular journal mode.
   Closing the repository drops none of its tables. A rebuild
   (fsl_repo_rebuild()) drops and recreates only the tables which
   libfossil's transient schemas define (see fsl_schema_repo2()), with
   the prefix, never others with it, which may be the host's. The
   repository's ticket schema (its "ticket-table" setting) gets the
   prefix for every object it makes and every table it names; one
   which names a table it does not make itself (e.g. in a trigger),
   which would be the host's, or makes anything but tables, indexes,
   views and triggers, is refused with FSL_RC_CONSISTENCY when the
   ticket tables are made (e.g. by a rebuild). fsl_cx_db_file_repo() returns the host main db's file name,
   which fsl_reserved_fn_check() then treats as the repository db.

   A repository so opened has no file name of its own: its identity is
   the host db and the prefix, and a checkout of it records it, in its
   vvar "repository" entry, as "fsl-host-prefix:" followed by the
   prefix (which is never the canonical file name which libfossil and
   fossil(1) record for a repository db), along with its
   "project-code". Such a checkout, in the host db or on disk, reopens
   with its repository only on a context bound to a host db handle
   whose main db has those tables, and only if they have that
   project-code (else FSL_RC_REPO_MISMATCH). The global config db's
   list of repositories ("repo:" entries) does not list them.

   The schema's REFERENCES clauses name the prefixed tables, but
   foreign keys are not enforced: libfossil requires PRAGMA
   foreign_keys=OFF on a host's handle.

   @see fsl_repo_export()
   @see fsl_repo_import()
*/
FSL_EXPORT int fsl_repo_open_host( fsl_cx * f, char const * zPrefix );

/**
   Writes f's opened repository, whether a db file of its own or tables
   of a host's main db (fsl_repo_open_host()), to the new file zFile
   as a standalone repository db, with the normal unprefixed table
   names and its PRAGMA application_id, which fossil(1) can open. If
   zFile exists, this fails with FSL_RC_ALREADY_EXISTS unless overwrite
   is true, in which case zFile and its -journal, -wal and -shm files
   are removed first, but never a db file of f's db connection (e.g.
   the repository's own or the host's), for which it fails with
   FSL_RC_MISUSE.

   Every table is copied as stored, including those which only
   fossil(1) creates (e.g. accesslog, unversioned, chat, alias,
   subscriber, pending_alert, admin_log, modreq, purgeevent, purgeitem,
   fx_*), with its rows, artifacts as they are stored (compressed and
   deltified, so that nothing is re-encoded and no rebuild is needed),
   its indexes and AUTOINCREMENT counters, along with the views and
   triggers. Left out are the virtual tables, i.e. the full-text
   search indexes (fossil(1)'s ftsidx and chatfts1), with their shadow
   tables and the documents of the search index (ftsdocs, its indexes
   and the view ftscontent), whose module arguments name tables which
   renaming cannot follow: the export has no search index, which
   "fossil fts-config index on" makes anew, and fossil(1) makes its chat
   index again the next time it uses chat (its chat_create_tables()).

   It reads the repository in one transaction, so the export is a
   consistent snapshot. It must be called outside a transaction,
   including one on a host db handle (else FSL_RC_MISUSE), since it
   ATTACHes zFile and an in-memory scratch db, which it DETACHes
   afterwards. On error, the new file is removed. Returns 0 on
   success, else an error code, with f's error state set.

   @see fsl_repo_import()
*/
FSL_EXPORT int fsl_repo_export( fsl_cx * f, char const * zFile,
                                bool overwrite );

/**
   Copies repository db file zFile into the main db of f's host db
   handle (fsl_cx_host_db()) as tables whose names start with zPrefix,
   in one transaction, and opens them as f's repository, as
   fsl_repo_open_host() does. Once it has checked the prefix and that
   zFile is a repository, it closes any repository and checkout f has
   opened, which fails inside a transaction.

   The copy is the reverse of fsl_repo_export()'s, with the same
   tables, rows and artifacts as stored, and the same exception for
   the search indexes. The rules for zPrefix are fsl_repo_open_host()'s,
   and the main db may have no table, index, trigger or view whose
   name starts with it (ignoring case), else FSL_RC_ALREADY_EXISTS:
   the copy never adopts or drops a table of the host's or of another
   repository or working copy. To import again, drop the tables
   first. The transaction holds the main db's write lock from before
   its checks. If zFile is not a repository (FSL_RC_NOT_A_REPO), or
   anything fails, nothing is left in the main db.

   Returns FSL_RC_NOT_FOUND if zFile does not exist, FSL_RC_MISUSE if f
   is not bound to a host db handle or the handle is in a transaction
   (SQLite cannot ATTACH zFile there), and otherwise 0 or an error
   code, with f's error state set.
*/
FSL_EXPORT int fsl_repo_import( fsl_cx * f, char const * zFile,
                                char const * zPrefix );

/**
   This function is a programmatic interpretation of
   this table:

   https://fossil-scm.org/index.html/doc/trunk/www/fileformat.wiki#summary

   For a given control artifact type and a card name in the form of
   the card name's letter (e.g. 'A', 'W', ...), this function
   returns 0 (false) if that card type is not permitted in this
   control artifact type, a negative value if the card is optional
   for this artifact type, and a positive value if the card type is
   required for this artifact type.

   As a special case, if t==FSL_SATYPE_ANY then this function
   always returns a negative value as long as card is a valid card
   letter.

   Another special case: when t==FSL_SATYPE_CHECKIN and card=='F',
   this returns a negative value because the table linked to above
   says F-cards are optional. In practice we have yet to find a use
   for checkins with no F-cards, so this library currently requires
   F-cards at checkin-time even though this function reports that
   they are optional.
*/
FSL_EXPORT int fsl_card_is_legal( fsl_satype_e t, char card );

/**
   Artifact tag types used by the Fossil framework. Their values
   are a hard-coded part of the Fossil format, and not subject to
   change (only extension, possibly).
*/
enum fsl_tagtype_e {
/**
   Sentinel value for use with constructors/initializers.
*/
FSL_TAGTYPE_INVALID = -1,
/**
   The "cancel tag" indicator, a.k.a. an anti-tag.
*/
FSL_TAGTYPE_CANCEL = 0,
/**
   The "add tag" indicator, a.k.a. a singleton tag.
*/
FSL_TAGTYPE_ADD = 1,
/**
   The "propagating tag" indicator.
*/
FSL_TAGTYPE_PROPAGATING = 2
};
typedef enum fsl_tagtype_e fsl_tagtype_e;

/**
   Hard-coded IDs used by the 'tag' table of repository DBs. These
   values get installed as part of the base Fossil db schema in new
   repos, and they must never change.
*/
enum fsl_tagid_e {
/**
   DB string tagname='bgcolor'.
*/
FSL_TAGID_BGCOLOR = 1,
/**
   DB: tag.tagname='comment'.
*/
FSL_TAGID_COMMENT = 2,
/**
   DB: tag.tagname='user'.
*/
FSL_TAGID_USER = 3,
/**
   DB: tag.tagname='date'.
*/
FSL_TAGID_DATE = 4,
/**
   DB: tag.tagname='hidden'.
*/
FSL_TAGID_HIDDEN = 5,
/**
   DB: tag.tagname='private'.
*/
FSL_TAGID_PRIVATE = 6,
/**
   DB: tag.tagname='cluster'.
*/
FSL_TAGID_CLUSTER = 7,
/**
   DB: tag.tagname='branch'.
*/
FSL_TAGID_BRANCH = 8,
/**
   DB: tag.tagname='closed'.
*/
FSL_TAGID_CLOSED = 9,
/**
   DB: tag.tagname='parent'.
*/
FSL_TAGID_PARENT = 10,
/**
   DB: tag.tagname='note'

   Extra text appended to a check-in comment.

   2026-09: neither fossil(1) nor libfossil have ever implemented this
   capability.
*/
FSL_TAGID_NOTE = 11,

/**
   Largest tag ID reserved for internal use.
*/
FSL_TAGID_MAX_INTERNAL = 99
};


/**
   Returns one of '-', '+', or '*' for a valid input parameter, 0
   for any other value.
*/
FSL_EXPORT char fsl_tag_prefix_char( fsl_tagtype_e t );


/**
   A list of fsl_card_F objects. F-cards used a custom list type,
   instead of the framework's generic fsl_list, because experience has
   shown that the number of (de)allocations we need for F-card lists
   has a large negative impact when parsing and creating artifacts en
   masse. This list type, unlike fsl_list, uses a conventional object
   array approach to storage, as opposed to an array of pointers (each
   entry of which has to be separately allocated).

   These lists, and F-cards in generally, are typically maintained
   internally in the library. There's probably "no good reason" for
   clients to manipulate them.
*/
struct fsl_card_F_list {
  /**
     The list of F-cards. The first this->used elements are in-use.
     This pointer may change any time the list is reallocated.
  */
  fsl_card_F * list;
  /**
     The number of entries in this->list which are in use.
  */
  uint32_t used;
  /**
     The number of entries currently allocated in this->list.
  */
  uint32_t capacity;
  /**
     An internal cursor into this->list, used primarily for
     properly traversing the file list in delta manifests.

     Maintenance notes: internal updates to this member are the only
     reason some of the deck APIs require a non-const deck. This type
     needs to be signed for compatibility with some of the older
     algos, e.g. fsl__deck_F_seek_base().
  */
  int32_t cursor;
  /**
     Internal flags. Never, ever modify these from client code.
  */
  uint32_t flags;
};
typedef struct fsl_card_F_list fsl_card_F_list;
/** Empty-initialized fsl_card_F instance for const copy
    initialization */
#define fsl_card_F_list_empty_m {NULL, 0, 0, 0, 0}
/** Empty-initialized fsl_card_F instance for non-const copy
    initialization */
FSL_EXPORT const fsl_card_F_list fsl_card_F_list_empty;

/**
   A "deck" stores (predictably enough) a collection of "cards."
   Cards are constructs embedded within Fossil's Structural Artifacts
   to denote various sorts of changes in a Fossil repository, and a
   Deck encapsulates the cards for a single Structural Artifact of an
   arbitrary type, e.g. Manifest (a.k.a. "checkin") or Cluster. A card
   is basically a command with a single-letter name and a well-defined
   signature for its arguments. Each card is represented by a member
   of this struct whose name is the same as the card type
   (e.g. fsl_card::C holds a C-card and fsl_card::F holds a list of
   F-card). Each type of artifact only allows certain types of
   card. The complete list of valid card/construct combinations can be
   found here:

   https://fossil-scm.org/home/doc/trunk/www/fileformat.wiki#summary

   fsl_card_is_legal() can be used determine if a given card type
   is legal (per the above chart) with a given Control Artifiact
   type (as stored in the fsl_deck::type member).

   The type member is used by some algorithms to determine which
   operations are legal on a given artifact type, so that they can
   fail long before the user gets a chance to add a malformed artifact
   to the database. Clients who bypass the fsl_deck APIs and
   manipulate the deck's members "by hand" (so to say) effectively
   invoke undefined behaviour.

   The various routines to add/set cards in the deck are named
   fsl_deck_CARDNAME_add() resp. fsl_deck_CARDNAME_set(). The "add"
   functions represent cards which may appear multiple times
   (e.g. the 'F' card) or have multiple values (the 'P' card), and
   those named "set" represent unique or optional cards. The R-card
   is the outlier, with fsl_deck_R_calc(). NEVER EVER EVER directly
   modify a member of this struct - always use the APIs. The
   library performs some optimizations which can lead to corrupt
   memory and invalid free()s if certain members' values are
   directly replaced by the client (as opposed to via the APIs).

   Note that the 'Z' card is not in this structure because it is a
   hash of the other inputs and is calculated incrementally and
   appended automatically by fsl_deck_output().

   All non-const pointer members of this structure are owned by the
   structure instance unless noted otherwise (the fsl_deck::f member
   being the notable exception).

   Maintenance reminder: please keep the card members alpha sorted to
   simplify eyeball-searching through their docs.

   @see fsl_deck_malloc()
   @see fsl_deck_init()
   @see fsl_deck_parse()
   @see fsl_deck_load_rid()
   @see fsl_deck_finalize()
   @see fsl_deck_clean()
   @see fsl_deck_save()
   @see fsl_deck_A_set()
   @see fsl_deck_B_set()
   @see fsl_deck_C_set()
   @see fsl_deck_D_set()
   @see fsl_deck_E_set()
   @see fsl_deck_F_add()
   @see fsl_deck_J_add()
   @see fsl_deck_K_set()
   @see fsl_deck_L_set()
   @see fsl_deck_M_add()
   @see fsl_deck_N_set()
   @see fsl_deck_P_add()
   @see fsl_deck_Q_add()
   @see fsl_deck_T_add()
   @see fsl_deck_branch_set()
   @see fsl_deck_U_set()
   @see fsl_deck_W_set()
*/
struct fsl_deck {
  /**
     Specifies the the type (or eventual type) of this
     artifact. The function fsl_card_is_legal() can be used to
     determined if a given card type is legal for a given value of
     this member. APIs which add/set cards use that to determine if
     the operation requested by the client is semantically legal.
  */
  fsl_satype_e type;

  /**
     DB repo.blob.rid value. Normally set by fsl_deck_load_rid().
  */
  fsl_id_t rid;

  /**
     The Fossil context responsible for this deck. Though this data
     type is normally, at least conceptually, free of any given fossil
     context, many related algorithms need a context in order to
     perform db- or caching-related work, as well as to simplify error
     message propagation. We store this as a struct member to keep all
     such algorithms from redundantly requiring both pieces of
     information as arguments.

     This object does not own the context and the context object must
     outlive this deck instance.
  */
  fsl_cx * f;

  /**
     The 'A' (attachment) card. Only used by FSL_SATYPE_ATTACHMENT
     decks. The spec currently specifies only 1 A-card per
     manifest, but conceptually this could/should be a list.
  */
  struct {
    /**
       Filename of the A-card.
    */
    char * name;

    /**
       Name of wiki page, or UUID of ticket or event (technote), to
       which the attachment applies.
    */
    char * tgt;

    /**
       UUID of the file being attached via the A-card.
    */
    fsl_uuid_str src;
  } A;

  struct {
    /**
       The 'B' (baseline) card holds the UUID of baseline manifest.
       This is empty for baseline manifests and holds the UUID of
       the parent for delta manifests.
    */
    fsl_uuid_str uuid;

    /**
       Baseline manifest corresponding to this->B. It is loaded on
       demand by routines which need it, typically by calling
       fsl_deck_F_rewind() (unintuitively enough!). The parent/child
       relationship in Fossil is the reverse of conventional -
       children own their parents, not the other way
       around. i.e. this->baseline will get cleaned up when the child
       part of that relationship is cleaned up.

       The baseline "should" be a baseline manifest but may itself be
       a delta manifest. In that case only its own F-cards are used,
       never those it inherits, and its own baseline is not loaded.
       fossil(1) behaves the same way.
    */
    fsl_deck * baseline;
  } B;
  /**
     The 'C' (comment) card.
  */
  char * C;

  /**
     The 'D' (date) card, in Julian format.
  */
  double D;

  /**
     The 'E' (event) card.
  */
  struct {
    /**
       The 'E' card's date in Julian Day format.
    */
    double julian;

    /**
       The 'E' card's UUID.
    */
    fsl_uuid_str uuid;
  } E;

  /**
     The 'F' (file) card container.
  */
  fsl_card_F_list F;

  /**
     UUID for the 'G' (forum thread-root) card.
  */
  fsl_uuid_str G;

  /**
     The H (forum title) card.
  */
  char * H;

  /**
     UUID for the 'I' (forum in-response-to) card.
  */
  fsl_uuid_str I;

  /**
     The 'J' card specifies changes to "value" of "fields" in
     tickets (FSL_SATYPE_TICKET).

     Holds (fsl_card_J*) entries.
  */
  fsl_list J;

  /**
     UUID for the 'K' (ticket) card.
  */
  fsl_uuid_str K;

  /**
     The 'L' (wiki name/title) card.
  */
  char * L;

  /**
     List of UUIDs (fsl_uuid_str) in a cluster ('M' cards).
  */
  fsl_list M;

  /**
     The 'N' (comment mime type) card. Note that this is only
     ostensibly supported by fossil, but fossil does not (as of
     2021-04-13) honor this value and always assumes that its value is
     "text/x-fossil-wiki".
  */
  char * N;

  /**
     List of UUIDs of parents ('P' cards). Entries are of type
     (fsl_uuid_str).
  */
  fsl_list P;

  /**
     'Q' (cherry pick) cards. Holds (fsl_card_Q*) entries.
  */
  fsl_list Q;

  /**
     The R-card holds an MD5 hash which is calculated based on the
     names, sizes, and contents of the files included in a
     manifest. See the class-level docs for a link to a page which
     describes how this is calculated.
  */
  char * R;

  /**
     List of 'T' (tag) cards. Holds (fsl_card_T*) instances.
  */
  fsl_list T;

  /**
     The U (user) card.
  */
  char * U;

  /**
     The W (wiki content) card.
  */
  fsl_b W;

  /**
     This is part of an optimization used when parsing fsl_deck
     instances from source text. For most types of card we re-use
     string values in the raw source text rather than duplicate them,
     and that requires storing the original text (as passed to
     fsl_deck_parse()). This requires that clients never tinker
     directly with values in a fsl_deck, in particular never assign
     over them or assume they know who allocated the memory for that
     bit.
  */
  fsl_b content;

  /**
     To potentially be used for a manifest cache.
  */
  fsl_deck * next;

  /**
     A marker which tells fsl_deck_finalize() whether or not
     fsl_deck_malloc() allocated this instance (in which case
     fsl_deck_finalize() will fsl_free() it) or not (in which case
     it does not fsl_free() it).
  */
  void const * allocStamp;
};

/**
   Initialized-with-defaults fsl_deck structure, intended for copy
   initialization.
*/
FSL_EXPORT const fsl_deck fsl_deck_empty;

/**
   Initialized-with-defaults fsl_deck structure, intended for
   in-struct and const copy initialization.
*/
#define fsl_deck_empty_m {                                  \
    FSL_SATYPE_ANY /*type*/,                                \
    0/*rid*/,                                            \
    NULL/*f*/,                                            \
    {/*A*/ NULL /* name */,                               \
           NULL /* tgt */,                                   \
           NULL /* src */},                                  \
    {/*B*/ NULL /*uuid*/,                                 \
           NULL /*baseline*/},                               \
    NULL /* C */,                                       \
    0.0 /*D*/,                                        \
    {/*E*/ 0.0 /* julian */,                          \
           NULL /* uuid */},                             \
    /*F*/ fsl_card_F_list_empty_m,  \
    0/*G*/,0/*H*/,0/*I*/,                           \
    fsl_list_empty_m /* J */,                       \
    NULL /* K */,                                 \
    NULL /* L */,                                 \
    fsl_list_empty_m /* M */,                     \
    NULL /* N */,                                 \
    fsl_list_empty_m /* P */,                     \
    fsl_list_empty_m /* Q */,                     \
    NULL /* R */,                                 \
    fsl_list_empty_m /* T */,                     \
    NULL /* U */,                                 \
    fsl_b_empty_m /* W */,                   \
    fsl_b_empty_m/*content*/,                \
    NULL/*next*/,                                 \
    NULL/*allocStamp*/                            \
  }


/**
   Allocates a new fsl_deck instance. Returns NULL on allocation
   error. The returned value must eventually be passed to
   fsl_deck_finalize() to free its resources.

   @see fsl_deck_finalize()
   @see fsl_deck_clean()
*/
FSL_EXPORT fsl_deck * fsl_deck_malloc(void);

/**
   Frees all resources belonging to the given deck's members
   (including its parents, recursively), and wipes deck clean of most
   state, but does not free() deck. Is a no-op if deck is NULL. As a
   special case, the (allocStamp, f) members of deck are kept intact.

   @see fsl_deck_finalize()
   @see fsl_deck_malloc()
   @see fsl_deck_clean2()
*/
FSL_EXPORT void fsl_deck_clean(fsl_deck * deck);

/**
   A variant of fsl_deck_clean() which "returns" its content buffer
   for re-use by transferring, after ensuring proper cleanup of its
   internals, its own content buffer's bytes into the given target
   buffer. Decks created "manually" do not have any content
   buffer contents, but those loaded via fsl_deck_load_rid() do. This
   function will fsl_b_swap() the contents of the given buffer
   (if any) with its own buffer, clean up its newly-acquired memory
   (tgt's previous contents, if any), and fsl_b_reuse() the
   output buffer.

   If tgt is NULL, this behaves exactly like fsl_deck_clean().
*/
FSL_EXPORT void fsl_deck_clean2(fsl_deck * deck, fsl_b * tgt);

/**
   Frees all memory owned by deck (see fsl_deck_clean()).  If deck
   was allocated using fsl_deck_malloc() then this function
   fsl_free()'s it, otherwise it does not free it.

   @see fsl_deck_malloc()
   @see fsl_deck_clean()
*/
FSL_EXPORT void fsl_deck_finalize(fsl_deck *deck);

/**
   Sets the A-card for an Attachment (FSL_SATYPE_ATTACHMENT)
   deck. Returns 0 on success.

   Returns FSL_RC_MISUSE if any of (mf, filename, target) are NULL,
   FSL_RC_SYNTAX if !*filename, if !*target, or if uuidSrc is not
   empty and fsl_is_uuid(uuidSrc) returns false.

   Returns FSL_RC_TYPE if mf is not (as determined by its mf->type
   member) of a deck type capable of holding 'A' cards. (Only decks
   of type FSL_SATYPE_ATTACHMENT may hold an 'A' card.) If uuidSrc
   is NULL or starts with a NUL byte then it is ignored, otherwise
   the same restrictions apply to it as to target.

   The target parameter represents the "name" of the
   wiki/ticket/event record to which the attachment applies. For
   wiki pages this is their normal name (e.g. "MyWikiPage"). For
   events and tickets it is their full 40-byte UUID.

   uuidSrc is the UUID of the attachment blob itself. If it is NULL
   or empty then this card indicates that the attachment will be
   "deleted" (insofar as anything is ever deleted in Fossil).
*/
FSL_EXPORT int fsl_deck_A_set( fsl_deck * mf, char const * filename,
                               char const * target,
                               fsl_uuid_cstr uuidSrc);

/**
   Sets or unsets (if uuidBaseline is NULL or empty) the B-card for
   the given manifest to a copy of the given UUID. Returns 0 on
   success, FSL_RC_MISUSE if !mf, FSL_RC_OOM on allocation
   error. Setting this will free any prior values in mf->B, including
   a previously loaded mf->B.baseline.

   If uuidBaseline is not NULL and fsl_is_uuid() returns false,
   FSL_RC_SYNTAX is returned. If it is NULL the current value is
   freed (semantically, though the deck may still own the memory), the
   B card is effectively removed, and 0 is returned.

   Returns FSL_RC_TYPE if mf is not syntactically allowed to have
   this card card (as determined by
   fsl_card_is_legal(mf->type,...)).

   Sidebar: the ability to unset this card is unusual within this API,
   and is a requirement the library-internal delta manifest creation
   process. Most of the card-setting APIs, even when they are
   described as working like this one, do not accept NULL hash values.
*/
FSL_EXPORT int fsl_deck_B_set( fsl_deck * mf, fsl_uuid_cstr uuidBaseline);

/**
   Semantically identical to fsl_deck_B_set() but sets the C-card and
   does not place a practical limit on the comment's length.  comment
   must be the comment text for the change being applied.  If the
   given length is negative, fsl_strlen() is used to determine its
   length.
*/
FSL_EXPORT int fsl_deck_C_set( fsl_deck * mf, char const * comment,
                               fsl_strlen_t cardLen);

/**
   Sets mf's D-card as a Julian Date value. Returns FSL_RC_MISUSE if
   !mf, FSL_RC_RANGE if date is negative, FSL_RC_TYPE if a D-card is
   not valid for the given deck, else 0. Passing a value of 0
   effectively unsets the card.
*/
FSL_EXPORT int fsl_deck_D_set( fsl_deck * mf, double date);

/**
   Sets the E-card in the given deck. date may not be negative -
   use fsl_db_julian_now() or fsl_julian_now() to get a default
   time if needed.  Retursn FSL_RC_MISUSE if !mf or !uuid,
   FSL_RC_RANGE if date is not positive, FSL_RC_RANGE if uuid is
   not a valid UUID string.

   Note that the UUID for an event, unlike most other UUIDs, need
   not be calculated - it may be a random hex string, but it must
   pass the fsl_is_uuid() test. Use fsl_db_random_hex() to generate
   random UUIDs. When editing events, e.g. using the HTML UI, only
   the most recent event with the same UUID is shown. So when
   updating events, be sure to apply the same UUID to the edited
   copies before saving them.
*/
FSL_EXPORT int fsl_deck_E_set( fsl_deck * mf, double date, fsl_uuid_cstr uuid);

/**
   Adds a new F-card to the given deck. The uuid argument is required
   to be NULL or pass the fsl_is_uuid() test. The name must be a
   "simplified path name" (as determined by fsl_is_simple_pathname()),
   or FSL_RC_RANGE is returned. Note that a NULL uuid is only valid
   when constructing a delta manifest, and this routine will return
   FSL_RC_MISUSE and update d->f's error state if uuid is NULL and
   d->B.uuid is also NULL. Returns FSL_RC_RANGE if uuid is not NULL
   and does not pass fsl_is_uuid().

   perms should be one of the fsl_fileperm_e values (0 is the usual
   case).

   priorName must only be non-NULL when renaming a file, and it must
   follow the same naming rules as the name parameter.

   Returns 0 on success.

   @see fsl_deck_F_set()
*/
FSL_EXPORT int fsl_deck_F_add( fsl_deck * d, char const * name,
                               fsl_uuid_cstr uuid,
                               fsl_fileperm_e perm,
                               char const * priorName);

/**
   Works mostly like fsl_deck_F_add() except that:

   1) It enables replacing an existing F-card with a new one matching
   the same name.

   2) It enables removing an F-card by passing a NULL uuid.

   3) It refuses to work on a deck for which d->uuid is not NULL or
   d->rid!=0, returning FSL_RC_MISUSE if either of those apply.

   If d contains no F-card matching the given name (case-sensitivity
   depends on d->f's fsl_cx_is_case_sensitive() value) then:

   - If the 3rd argument is NULL, it returns FSL_RC_NOT_FOUND with
     (effectively) no side effects (aside, perhaps, from sorting d->F
     if needed to perform the search).

   - If the 3rd argument is not NULL then it behaves identically to
     fsl_deck_F_add().

   If a match is found, then:

   - If the 3rd argument is NULL, it removes that entry from the
     F-card list and returns 0.

   - If the 3rd argument is not NULL, the fields of the resulting
     F-card are modified to match the arguments passed to this
     function, copying the values of all C-string arguments. (Sidebar:
     we may need to copy the name, despite already knowing it, because
     of how fsl_deck instances manage F-card memory.)

   In all cases, if the 3rd argument is NULL then the 4th and 5th
   arguments are ignored.

   Returns 0 on success, FSL_RC_OOM if an allocation fails.  See
   fsl_deck_F_add() for other failure modes. On error, d's F-card list
   may be left in an inconsistent state and it must not be used
   further.

   @see fsl_deck_F_add()
   @see fsl_deck_F_set_content()
*/
FSL_EXPORT int fsl_deck_F_set( fsl_deck * d, char const * name,
                               fsl_uuid_cstr uuid,
                               fsl_fileperm_e perm,
                               char const * priorName);
/**
   This variant of fsl_deck_F_set() accepts a buffer of content to
   store as the file's contents. Its hash is derived from that
   content, using fsl_repo_blob_lookup() to hash the given content.
   Thus this routine can replace existing F-cards and save their
   content at the same time. When doing so, it will try to make the
   parent version (if this is a replacement F-card) a delta of the new
   content version (it may refuse to do so for various resources, but
   any heuristics which forbid that will not trigger an error).

   The intended use of this routine is for adding or replacing content
   in a deck which has been prepared using fsl_deck_derive().

   Returns 0 on success, else an error code propagated by
   fsl_deck_F_set(), fsl_repo_blob_lookup(), or some other lower-level
   routine. This routine requires that a transaction is active and
   returns FSL_RC_MISUSE if none is active. For any non-trivial
   error's, d->f's error state will be updated with a description of
   the problem.

   Returns FSL_RC_MISUSE if `d->rid>0` (which indicates that the deck
   has already been saved in the repository). fsl_deck_derive() can be
   used to "extend" a saved deck into a new version before using this API.

   Returns FSL_RC_RANGE if zName is not a valid filename for use as a
   repository entry, as per fsl_is_simple_pathname().

   On error, d->f's error state will be updated with a description of
   the problem.

   TODO: add a fsl_cx-level or fsl_deck-level API for marking content
   saved this way as private. This type of content is intended for use
   cases which do not have a checkout, and thus cannot be processed
   with fsl_checkin_commit() (which includes a flag to mark its
   content as private).

   @see fsl_deck_F_set()
   @see fsl_deck_F_add()
   @see fsl_deck_derive()
*/
FSL_EXPORT int fsl_deck_F_set_content( fsl_deck * d, char const * name,
                                       fsl_b const * src,
                                       fsl_fileperm_e perm,
                                       char const * priorName);

/**
   This routine rewires d such that it becomes the basis for a derived
   version of itself. Requires that d be a loaded from a repository,
   complete with an RID, else FSL_RC_MISUSE is returned.

   In short, this function performs the following:

   - Clears d->P
   - Assigns d->P[0] to the UUID of d->rid
   - Clears d->rid
   - Clears any other members which need to be (re)set by the new
     child/derived version. That includes the following card
     letters: `ACDEGHIJKLMNQRTUW`.
   - If d is a delta manifest it restructures it as a new baseline
     (see below).
   - It specifically keeps d->F intact OR creates a new one (see below).

   Returns 0 on success, FSL_RC_OOM on an allocation error,
   FSL_RC_MISUSE if d->rid<=0 (i.e. the deck has never been saved or
   was not loaded from the db). If d->type is not FSL_SATYPE_CHECKIN,
   FSL_RC_TYPE is returned (supporting other derivable types is
   TODO). On error, d may be left in an inconsistent state and must
   not be used further except to pass it to fsl_deck_finalize().

   The intention of this function is to simplify creation of decks
   which are to be used for creating checkins without requiring a
   checkout.

   To avoid certain corner cases, this function does not allow
   creation of delta manifests. If d has a B-card then it is a delta.
   This function clears its B-card and recreates the F-card list using
   the B-card's F-card list and any F-cards from the current delta. In
   other words, it creates a new baseline manifest.

   The expected workflow for this API is something like:

   - Use fsl_deck_load_rid() to load a deck.
   - Pass that deck to fsl_deck_derive().
   - Update the deck's cards to suit.
   - fsl_deck_save() the deck.

   @todo Extend this to support other inheritable deck types, e.g.
   wiki, forum posts, and technotes.

   @see fsl_deck_F_set_content()
*/
FSL_EXPORT int fsl_deck_derive(fsl_deck * d);

/**
   Callback type for use with fsl_deck_F_foreach() and
   friends. Implementations must return 0 on success, FSL_RC_BREAK
   to abort looping without an error, and any other value on error.
*/
typedef int (*fsl_card_F_visitor_f)(fsl_card_F const * fc,
                                     void * state);

/**
   For each F-card in d, cb(card,visitorState) is called. Returns
   the result of that loop. If cb returns FSL_RC_BREAK, the
   visitation loop stops immediately and this function returns
   0. If cb returns any other non-0 code, looping stops and that
   code is returned immediately.

   This routine calls fsl_deck_F_rewind() to reset the F-card cursor
   and/or load d's baseline manifest (if any). If loading the baseline
   fails, an error code from fsl_deck_baseline_fetch() is returned.

   The F-cards will be visited in the order they are declared in
   d. For loaded-from-a-repo manifests this is always lexical order
   (for delta manifests, consistent across the delta and
   baseline). For hand-created decks which have not yet been
   fsl_deck_unshuffle()'d, the order is unspecified.
*/
FSL_EXPORT int fsl_deck_F_foreach( fsl_deck * d,
                                   fsl_card_F_visitor_f cb,
                                   void * visitorState );

/**
   Fetches the next F-card entry from d. fsl_deck_F_rewind() must
   have be successfully executed one time before calling this, as
   that routine ensures that the baseline is loaded (if needed),
   which is needed for proper iteration over delta manifests.

   This routine always assigns *f to NULL before starting its work, so
   the client can be assured that it will never contain the same value
   as before calling this (unless that value was NULL).

   On success 0 is returned and *f is assigned to the next F-card.
   If *f is NULL when returning 0 then the end of the list has been
   reached (fsl_deck_F_rewind() can be used to re-set it).

   Example usage:

   ```
   int rc;
   fsl_card_F const * fc = NULL;
   rc = fsl_deck_F_rewind(d);
   if(!rc) while( !(rc=fsl_deck_F_next(d, &fc)) && fc ) {...}
   // Or, more simply:
   fsl_deck_F_each(d, fc, rc) {...}
   ```

   The special case of deleted files: files which were deleted in a
   given version are not recorded in baseline manifests but are in
   delta manifests. To avoid inconsistencies, this routine does NOT
   include deleted files in its results, regardless of whether d is a
   baseline or delta. (It used to, but that turned out to be a design
   flaw in that it burdened all callers except for the very few (one?)
   which were (was?) interested in deletions.)

   If d's baseline is itself a delta manifest, only that baseline's
   own F-cards are merged with d's, never those it inherits from its
   own baseline. This is how fossil(1) resolves such a manifest.

   Implementation notes: for baseline manifests this is a very
   fast and simple operation. For delta manifests it gets
   rather complicated.
*/
FSL_EXPORT int fsl_deck_F_next( fsl_deck * d, fsl_card_F const **f );

/**
   A helper macro for looping over fsl_deck_F_next(). Its arguments
   are:

   - DECK: a valid (fsl_deck*)

   - FCARD: a (fsl_card_F const *) to point to the next F-card.

   - RCVAR: the name of a local int-type var to record the result of
     fsl_deck_F_next() and give the client a way to break out early
     without invoking break.

   It loops for so long as 0==RCVAR and fsl_deck_F_next() delivers
   a new card.

   Example:

   ```
    fsl_deck * d = a_fsl_deck_instance;
    fsl_card_F const * fc; // need not be initialized
    int rc = fsl_deck_F_rewind(d);
    fsl_deck_F_each(d, fc, rc){
      rc = doSomething(fc);
    }
    ```
*/
#define fsl_deck_F_each(DECK,FCARD,RCVAR) \
  while( 0==RCVAR && 0==(RCVAR=fsl_deck_F_next(DECK,&(FCARD))) && FCARD )

/**
   Rewinds d's F-card traversal iterator and loads d's baseline
   manifest, if it has one (i.e. if d->B.uuid is not NULL) and it is
   not loaded already (i.e. if d->B.baseline is NULL). Returns 0 on
   success. The only error condition is if loading of the a baseline
   manifest fails, noting that only delta manifests have baselines.

   Results are undefined if d->f is NULL, and that may trigger an
   assert() in debug builds.
*/
FSL_EXPORT int fsl_deck_F_rewind( fsl_deck * d );

/**
   Looks for a file in a manifest or (for a delta manifest) its
   baseline. No normalization of the given filename is performed -
   it is assumed to be relative to the root of the checkout.

   It requires that d->type be FSL_SATYPE_CHECKIN and that d be
   loaded from a stored manifest or have been fsl_deck_unshuffle()'d
   (if called on an under-construction deck). Specifically, this
   routine requires that d->F be sorted properly or results are
   undefined.

   d->f is assumed to be the fsl_cx instance which deck was loaded
   from, which impacts the search process as follows:

   - The search take's d->f's underlying case-insensitive option into
   account. i.e. if case-insensitivy is on then files in any case
   will match.

   - If no match is found in d and is a delta manifest (d->B.uuid
   is set) then d's baseline is lazily loaded (if needed) and
   the search continues there. (Delta manifests are only one level
   deep, so this is not recursive. If the baseline is itself a delta
   manifest, only its own F-cards are searched and a deletion marker
   there counts as no match.)

   Returns NULL if !d, !d->f, or d->type!=FSL_SATYPE_CHECKIN, if no
   entry is found, or if delayed loading of the parent manifest (if
   needed) of a delta manifest fails (in which case d->f's error
   state should hold more information about the problem). A caller
   which must tell "not found" from "could not search" should use
   fsl_deck_F_search2().

   In debug builds this function asserts that d is not NULL.

   Design note: d "should" be const, but search optimizations for
   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);

/**
   Works like fsl_deck_F_search() but tells a missing file from a
   search which could not be done: sets *rv to the entry for zName, or
   to NULL if there is none, and returns 0, or returns an error code,
   with d->f's error state set, if the search cannot be done (a delta
   manifest's baseline cannot be loaded). *rv is NULL whenever the
   result is not 0.
*/
FSL_EXPORT int fsl_deck_F_search2(fsl_deck *d, const char *zName,
                                  fsl_card_F const ** rv);

/**
   Given two F-card instances, this function compares their names
   (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_name( fsl_card_F const * lhs,
                                        fsl_card_F 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
   a delta manifest) then FSL_RC_RANGE is returned. Returns
   FSL_RC_NOT_A_REPO if f has no repository opened.

   On any error but FSL_RC_MISUSE (basic argument validation) f's
   error state is updated to describe the error.

   @see fsl_content_get()
*/
FSL_EXPORT int fsl_card_F_content( fsl_cx * f, fsl_card_F const * fc,
                                   fsl_b * dest );

/**
   Sets the 'G' card on a forum-post deck to a copy of the given
   UUID. Returns 0 on success, FSL_RC_SYNTAX if uuid does not pass
   fsl_is_uuid(), FSL_RC_TYPE if mf's type may not have a G-card, or
   FSL_RC_OOM on allocation error.
*/
FSL_EXPORT int fsl_deck_G_set( fsl_deck * mf, fsl_uuid_cstr uuid);
/**
   Sets the 'H' card on a forum-post deck to a copy of the given
   comment. If cardLen is negative then fsl_strlen() is used to
   calculate its length. Returns 0 on success, FSL_RC_SYNTAX if
   comment is not NULL and mf already has an I-card, FSL_RC_TYPE if
   mf's type may not have an H-card, or FSL_RC_OOM on allocation
   error.
 */
FSL_EXPORT int fsl_deck_H_set( fsl_deck * mf, char const * comment, fsl_int_t cardLen);
/**
   Sets the 'I' card on a forum-post deck to a copy of the given
   UUID. Returns 0 on success, FSL_RC_SYNTAX if uuid is not NULL and
   either mf already has an H-card or uuid does not pass
   fsl_is_uuid(), FSL_RC_TYPE if mf's type may not have an I-card,
   or FSL_RC_OOM on allocation error.
*/
FSL_EXPORT int fsl_deck_I_set( fsl_deck * mf, fsl_uuid_cstr uuid);

/**
   Adds a J-card to the given deck, setting/updating the given ticket
   property key to the given value. The key is required but the value
   is optional (may be NULL). If isAppend then the value is appended
   to any existing value, otherwise it replaces any existing value.

   It is currently unclear whether it is legal to include multiple
   J cards for the same key in the same control artifact, in
   particular if their isAppend values differ.

   Returns 0 on success, FSL_RC_MISUSE if !mf or !key, FSL_RC_SYNTAX
   if !*key, FSL_RC_TYPE if mf is of a type for which J cards are
   not legal (see fsl_card_is_legal()), FSL_RC_OOM on allocation
   error.
*/
FSL_EXPORT int fsl_deck_J_add( fsl_deck * mf, bool isAppend,
                               char const * key, char const * value );

/**
   Sets the K-card (ticket ID) on the given deck. If passed NULL, it
   creates a new ticket ID (a 40-digit string of random hex bytes) and
   returns FSL_RC_OOM if allocation of those bytes fails. If uuid is
   not NULL then it must be a 40-byte lower-case hex string, the K-card
   value of the ticket this change is being applied to. Returns
   FSL_RC_SYNTAX if uuid is not NULL and does not pass fsl_is_uuid(),
   and FSL_RC_TYPE if mf's type may not have a K-card.
*/
FSL_EXPORT int fsl_deck_K_set( fsl_deck * mf, fsl_uuid_cstr uuid);

/**
   Semantically identical fsl_deck_B_set() but sets the L-card.
   title must be the wiki page title text of the wiki page this
   change is being applied to. Returns FSL_RC_RANGE if title does not
   pass fsl_wiki_name_is_wellformed(), because fossil(1) rejects an
   artifact with such an L-card.
*/
FSL_EXPORT int fsl_deck_L_set( fsl_deck * mf, char const *title, fsl_int_t len);

/**
   Returns true if the first n bytes of z (all of z, up to its NUL
   terminator, if n is negative) are a well-formed wiki page name, as
   fossil(1) defines it: 1 to 100 bytes long, the first byte greater
   than 0x20, no byte below 0x20, no two spaces in a row, and no
   trailing space.

   The limit is in bytes, not characters. A character outside ASCII
   takes two to four bytes in UTF-8, so a name written in Chinese, for
   example, can have at most 33 characters. fossil(1) rejects an
   artifact whose L-card, or whose A-card wiki target, fails this test.
*/
FSL_EXPORT bool fsl_wiki_name_is_wellformed(char const *z, fsl_int_t n);

/**
   Adds the given UUID as an M-card entry. Returns 0 on success, or:

   FSL_RC_MISUSE if !mf or !uuid

   FSL_RC_TYPE if fsl_deck_check_type(mf,'M') returns false.

   FSL_RC_SYNTAX if !fsl_is_uuid(uuid).

   FSL_RC_OOM if memory allocation fails while adding the entry.
*/
FSL_EXPORT int fsl_deck_M_add( fsl_deck * mf, fsl_uuid_cstr uuid );

/**
   Semantically identical to fsl_deck_B_set() but sets the N card.
   mimeType must be the content mime type for comment text of the
   change being applied.
*/
FSL_EXPORT int fsl_deck_N_set( fsl_deck * mf, char const *mimeType, fsl_int_t len);

/**
   Adds the given UUID as a parent of the given change record. If len
   is less than 0 then fsl_strlen(parentUuid) is used to determine its
   length. Returns FSL_RC_SYNTAX if parentUuid does not pass
   fsl_is_uuid(), which includes an empty string, and FSL_RC_TYPE if
   mf's type may not have a P-card.

   Results are undefined if parentUuid is NULL.

   The first P-card added to a deck MUST be the UUID of its primary
   parent (one which was not involved in a merge operation). All
   others (from merges) are considered "non-primary."

*/
FSL_EXPORT int fsl_deck_P_add( fsl_deck * mf, fsl_uuid_cstr parentUuid);
/**
   A convenience wrapper around fsl_deck_P_add() which resolves the given
   RID to its UUID and passes it on to fsl_deck_P_add(). Returns non-0
   on error.
*/
FSL_EXPORT int fsl_deck_P_add_rid( fsl_deck * mf, fsl_id_t parentRid );

/**
   If d contains a P card with the given index, this returns the RID
   corresponding to the UUID at that index. Returns a negative value
   on error, 0 if there is no entry for that index (the index is out
   of bounds).
*/
FSL_EXPORT fsl_id_t fsl_deck_P_get_id(fsl_deck * d, int index);

/**
   Adds a Q-card record to the given deck. The type argument must
   be negative for a backed-out change, positive for a cherrypicked
   change.  target must be a valid UUID string. If baseline is not
   NULL then it also must be a valid UUID.

   Returns 0 on success, non-0 on error. FSL_RC_MISUSE if !mf or
   !target, FSL_RC_SYNTAX if type is 0 or target/baseline are not
   valid UUID strings (baseline may be NULL).
*/
FSL_EXPORT int fsl_deck_Q_add( fsl_deck * mf, int type,
                               fsl_uuid_cstr target,
                               fsl_uuid_cstr baseline );

/**
   Adds a new T-card (tag) entry to the given deck.

   If uuid is not NULL and fsl_is_uuid(uuid) returns false then
   this function returns FSL_RC_SYNTAX. If uuid is NULL then it is
   assumed to be the UUID of the currently-being-constructed
   artifact in which the tag is contained (which appears as the '*'
   character in generated artifacts).

   Returns 0 on success. Returns FSL_RC_MISUSE if !d or
   !name. Returns FSL_RC_TYPE (and update's d's error state with a
   message) if the T card is not legal for d (see
   fsl_card_is_legal()).  Returns FSL_RC_SYNTAX if !*name, tagType
   is invalid, or if uuid is not NULL and fsl_is_uuid(uuid)
   return false, and for the other tag rules which
   fsl_deck_T_add2() enforces. Returns FSL_RC_OOM if an allocation
   fails.
*/
FSL_EXPORT int fsl_deck_T_add( fsl_deck * d, fsl_tagtype_e tagType,
                               fsl_uuid_cstr uuid, char const * name,
                               char const * value);

/**
   Adds the given tag instance to the given manifest.
   Returns 0 on success, FSL_RC_MISUSE if either argument
   is NULL, FSL_RC_OOM if appending the tag to the list
   fails, FSL_RC_TYPE if mf's type may not have T-cards, and
   FSL_RC_SYNTAX if t's name is empty or entirely hexadecimal, if
   t->uuid is not NULL and does not pass fsl_is_uuid(), if mf is a
   CONTROL artifact and t has no uuid, or if mf is a TECHNOTE and t
   has a uuid or is not an ADD-type tag. On error, mf->f's error
   state describes the problem.

   On success ownership of t is passed to mf. On error ownership is
   not modified.
*/
FSL_EXPORT int fsl_deck_T_add2( fsl_deck * mf, fsl_card_T * t);

/**
   A convenience form of fsl_deck_T_add() which adds two propagating
   tags to the given deck: "branch" with a value of branchName and
   "sym-branchName" with no value.

   Returns 0 on success. Returns FSL_RC_OOM on allocation error and
   FSL_RC_RANGE if branchName is empty or contains any characters with
   ASCII values <=32d. It naively assumes that any characters >=128
   are part of multibyte UTF8 characters.

   ACHTUNG: this does not arrange for canceling the previous branch
   because it doesn't know that branch at this point. To cancel the
   previous branch a cancellation T-card needs to be added to the deck
   named "sym-BRANCHNAME". Historically such tags have had the value
   "Cancelled by branch", but that's not a requirement.
*/
FSL_EXPORT int fsl_deck_branch_set( fsl_deck * d, char const * branchName );

/**
   Calculates the value of d's R-card based on its F-cards and updates
   d->R. It may also, as a side-effect, sort d->F.list lexically (a
   requirement of a R-card calculation).

   Returns 0 on success. Requires that d->f have an opened
   repository db, else FSL_RC_NOT_A_REPO is returned. If d's type is
   not legal for an R-card then FSL_RC_TYPE is returned and d->f's
   error state is updated with a description of the error. If d is of
   type FSL_SATYPE_CHECKIN and has no F-cards then the R-card's value
   is that of the initial MD5 hash state. Various other codes can be
   returned if fetching file content from the db fails.

   Note that this calculation is exceedingly memory-hungry. While
   Fossil originally required R-cards, the cost of calculation
   eventually caused the R-card to be made optional. This API
   allows the client to decide on whether to use them (for more
   (admittedly redundant!) integrity checking) or not (much faster
   but "not strictly historically correct"), but defaults to having
   them enabled for symmetry with fossil(1).

   @see fsl_deck_R_calc2()
*/
FSL_EXPORT int fsl_deck_R_calc(fsl_deck * d);

/**
   A variant of fsl_deck_R_calc() which calculates the given deck's
   R-card but does not assign it to the deck, instead returning it
   via the 2nd argument:

   If *tgt is not NULL when this function is called, it is required to
   point to at least FSL_STRLEN_MD5+1 bytes of memory to which the
   NUL-terminated R-card hash will be written. If *tgt is NULL then
   this function assigns (on success) *tgt to a dynamically-allocated
   R-card hash and transfers ownership of it to the caller (who must
   eventually fsl_free() it). On error, *tgt is not modified.

   Results are undefined if either argument is NULL.

   Returns 0 on success. See fsl_deck_R_calc() for information about
   possible errors, with the addition that FSL_RC_OOM is returned
   if *tgt is NULL and allocating a new *tgt value fails.

   Calculating the R-card necessarily requires that d's F-card list be
   sorted, which this routine does if it seems necessary. The
   calculation also necessarily mutates the deck's F-card-traversal
   cursor, which requires loading the deck's B-card, if it has
   one. Aside from the F-card sorting, and potentially B-card, and the
   cursor resets, this routine does not modify the deck. On success,
   the deck's F-card iteration cursor (and that of d->B, if it's
   loaded) is rewound.
*/
FSL_EXPORT int fsl_deck_R_calc2(fsl_deck *d, char ** tgt);

/**
   Semantically identical fsl_deck_B_set() but sets the U-card.
   userName must be the user who's name should be recorded for
   this change.
*/
FSL_EXPORT int fsl_deck_U_set( fsl_deck * mf, char const *userName);

/**
   Semantically identical fsl_deck_B_set() but sets the W-card.
   content must be the page content of the Wiki page or Event this
   change is being applied to.
*/
FSL_EXPORT int fsl_deck_W_set( fsl_deck * mf, char const *content, fsl_int_t len);

/**
   Must be called to initialize a newly-created/allocated deck
   instance. This function clears out all contents of the d
   parameter except for its (f, type, allocStamp) members, sets its
   (f, type) members, and leaves d->allocStamp intact.

   Note that, prior to calling this, the deck _must_ have been cleanly
   initialized via copying from fsl_deck_empty or (depending on the
   context) fsl_deck_empty_m or results are undefined.
*/
FSL_EXPORT void fsl_deck_init( fsl_cx * cx, fsl_deck * d,
                               fsl_satype_e type );

/**
   Returns true if d contains data for all _required_ cards, as
   determined by the value of d->type, else returns false. It returns
   false if d->type==FSL_SATYPE_ANY, as that is a placeholder value
   intended to be re-set by the deck's user.

   If it returns false, d->f's error state will help a description of
   the problem.

   The library calls this as needed, but clients may, if they want
   to. Note, however, that for FSL_SATYPE_CHECKIN decks it may fail
   if the deck has not been fsl_deck_unshuffle()d yet because the
   R-card gets calculated there (if needed).

   As a special case, d->f is configured to calculate R-cards,
   d->type==FSL_SATYPE_CHECKIN, AND d->R is not set, this will fail
   (with a descriptive error message).

   Another special case: for FSL_SATYPE_CHECKIN decks, if no
   F-cards are in th deck then an R-card is required to avoid a
   potental (admittedly harmless) syntactic ambiguity with
   FSL_SATYPE_CONTROL artifacts. The only legal R-card for a
   checkin with no F-cards has the initial MD5 hash state value
   (defined in the constant FSL_MD5_INITIAL_HASH), and that
   precondition is checked in this routine. fsl_deck_unshuffle()
   recognizes this case and adds the initial-state R-card, so
   clients normally need not concern themselves with this. If d has
   F-cards, whether or not an R-card is required depends on
   whether d->f is configured to require them or not.

   Enough about the R-card. In all other cases not described above,
   R-cards are not required (and they are only ever required on
   FSL_SATYPE_CHECKIN manifests).

   Though fossil(1) does not technically require F-cards in
   FSL_SATYPE_CHECKIN decks, so far none of the Fossil developers
   have found a use for a checkin without F-cards except the
   initial empty checkin. Additionally, a checkin without F-cards
   is potentially syntactically ambiguous (it could be an EVENT or
   ATTACHMENT artifact if it has no F- or R-card). So... this
   library _normally_ requires that CHECKIN decks have at least one
   F-card. This function, however, does not consider F-cards to be
   strictly required.
*/
FSL_EXPORT bool fsl_deck_has_required_cards( fsl_deck const * d );

/**
   Prepares the given deck for output by ensuring that cards
   which need to be sorted are sorted, and it may run some
   last-minute validation checks.

   The cards which get sorted are: F, J, M, Q, T. The P-card list is
   _not_ sorted - the client is responsible for ensuring that the
   primary parent is added to that list first, and after that the
   ordering is largely irrelevant. It is not possible for the library
   to determine a proper order for P-cards, nor to validate that order
   at input-time.

   If calculateRCard is true and fsl_card_is_legal(d,'R') then this
   function calculates the R-card for the deck. The R-card
   calculation is _extremely_ memory-hungry but adds another level
   of integrity checking to Fossil. If d->type is not
   FSL_SATYPE_MANIFEST then calculateRCard is ignored.

   If calculateRCard is true but no F-cards are present AND d->type is
   FSL_SATYPE_CHECKIN then the R-card is set to the initial MD5 hash
   state (the only legal R-card value for an empty F-card list). (This
   is necessary in order to prevent a deck-type ambiguity in one
   corner case.)

   The R-card, if used, must be calculated before
   fsl_deck_output()ing a deck containing F-cards. Clients may
   alternately call fsl_deck_R_calc() to calculate the R card
   separately, but there is little reason to do so. There are rare
   cases where the client can call fsl_deck_R_set()
   legally. Historically speaking the R-card was required when
   F-cards were used, but it was eventually made optional because
   (A) the memory cost and (B) it's part of a 3rd or 4th level of
   integrity-related checks, and is somewhat superfluous.

   @see fsl_deck_output()
   @see fsl_deck_save()
*/
FSL_EXPORT int fsl_deck_unshuffle( fsl_deck * d, bool calculateRCard );

/**
   Renders the given artifact's contents to the given output function
   and calculates any cards which cannot be calculated until the
   contents are complete (namely the R-card and Z-card).

   If both (output, outputState) are NULL then d->f's outputer is
   used.

   The given deck is "logically const" but traversal over F-cards and
   baselines requires non-const operations. To keep this routine from
   requiring an undue amount of pre-call effort on the client's part,
   it also takes care of calling fsl_deck_unshuffle() to ensure that
   all of the deck's cards are in order. (If the deck has no R card,
   but has F-cards, and d->f is configured to generate R-cards, then
   unshuffling will also calculate the R-card.)

   Returns 0 on success, FSL_RC_MISUSE if !d or !d->f or !out. If
   out() returns non-0, output stops and that code is
   returned. outputState is passed as the first argument to out() and
   out() may be called an arbitrary number of times by this routine.

   Returns FSL_RC_SYNTAX if fsl_deck_has_required_cards()
   returns false.

   On errors more serious than argument validation, the deck's
   context's (d->f) error state is updated.

   The exact structure of the ouput depends on the value of
   d->type, and FSL_RC_TYPE is returned if this function cannot
   figure out what to do with the given deck's type.

   @see fsl_deck_unshuffle()
   @see fsl_deck_save()
*/
FSL_EXPORT int fsl_deck_output(fsl_deck * d, fsl_output_f out,
                               void * outputState);

/**
   Emits a JSON representation of the given deck to the given output
   routine. Returns 0 on success, non-0 on error. Any error codes,
   aside from FSL_RC_OOM, will have come from the given callback.

   The output is intended to be compatible with fossil(1)'
   artifact_to_json() (any deviation is a bug). The output is compact,
   not nicely-formatted. It can be sent to sqlite's json_pretty() to
   format it.

   If d->rid<=0, e.g. because it was just processed by
   fsl_deck_parse(), the resulting JSON object will have a "uuid" of
   null. If that property is important, it is up to the caller to set
   it before calling this.
*/
FSL_EXPORT int fsl_deck_to_json(fsl_deck const * d, fsl_output_f fn, void * fState);

/**
   Saves the given deck into f's repository database as new control
   artifact content. If isPrivate is true then the content is
   marked as private, otherwise it is not. Note that isPrivate is a
   suggestion and might be trumped by existing state within f or
   its repository, and such a trumping is not treated as an
   error. e.g. tags are automatically private when they tag private
   content. The deck is saved as private if its first P-card refers
   to private content, and otherwise later P-cards which refer to
   private content are removed from d, as fossil(1) and fsl_checkin_commit()
   do for a checkin's parents: a public child would
   sync and leave other repositories with a phantom for the parent.

   Before saving, the deck is passed through fsl_deck_unshuffle()
   and fsl_deck_output(), which will fail for a variety of
   easy-to-make errors such as the deck missing required cards.
   For unshuffle purposes, the R-card gets calculated if the deck
   has any F-cards AND if the caller has not already set/calculated
   it AND if f's FSL_CX_F_CALC_R_CARD flag is set (it is on by
   default for historical reasons, but this may change at some
   point). If that flag is set and the caller has set the R-card of a
   checkin deck, this calculates the R-card and fails with
   FSL_RC_CONSISTENCY if it differs from the one set.

   Before storing it, this parses the output with fsl_deck_parse(),
   as fossil(1) parses an artifact before crosslinking it, and fails
   with the parser's result code and message if it does not parse.
   It fails with FSL_RC_SYNTAX if the text parses as a different
   artifact type than d->type, and with FSL_RC_RANGE if an F-card has
   a reserved name (see fsl_is_reserved_fn()), which the parser
   drops.

   Returns 0 on success, the usual non-0 suspects on error.

   - If d->rid is positive, it is assumed to refer to a valid
   `blob.rid` and this function returns 0 without side-effects. It
   does _not_ attempt to re-save such a record, as that could very
   possible result in a new hash (and would definitely do so if the
   deck's state had been modified in the slightest bit (literally
   "bit")). It should arguably return FSL_RC_ALREADY_EXISTS for this
   case, but does not do so for historical reasons.

   - PREVIOUSLY (prior to 2021-10-20), we assumed such a deck referred
   to a phantom which we would then save, but that behaviour seems to
   be misguided, as we only ever want to save newly-created decks, not
   decks created from existing content.

   On success, d->rid be set to the new record's RID. It will only be
   set on success because it would otherwise refer to a db record
   which get destroyed when the transaction rolls back.

   After saving, the deck will be cross-linked to update any
   relationships described by the deck.

   The save operation happens within a transaction, of course, and
   on any sort of error, db-side changes are rolled back. Note that
   it _is_ legal to start the transaction before calling this,
   which effectively makes this operation part of that transaction.

   This function will fail with FSL_RC_ACCESS if d is a delta manifest
   (has a B-card) and d->f's forbid-delta-manifests configuration
   option is set to a truthy value. See
   fsl_repo_forbids_delta_manifests().

   Maintenance reminder: this function also does a very small bit of
   artifact-type-specific processing.

   @see fsl_deck_output()
*/
FSL_EXPORT int fsl_deck_save( fsl_deck * d, bool isPrivate );

/**
   Parses src as Control Artifact content and populates d with it.

   d will be cleaned up before parsing if it has any contents,
   retaining its d->f member (which must be set to non-NULL by the
   caller for error-reporting purposes).

   This function _might_ take over the contents of the source
   buffer. If it does, after returning src->mem will be NULL, and all
   other members will be reset to their default state. This function
   only takes over the contents if it decides to implement certain
   memory optimizations. It may fsl_b_reuse() the source buffer
   regardless of how it returns.

   Ownership of src itself is never changed by this function, only the
   ownership of its contents. On success, this function always either
   fsl_b_reuse()s the buffer or takes over ownership of that
   memory and clears src. (Prior to 2026-07-28 it guaranteed to free
   the buffer's memory if it did not take it over. That was a design
   flaw, the correction of which is currently known to only have
   broken a single test app but which _might_ affect other clients.

   In any case, the content of the source buffer is (normally)
   modified by this function because (A) that simplifies tokenization
   greatly, (B) saves us having to make another copy to work on, (C)
   the original implementation did it that way, (D) because in
   historical use the source is normally thrown away after parsing,
   anyway, and (E) in combination with taking ownership of src's
   contents it allows us to optimize away some memory allocations by
   re-using the internal memory of the buffer. This function never
   changes src's size, but it mutilates its contents (injecting NUL
   bytes as token delimiters).

   If d->type is _not_ FSL_SATYPE_ANY when this is called, then
   this function requires that the input to be of that type. We can
   fail relatively quickly in that case, and this can be used to
   save some downstream code some work. Note that the initial type
   for decks created using fsl_deck_malloc() or copy-initialized
   from ::fsl_deck_empty is FSL_SATYPE_ANY, so normally clients do
   not need to set this (unless they want to, as a small
   optimization).

   On success it returns 0 and d will be updated with the state from
   the input artifact and the contents of the source buffer will
   either be cleared or taken over by d. (Ideally, outputing d via
   fsl_deck_output() will produce a lossless copy of the original, but
   timestamp granularity might prevent that.)

   On error, if there is error information to propagate beyond the
   result code then it is stored in d->f. Whether or not such error
   info is propagated depends on the type of error, but anything more
   trivial than invalid arguments will be noted there. On error, the
   source buffer's contents _might_, depending on which phase the
   error happened, be left in place but may have been modified by the
   parsing process.  If the error happens after _certain_ parsing
   steps then the deck will be required to take over the buffer's
   memory in order to keep memory management sane. On error, clients
   should always eventually pass the source buffer to
   fsl_b_clear(). On success its contents are guaranteed to have
   been cleared or or transfered to the destination deck when this
   function returns.

   d might be partially populated on error, so regardless of success
   or failure, the client must eventually pass d to
   fsl_deck_finalize() to free its memory.

   Error result codes include:

   - FSL_RC_SYNTAX on syntax errors, including an empty source
     buffer. Fossil's tried-and-true approach
     to determine "is this an artifact?" is "can it pass through
     fsl_deck_parse()?" This result code simply means that the input
     is, strictly speaking, not a fossil artifact. In some contexts
     this condition must be caught and treated as not-an-error (but
     also not an artifact). The error message names the offending
     card and its line number, in the form "line N: ...", prefixed
     with "artifact [HASH]" if fsl_deck_parse2() was given the
     artifact's rid.

   - FSL_RC_MISUSE if any pointer argument is NULL or d->f is NULL.

   - FSL_RC_CONSISTENCY if validation of a Z-card fails. This is a
     more specialized form of FSL_RC_SYNTAX but indicates that the
     artifact is (or may be) well-formed but has an incorrect hash.
     This check happens relatively early in the parsing process, but
     after this function has uses fsl_might_be_artifact() to do a
     basic sniff-test. In practice, this error "cannot happen" unless
     the source buffer has been manually manipulated. Whether or not
     client-side code wants to treat this as FSL_RC_SYNTAX (i.e. "not
     an artifact but not an error") is up to the client

   - Any number of errors coming from the allocator, database, or
     fsl_deck APIs used here.

   ACHTUNG API CHANGE: prior to 2021-10-20, this routine set d->rid
   (and the now-removed d->uuid) based on the hash of the input buffer
   if a matching record could be found in the db. That proved to be
   a huge performance hit and was removed.

   Maintenance reminder: in keeping with fossil's "if it quacks like
   an artifact, it is an artifact, else it's not" approach to
   determining whether opaque blobs are artifacts, this function
   _must_ continue to return FSL_RC_SYNTAX to indicate that "it
   doesn't quack like an artifact but there's otherwise nothing
   wrong," which downstream code must be able to rely upon as the
   input being a non-artifact. More serious errors, e.g. FSL_RC_OOM,
   are (of course) to be propagated back.

   @see fsl_deck_parse2()
*/
FSL_EXPORT int fsl_deck_parse(fsl_deck * d, fsl_b * src);

/**
    This variant of fsl_deck_parse() works identically to that
    function except for the 3rd argument.

    If you happen to know the _correct_ RID for the deck being parsed,
    pass it as the rid argument, else pass 0. A negative value will
    result in a FSL_RC_RANGE error. This value is (or may be) only
    used as an optimization in this function and/or downstream
    functions. Passing a positive value will cause d->f to do a cache
    lookup which may avoid it having to parse the deck at all.
*/
FSL_EXPORT int fsl_deck_parse2(fsl_deck * d, fsl_b * src, fsl_id_t rid);

/**
   If *pz points to *pn bytes beginning with a PGP or SSH clearsign
   envelope, as fossil(1) writes when its clearsign setting is on,
   this advances *pz past the envelope's header and blank line, sets
   *pn to the length of the enveloped text up to and including the
   newline before the signature block, and returns true. The result
   is the artifact text as it was before signing. If *pz does not
   begin with such an envelope, neither pointer is changed and false
   is returned. Neither pointer may be NULL.

   The artifact parsers call this before parsing, so a signed artifact
   parses like an unsigned one and its hash is that of the signed
   text. This is public so that clients which verify signatures can
   separate the envelope from the text.

   @see fsl_cx_signer()
*/
FSL_EXPORT bool fsl_signature_strip(char const **pz, fsl_size_t *pn);

/**
   Callback type for signing artifacts. fsl_deck_save() calls it with
   the complete artifact text, Z-card included, after that text is
   generated and before it is hashed and stored, as fossil(1)'s
   clearsign() is called. d is the deck being saved and state is the
   fsl_signer::state it was installed with.

   The callback may leave manifest as it is, to decline (e.g. for
   artifact types it does not sign), or replace its contents with the
   same text inside a PGP or SSH clearsign envelope, one which
   fsl_signature_strip() turns back into the text it was given.
   fsl_deck_save() checks that and fails with FSL_RC_CONSISTENCY if
   the result does not strip back to the original text. The artifact's
   hash is then that of the signed text, as in fossil(1).

   It must return 0 on success, including when it declines, or a
   non-0 fsl_rc_e code to fail the save.

   It is never called for private artifacts, which fossil(1) does not
   sign either.
*/
typedef int (*fsl_deck_sign_f)(fsl_deck const * d, fsl_b * manifest,
                               void * state);

/**
   Holds a signing callback and its state. See fsl_cx_signer().
*/
struct fsl_signer {
  /** The callback, or NULL for no signing. */
  fsl_deck_sign_f callback;
  /** Opaque state passed to the callback. */
  void * state;
};
typedef struct fsl_signer fsl_signer;
/** Initialized-with-defaults fsl_signer instance, intended for
    const-copy initialization. */
#define fsl_signer_empty_m {NULL, NULL}
/** Initialized-with-defaults fsl_signer instance, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_signer fsl_signer_empty;

/**
   Installs a bitwise copy of *newSigner as f's artifact signer, which
   fsl_deck_save() calls as described for fsl_deck_sign_f. If
   newSigner is NULL, f's signer is cleared and artifacts are saved
   unsigned. If prevSigner is not NULL, the previous signer is copied
   to it first, so that a caller can restore it later.

   libfossil never signs on its own: the library has no opinion on
   gpg, ssh-keygen or keys, so an application which wants fossil(1)'s
   clearsign behavior installs a callback which runs its pgp-command
   equivalent.

   @see fsl_cx_signer_get()
   @see fsl_signature_strip()
*/
FSL_EXPORT void fsl_cx_signer(fsl_cx * const f, fsl_signer const * newSigner,
                              fsl_signer * prevSigner);

/**
   Stores a bitwise copy of f's current signer into *dest.

   @see fsl_cx_signer()
*/
FSL_EXPORT void fsl_cx_signer_get(fsl_cx const * const f, fsl_signer * dest);

/**
   Quickly determines whether the content held by the given buffer
   "might" be a structural artifact. It performs a fast sanity check
   for prominent features which can be checked either in O(1) or very
   short O(N) time (with a fixed N). If it returns false then the
   given buffer's contents are, with 100% certainty, _not_ a
   structural artifact. If it returns true then they _might_ be, but
   being 100% certain requires passing the contents to
   fsl_deck_parse() to fully parse them.
*/
FSL_EXPORT bool fsl_might_be_artifact(fsl_b const * src);

/**
   Loads the content from given rid and tries to parse it as a
   Fossil artifact. If rid==0 the current checkout (if opened) is
   used. (Trivia: there can never be a checkout with rid==0 but
   rid==0 is sometimes valid for an new/empty repo devoid of
   commits.) If type==FSL_SATYPE_ANY then it will allow any type of
   control artifact, else it returns FSL_RC_TYPE if the loaded
   artifact is of the wrong type.

   Returns 0 on success. Results are undefined if f or d are NULL. The
   potential error result codes include, but are not limited to:

   - FSL_RC_OOM

   - FSL_RC_RANGE if rid is negative or is 0 and no checkout is
     opened.

   - FSL_RC_TYPE if `type` is not `FSL_SATYPE_ANY` and the loaded
     result is of any artifact type other than `type`.

   - Any code from fsl_deck_parse(), whose error message is then
     prefixed with "artifact [HASH]".

   d must be properly initialized, either copy-initialized from
   fsl_deck_empty or populated by the library's API. This function
   will (re)initialize it and may leave it partially populated on
   error. The caller must eventually pass it to fsl_deck_finalize()
   resp. fsl_deck_clean() regardless of success or error. This
   function "could" clean it up on error, but leaving it partially
   populated makes debugging easier.

   f's error state may be updated on error (for anything more
   serious than basic argument validation errors).

   On success this function sets d->rid to rid.

   @see fsl_deck_load_sym()
*/
FSL_EXPORT int fsl_deck_load_rid( fsl_cx * f, fsl_deck * d,
                                  fsl_id_t rid, fsl_satype_e type );

/**
   A convenience form of fsl_deck_load_rid() which uses
   fsl_sym_to_rid() to convert symbolicName into an artifact RID.  See
   fsl_deck_load_rid() for the symantics of the first, second, and
   fourth arguments, as well as the return value. See fsl_sym_to_rid()
   for the allowable values of symbolicName.

   @see fsl_deck_load_rid()
*/
FSL_EXPORT int fsl_deck_load_sym( fsl_cx * f, fsl_deck * d,
                                  char const * symbolicName,
                                  fsl_satype_e type );

/**
   Loads the baseline manifest specified in d->B.uuid, if any and if
   necessary. Returns 0 on success. If d->B.baseline is already loaded
   or d->B.uuid is NULL (in which case there is no baseline), it
   returns 0 and has no side effects.

   Neither argument may be NULL and d must be a fully-populated
   object, complete with a proper d->rid, before calling this.

   On success 0 is returned. If d->B.baseline is NULL then
   it means that d has no baseline manifest (and d->B.uuid will be NULL
   in that case). If d->B.baseline is not NULL then it is owned by
   d and will be cleaned up when d is cleaned/finalized.

   Error codes include, but are not limited to:

   - FSL_RC_MISUSE if !d->f.

   - FSL_RC_NOT_A_REPO if d->f has no opened repo db.

   - FSL_RC_PHANTOM if the baseline is not yet in the repository
   (it is recorded as a phantom, and d is recorded as its orphan if
   d->rid>0).

   - FSL_RC_SHUNNED if the baseline is shunned.

   On non-trivial errors d->f's error state will be updated to hold
   a description of the problem.

   Some misuses trigger assertions in debug builds.
*/
FSL_EXPORT int fsl_deck_baseline_fetch( fsl_deck * d );

/**
   A callback interface for manifest crosslinking, so that we can farm
   out the updating of the event table (and similar bookkeeping) as
   manifests are crosslinked. Each callback registered via
   fsl_xlink_listener() will be called at the end of the so-called
   crosslinking process, which is run every time an artifact is
   processed for d->f's repository database, passed the deck being
   crosslinked and the client-provided state which was registered with
   fsl_xlink_listener(). Note that the deck object itself holds other
   state useful for crosslinking, like the blob.rid value of the deck
   and its fsl_cx instance.

   If an implementation is only interested in a specific type of
   artifact, it must check d->type and return 0 if it's an
   "uninteresting" type.

   Implementations must return 0 on success or some other fsl_rc_e
   value on error. Returning non-0 causes the database transaction
   for the crosslinking operation to roll back, effectively
   cancelling whatever pending operation triggered the
   crosslink. If any callback fails, processing stops immediately -
   no other callbacks are executed.

   Implementations which want to report more info than an integer
   should call fsl_cx_err_set() to set d->f's error state, as that
   will be propagated up to the code which initiated the failed
   crosslink.

   ACHTUNG and WARNING: the fsl_deck parameter "really should" be
   const, but certain operations on a deck are necessarily non-const
   operations. That includes, but may not be limited to:

   - Iterating over F-cards, which requires calling
     fsl_deck_F_rewind() before doing so. Traversal of F-cards
     internally uses a necessarily-mutable cursor.

   - Loading a checkin's baseline (required for F-card iteration and
     performed automatically by fsl_deck_F_rewind()).

   Aside from such iteration-related mutable state, it is STRICTLY
   ILLEGAL to modify a deck's artifact-related state while it is
   undergoing crosslinking. Violating that will lead to undefined
   results.

   Potential TODO: add some client-opaque state to decks so that they
   can be flagged as "being crosslinked" and fail mutation operations
   such as card adders/setters.

   @see fsl_xlink_listener()
*/
typedef int (*fsl_deck_xlink_f)(fsl_deck * d, void * state);

/**
    A type for holding state for artifact crosslinking callbacks.
*/
struct fsl_xlinker {
  /** Human-readable name of the crosslinker, noting that each
      registered crosslinker must have a unique name. Registering a
      crosslinker with the same name as an existing one replaces that
      one.
  */
  char const * name;
  /** Callback function. */
  fsl_deck_xlink_f f;
  /** State for this->f's last argument. */
  void * state;
};
typedef struct fsl_xlinker fsl_xlinker;

/** Empty-initialized fsl_xlinker struct, intended for const-copy
    intialization. */
#define fsl_xlinker_empty_m {NULL,NULL,NULL}

/** Empty-initialized fsl_xlinker struct, intended for copy intialization. */
extern const fsl_xlinker fsl_xlinker_empty;

/**
    A list of fsl_xlinker instances.
*/
struct fsl_xlinker_list {
  /** Number of used items in this->list. */
  fsl_size_t used;
  /** Number of slots allocated in this->list. */
  fsl_size_t capacity;
  /** Array of this->used elements. */
  fsl_xlinker * list;
};
typedef struct fsl_xlinker_list fsl_xlinker_list;

/** Empty-initializes fsl_xlinker_list struct, intended for
    const-copy intialization. */
#define fsl_xlinker_list_empty_m {0,0,NULL}

/** Empty-initializes fsl_xlinker_list struct, intended for copy intialization. */
extern const fsl_xlinker_list fsl_xlinker_list_empty;

/**
    Searches f's crosslink callbacks for an entry with the given
    name and returns that entry, or NULL if no match is found.  The
    returned object is owned by f.
*/
fsl_xlinker * fsl_xlinker_by_name( fsl_cx * f, char const * name );

/**
   Adds the given function as a "crosslink callback" for the given
   Fossil context. The callback is called at the end of a successful
   "artifact crosslink" operation and provides a way for the client to
   perform their own work based on the app having crosslinked an
   artifact. Crosslinking happens when artifacts are saved or upon a
   rebuild operation.

   This function returns 0 on success, non-0 on error. Behaviour is
   undefined if any of the first 3 arguments are NULL.

   Crosslink callbacks are called at the end of the core crosslink
   steps, in the order they are registered, with the caveat that if a
   listener is overwritten by another with the same name, the new
   entry retains the older one's position in the list. The library may
   register its own before the client gets a chance to.

   If _any_ crosslinking callback fails (returns non-0) then the
   _whole_ crosslinking fails and is rolled back (which may very
   well include pending tags/commits/whatever getting rolled back).

   The state parameter has no meaning for this function, but is
   passed on as the final argument to cb(). If not NULL, cbState
   "may" be required to outlive f, depending on cbState's exact
   client-side internal semantics/use, as there is currently no API
   to remove registered crosslink listeners.

   The name must be non-NULL/empty. If a listener is registered with a
   duplicate name then the first one is replaced. This function does
   not copy the name bytes - they are assumed to be static or
   otherwise to live at least as long as f. The name may be
   arbitrarily long, but must have a terminating NUL byte. It is
   recommended that clients choose a namespace/prefix to apply to the
   names they register. The library reserves the prefix "fsl/" for
   its own use, and will happily overwrite client-registered entries
   with the same names. The name string need not be stable across
   application sessions and maybe be a randomly-generated string.

   Caveat: some obscure artifact crosslinking steps do not happen
   unless crosslinking takes place in the context of a
   fsl__crosslink_begin() and fsl__crosslink_end()
   session. Thus, at the time client-side crosslinker callbacks are
   called, certain crosslinking state in the database may still be
   pending. It is as yet unclear how best to resolve that minor
   discrepancy, or whether it even needs resolving.

   As a rule, it is important that crosslink handler checks the
   deck->type field of the deck they are passed, and return 0, without
   side effects, if the type is not specifically handled by that
   handler. Every crosslink handler is passed every crosslinked
   artifact, but it's rare for crosslink handlers to handle more than
   one type of artifact, except perhaps for purposes of notifying a
   user that some progress is being made.

   Default (overrideable) crosslink handlers:

   The library internally splits crosslinking of artifacts into two
   parts: the main one (which clients cannot modify) handles the
   database-level linking of relational state implied by a given
   artifact. The secondary one adds an entry to the "event" table,
   which is where Fossil's timeline lives. The crosslinkers for the
   timeline updates may be overridden by clients by registering
   a crosslink listener with the following names:

   - Attachment artifacts: "fsl/attachment/timeline"

   - Checkin artifacts: "fsl/checkin/timeline"

   - Control artifacts: "fsl/control/timeline"

   - Forum post artifacts: "fsl/forumpost/timeline"

   - Technote artifacts: "fsl/technote/timeline"

   - Wiki artifacts: "fsl/wiki/timeline"

   A context registers listeners under those names when it
   initializes, and clients may override them at any point after that.

   Sidebar: due to how tickets are crosslinked (_after_ the general
   crosslinking phase is actually finished and requiring state which
   other crosslinkers do not), it is not currently possible to
   override the ticket crosslink handler. Thus the core ticket
   crosslinker will always run, and update the [event] table, but a
   custom crosslinker may overwrite the resulting [event] table
   entries (in particular, the comment). Determining whether/how
   ticket crosslinking can be restructured to be consistent with the
   other types is on the TODO list.

   Caveat: updating the timeline requires a bit of knowledge about the
   Fossil DB schema and/or conventions. Updates for certain types,
   e.g. attachment/control/forum post, is somewhat more involved and
   updating the timeline for wiki comments requires observing a "quirk
   of conventions" for labeling such comments, such that they will
   appear properly when the main fossil app renders them. That said,
   the only tricky parts of those updates involve generating the
   "correct" comment text. So long as the non-comment parts are
   updated properly (that part is easy to do), fossil can function
   with it.  The timeline comment text/links are soley for human
   consumption. Fossil makes much use of the "event" table internally,
   however, so the rest of that table must be properly populated.

   Because of that caveat, clients may, rather than overriding the
   defaults, install their own crosslink listners which ammend the
   state applied by the default ones. e.g. add a listener which
   watches for checkin updates and replace the default-installed
   comment with one suitable for your application, leaving the rest of
   the db state in place. At its simplest, that looks more or less
   like the following code (inside a fsl_deck_xlink_f() callback):

   ```
   int rc = fsl_db_exec(fsl_cx_db_repo(deck->f),
                        "UPDATE event SET comment=%Q "
                        "WHERE objid=%"FSL_ID_T_PFMT,
                        "the new comment.", deck->rid);
   ```
*/
FSL_EXPORT int fsl_xlink_listener( fsl_cx * f, char const * name,
                                   fsl_deck_xlink_f cb, void * cbState );


/**
   For the given blob.rid value, returns the blob.size value of
   that record via *rv. Returns 0 or higher on success, -1 if a
   phantom record is found, -2 if no entry is found, or a smaller
   negative value on error (dig around the sources to decode them -
   this is not expected to fail unless the system is undergoing a
   catastrophe).

   @see fsl_content_raw()
   @see fsl_content_get()
   @see fsl_content_size_v2()
*/
FSL_EXPORT fsl_int_t fsl_content_size( fsl_cx * f, fsl_id_t blobRid );

/**
   Given a blob RID, this function extracts its size from the
   `blob.rid` db field. On success, returns 0 and sets *pOut to
   the new size. Negative sizes mean the blob is a "phantom."

   On error it returns non-0 and updates f's error state.

   @see fsl_content_size()
*/
FSL_EXPORT int fsl_content_size_v2(fsl_cx * f, fsl_id_t rid,
                                   fsl_int_t *pOut);

/**
   For the given blob.rid value, fetches the content field of that
   record and overwrites tgt's contents with it (reusing tgt's
   memory if it has any and if it can). The blob's contents are
   uncompressed if they were stored in compressed form. This
   extracts a raw blob and does not apply any deltas - use
   fsl_content_get() to fully expand a delta-stored blob.

   By and large, client-side code will want fsl_content_get() over
   this functino.

   Returns 0 on success. On error tgt might be partially updated,
   e.g. it might be populated with compressed data instead of
   uncompressed. On error tgt's contents should be recycled
   (e.g. fsl_b_reuse()) or discarded (e.g. fsl_b_clear()) by
   the client. Returns FSL_RC_RANGE if blobRid<=0, FSL_RC_NOT_A_REPO
   if f has no repo opened, FSL_RC_OOM on allocation error, or
   potentially any number of other codes via the db layer.

   Results are undefined if any pointer argument is NULL.

   @see fsl_content_get()
   @see fsl_content_size()
*/
FSL_EXPORT int fsl_content_raw( fsl_cx * f, fsl_id_t blobRid,
                                 fsl_b * tgt );

/** @deprecated

    Older (deprecated) name of fsl_content_raw().
*/
#define fsl_content_blob fsl_content_raw

/**
   Functionally similar to fsl_content_raw() but does a lot of
   work to ensure that the returned blob is expanded from its
   deltas, if any. The tgt buffer's memory, if any, will be
   replaced/reused if it has any.

   Returns 0 on success. There are no less than 50 potental
   different errors, so we won't bother to list them all. On error
   tgt might be partially populated. The basic error cases are:

   - FSL_RC_MISUSE if !tgt or !f.

   - FSL_RC_RANGE if rid<=0 or if an infinite loop is discovered in
   the repo delta table links (that is a consistency check to avoid
   an infinite loop - that condition "cannot happen" because the
   verify-before-commit logic catches that error case).

   - FSL_RC_NOT_A_REPO if f has no repo db opened.

   - FSL_RC_NOT_FOUND if the given rid is not in the repo db.

   - FSL_RC_OOM if an allocation fails.


   @see fsl_content_raw()
   @see fsl_content_size()
*/
FSL_EXPORT int fsl_content_get( fsl_cx * f, fsl_id_t blobRid,
                                fsl_b * 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_b * 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);

/**
   Marks the given rid public, if it was previously marked as
   private, and adds it to the unsent and unclustered tables so that
   the next sync offers it to peers. It is a no-op if rid is not
   private. Returns 0 on success, non-0 on error.

   This affects only the given rid. Unlike fossil(1)'s publish
   command, it does not also publish the files and tags of a
   check-in.

   Note that it is not possible to make public content private.
*/
FSL_EXPORT int fsl_content_make_public(fsl_cx * f, fsl_id_t rid);

/**
   Generic callback interface for visiting decks. The interface
   does not generically require that d survive after this call
   returns.

   Implementations must return 0 on success, non-0 on error. Some
   APIs using this interface may specify that FSL_RC_BREAK can be
   used to stop iteration over a loop without signaling an error.
   In such cases the APIs will translate FSL_RC_BREAK to 0 for
   result purposes, but will stop looping over whatever it is they
   are looping over.

   Note that the passed-in deck "should" be const but is not because
   iterating over a deck's F-cards requires non-const state.
*/
typedef int (*fsl_deck_visitor_f)( fsl_cx * f, fsl_deck * d,
                                   void * state );

/**
   For each unique wiki page name in f's repostory, this calls
   cb(), passing it the manifest of the most recent version of that
   page. The callback should return 0 on success, FSL_RC_BREAK to
   stop looping without an error, or any other non-0 code
   (preferably a value from fsl_rc_e) on error.

   The 3rd parameter has no meaning for this function but it is
   passed on as-is to the callback.

   ACHTUNG: the deck passed to the callback is transient and will
   be cleaned up after the callback has returned, so the callback
   must not hold a pointer to it or its contents.

   @see fsl_wiki_load_latest()
   @see fsl_wiki_latest_rid()
   @see fsl_wiki_names_get()
   @see fsl_wiki_page_exists()
*/
FSL_EXPORT int fsl_wiki_foreach_page( fsl_cx * f, fsl_deck_visitor_f cb, void * state );

/**
   Fetches the most recent RID for the given wiki page name and
   assigns *newId (if it is not NULL) to that value. Returns 0 on
   success, FSL_RC_MISUSE if !f or !pageName, FSL_RC_RANGE if
   !*pageName, and a host of other potential db-side errors
   indicating more serious problems. If no such page is found,
   newRid is not modified and this function returns 0 (as opposed
   to FSL_RC_NOT_FOUND) because that simplifies usage (so far).

   On error *newRid is not modified.

   @see fsl_wiki_load_latest()
   @see fsl_wiki_foreach_page()
   @see fsl_wiki_names_get()
   @see fsl_wiki_page_exists()
*/
FSL_EXPORT int fsl_wiki_latest_rid( fsl_cx * f, char const * pageName, fsl_id_t * newRid );

/**
   Loads the artifact for the most recent version of the given wiki page,
   populating d with its contents.

   Returns 0 on success. On error d might be partially populated,
   so it needs to be passed to fsl_deck_finalize() regardless of
   whether this function succeeds or fails.

   Returns FSL_RC_NOT_FOUND if no page with that name is found, and
   f's error message then contains the page name. Returns
   FSL_RC_MISUSE if any argument is NULL and FSL_RC_RANGE if
   !*pageName.

   @see fsl_wiki_latest_rid()
   @see fsl_wiki_names_get()
   @see fsl_wiki_page_exists()
*/
FSL_EXPORT int fsl_wiki_load_latest( fsl_cx * f, char const * pageName, fsl_deck * d );

/**
   Returns true (non-0) if f's repo database contains a page with the
   given name, else false.

   @see fsl_wiki_load_latest()
   @see fsl_wiki_latest_rid()
   @see fsl_wiki_names_get()
   @see fsl_wiki_names_get()
*/
FSL_EXPORT bool fsl_wiki_page_exists(fsl_cx * f, char const * pageName);

/**
   A helper type for use with fsl_wiki_save(), intended primarily
   to help client-side code readability somewhat.
*/
enum fsl_wiki_save_mode_t {
/**
   Indicates that fsl_wiki_save() must only allow the creation of
   a new page, and must fail if such an entry already exists.
*/
FSL_WIKI_SAVE_MODE_CREATE = -1,
/**
   Indicates that fsl_wiki_save() must only allow the update of an
   existing page, and will not create a brand new page.
*/
FSL_WIKI_SAVE_MODE_UPDATE = 0,
/**
   Indicates that fsl_wiki_save() must allow both the update and
   creation of pages. Trivia: "upsert" is a common SQL slang
   abbreviation for "update or insert."
*/
FSL_WIKI_SAVE_MODE_UPSERT = 1
};

typedef enum fsl_wiki_save_mode_t fsl_wiki_save_mode_t;

/**
   Saves wiki content to f's repository db.

   pageName is the name of the page to update or create.

   b contains the content for the page.

   userName specifies the user name to apply to the change. If NULL
   or empty then fsl_cx_user_get() or fsl_user_name_guess() are
   used (in that order) to determine the name.

   mimeType specifies the mime type for the content (may be NULL).
   Mime type names supported directly by fossil(1) include (as of
   this writing): text/x-fossil-wiki, text/x-markdown,
   text/plain

   Whether or not this function is allowed to create a new page is
   determined by creationPolicy. If it is
   FSL_WIKI_SAVE_MODE_UPDATE, this function will fail with
   FSL_RC_NOT_FOUND if no page with the given name already exists.
   If it is FSL_WIKI_SAVE_MODE_CREATE and a previous version _does_
   exist, it fails with FSL_RC_ALREADY_EXISTS. If it is
   FSL_WIKI_SAVE_MODE_UPSERT then both the save-exiting and
   create-new cases are allowed. In summary:

   - use FSL_WIKI_SAVE_MODE_UPDATE to allow updates to existing pages
   but disallow creation of new pages,

   - use FSL_WIKI_SAVE_MODE_CREATE to allow creating of new pages
   but not of updating an existing page.

   - FSL_WIKI_SAVE_MODE_UPSERT allows both updating and creating
   a new page on demand.

   Returns 0 on success, or any number fsl_rc_e codes on error. On
   error no content changes are saved, and any transaction is
   rolled back or a rollback is scheduled if this function is
   called while a transaction is active.


   Potential TODO: add an optional (fsl_id_t*) output parameter
   which gets set to the new record's RID.

   @see fsl_wiki_page_exists()
   @see fsl_wiki_names_get()
*/
FSL_EXPORT int fsl_wiki_save(fsl_cx * f, char const * pageName,
                  fsl_b const * b, char const * userName,
                  char const * mimeType, fsl_wiki_save_mode_t creationPolicy );

/**
   Fetches the list of all wiki page names in f's current repo db
   and appends them as new (char *) strings to tgt. On error tgt
   might be partially populated (but this will only happen on an
   OOM or serious system-level error).

   It is up to the caller free the entries added to the list. Some
   of the possibilities include:

   ```
   fsl_list_visit( list, 0, fsl_list_v_fsl_free, NULL );
   fsl_list_reserve(list,0);
   // Or:
   fsl_list_clear(list, fsl_list_v_fsl_free, NULL);
   // Or simply:
   fsl_list_visit_free( list, 1 );
   ```

*/
FSL_EXPORT int fsl_wiki_names_get( fsl_cx * f, fsl_list * tgt );

/**
   F-cards each represent one file entry in a Manifest Artifact (i.e.,
   a checkin version).

   All of the non-const pointers in this class are owned by the
   respective instance of the class OR by the fsl_deck which created
   it, and must neither be modified nor freed except via the
   appropriate APIs.
*/
struct fsl_card_F {
  /**
     UUID of the underlying blob record for the file. NULL for
     removed entries.
  */
  fsl_uuid_str uuid;
  /**
     Name of the file.
  */
  char * name;
  /**
     Previous name if the file was renamed, else NULL.
  */
  char * priorName;
  /**
     File permissions. Fossil only supports one "permission" per
     file, and it does not necessarily map to a real
     filesystem-level permission.

     @see fsl_fileperm_e
  */
  fsl_fileperm_e perm;

  /**
     An internal optimization. Do not mess with this.  When this is
     true, the various string members of this struct are not owned
     by this struct, but by the deck which created this struct. This
     is used when loading decks from storage - the strings are
     pointed to the original content data, rather than strdup()'d
     copies of it. fsl_card_F_clean() will DTRT and delete the
     strings (or not).
  */
  bool deckOwnsStrings;
};
/**
   Empty-initialized fsl_card_F structure, intended for use in
   initialization when embedding fsl_card_F in another struct or
   copy-initializing a const struct.
*/
#define fsl_card_F_empty_m {   \
  NULL/*uuid*/,                \
  NULL/*name*/,                \
  NULL/*priorName*/,           \
  0/*perm*/,                   \
  false/*deckOwnsStrings*/     \
}
FSL_EXPORT const fsl_card_F fsl_card_F_empty;

/**
   Represents a J card in a Ticket Control Artifact.
*/
struct fsl_card_J {
  /**
     If true, the new value should be appended to any existing one
     with the same key, else it will replace any old one.
  */
  bool append;
  /**
     For internal use only.
  */
  unsigned char flags;
  /**
     The ticket field to update. The bytes are owned by this object.
  */
  char * field;
  /**
     The value for the field. The bytes are owned by this object.
  */
  char * value;
};
/** Empty-initialized fsl_card_J struct. */
#define fsl_card_J_empty_m {false,0,NULL, NULL}
/** Empty-initialized fsl_card_J struct. */
FSL_EXPORT const fsl_card_J fsl_card_J_empty;

/**
   Represents a tag in a Manifest or Control Artifact.
*/
struct fsl_card_T {
  /**
     The type of tag.
  */
  fsl_tagtype_e type;
  /**
     UUID of the artifact this tag is tagging. When applying a tag to
     a new checkin, this value is left empty (=NULL) and gets replaced
     by a '*' in the resulting control artifact.
  */
  fsl_uuid_str uuid;
  /**
     The tag's name. The bytes are owned by this object.
  */
  char * name;
  /**
     The tag's value. May be NULL/empty. The bytes are owned by
     this object.
  */
  char * value;
};
/** Defaults-initialized fsl_card_T instance. */
#define fsl_card_T_empty_m {FSL_TAGTYPE_INVALID, NULL, NULL,NULL}
/** Defaults-initialized fsl_card_T instance. */
FSL_EXPORT const fsl_card_T fsl_card_T_empty;

/**
   Types of cherrypick merges.
*/
enum fsl_cherrypick_type_e {
/** Sentinel value. */
FSL_CHERRYPICK_INVALID = 0,
/** Indicates a cherrypick merge. */
FSL_CHERRYPICK_ADD = 1,
/** Indicates a cherrypick backout. */
FSL_CHERRYPICK_BACKOUT = -1
};
typedef enum fsl_cherrypick_type_e fsl_cherrypick_type_e;

/**
   Represents a Q card in a Manifest or Control Artifact.
*/
struct fsl_card_Q {
  /** 0==invalid, negative==backed out, positive=cherrypicked. */
  fsl_cherrypick_type_e type;
  /**
     UUID of the target of the cherrypick. The bytes are owned by
     this object.
  */
  fsl_uuid_str target;
  /**
     UUID of the baseline for the cherrypick. The bytes are owned by
     this object.
  */
  fsl_uuid_str baseline;
};
/** Empty-initialized fsl_card_Q struct. */
#define fsl_card_Q_empty_m {FSL_CHERRYPICK_INVALID, NULL, NULL}
/** Empty-initialized fsl_card_Q struct. */
FSL_EXPORT const fsl_card_Q fsl_card_Q_empty;

/**
   Allocates a new J-card record instance

   On success it returns a new record which must eventually be
   passed to fsl_card_J_free() to free its resources. On
   error (invalid arguments or allocation error) it returns NULL.
   field may not be NULL or empty but value may be either.

   These records are immutable - the API provides no way to change
   them once they are instantiated.
*/
FSL_EXPORT fsl_card_J * fsl_card_J_malloc(bool isAppend,
                                          char const * field,
                                          char const * value);
/**
   Frees a J-card record created by fsl_card_J_malloc().
   Is a no-op if cp is NULL.
*/
FSL_EXPORT void fsl_card_J_free( fsl_card_J * cp );

/**
   Allocates a new fsl_card_T instance. If any of the pointer
   parameters are non-NULL, their values are assumed to be
   NUL-terminated strings, which this function copies.  Returns NULL
   on allocation error.  The returned value must eventually be passed
   to fsl_card_T_clean() or fsl_card_T_free() to free its resources.

   If uuid is not NULL and fsl_is_uuid(uuid) returns false then
   this function returns NULL. If it is NULL and gets assigned
   later, it must conform to fsl_is_uuid()'s rules or downstream
   results are undefined.

   @see fsl_card_T_free()
   @see fsl_card_T_clean()
   @see fsl_deck_T_add()
*/
FSL_EXPORT fsl_card_T * fsl_card_T_malloc(fsl_tagtype_e tagType,
                                          fsl_uuid_cstr uuid,
                                          char const * name,
                                          char const * value);
/**
   If t is not NULL, calls fsl_card_T_clean(t) and then passes t to
   fsl_free().

   @see fsl_card_T_clean()
*/
FSL_EXPORT void fsl_card_T_free(fsl_card_T *t);

/**
   Frees up any memory owned by t and clears out t's state,
   but does not free t.

   @see fsl_card_T_free()
*/
FSL_EXPORT void fsl_card_T_clean(fsl_card_T *t);

/**
   Allocates a new cherrypick record instance. The type argument must
   be one of FSL_CHERRYPICK_ADD or FSL_CHERRYPICK_BACKOUT.  target
   must be a valid UUID string. If baseline is not NULL then it also
   must be a valid UUID.

   On success it returns a new record which must eventually be
   passed to fsl_card_Q_free() to free its resources. On
   error (invalid arguments or allocation error) it returns NULL.

   These records are immutable - the API provides no way to change
   them once they are instantiated.
*/
FSL_EXPORT fsl_card_Q * fsl_card_Q_malloc(fsl_cherrypick_type_e type,
                                          fsl_uuid_cstr target,
                                          fsl_uuid_cstr baseline);
/**
   Frees a cherrypick record created by fsl_card_Q_malloc().
   Is a no-op if cp is NULL.
*/
FSL_EXPORT void fsl_card_Q_free( fsl_card_Q * cp );

/**
   Returns true if f is not NULL and f has an opened repo
   which contains a checkin with the given rid, else it returns
   false.

   As a special case, if rid==0 then this only returns true
   if the repository currently has no content in the blob
   table.
*/
FSL_EXPORT bool fsl_rid_is_a_checkin(fsl_cx * f, fsl_id_t rid);

/**
   Fetches the list of all directory names for a given checkin record
   id or (if rid is negative) the whole repo over all of its combined
   history. Each name entry in the list is appended to tgt. The
   results are reduced to unique names only and are sorted
   lexically. If addSlash is true then each entry will include a
   trailing slash character, else it will not. The list does not
   include an entry for the top-most directory.

   If rid is less than 0 then the directory list across _all_
   versions is returned. If it is 0 then the current checkout's RID
   is used (if a checkout is opened, otherwise a usage error is
   triggered). If it is positive then only directories for the
   given checkin RID are returned. If rid is specified, it is
   assumed to be the record ID of a commit (manifest) record, and
   it is impossible to distinguish between the results "invalid
   rid" and "empty directory list" (which is a legal result).

   On success it returns 0 and tgt will have a number of (char *)
   entries appended to it equal to the number of subdirectories in
   the repo (possibly 0).

   Returns non-0 on error, FSL_RC_MISUSE if !tgt, FSL_RC_NOT_A_REPO if
   f has no opened repository. On other errors error tgt might have
   been partially populated and the list contents should not be
   considered valid/complete. Results are undefined if f is NULL.

   Ownership of the returned strings is transfered to the caller,
   who must eventually free each one using
   fsl_free(). fsl_list_visit_free() is the simplest way to free
   them all at once.
*/
FSL_EXPORT int fsl_repo_dir_names( fsl_cx * f, fsl_id_t rid,
                                   fsl_list * tgt, bool addSlash );


/**
   ZIPs up a copy of the contents of a specific version from f's
   opened repository db. sym is the symbolic name for the checkin
   to ZIP. filename is the name of the ZIP file to output the
   result to. See fsl_zip_writer for details and caveats of this
   library's ZIP creation. If vRootDir is not NULL and not empty
   then each file injected into the ZIP gets that directory
   prepended to its name.

   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 result code is returned. This is
   intended primarily for providing feedback on the zip progress, 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.

   Returns 0 on success. On error returns non-0 and, except for
   FSL_RC_OOM and for FSL_RC_MISUSE when f is NULL, f's error state
   describes the failure, naming the check-in and, where one is
   involved, the file or the output file name.

   A symlink is stored as fossil(1) stores it: an entry with Unix
   mode 0120755 whose content is the link target.

   @see fsl_zip_writer
   @see fsl_card_F_visitor_f()
*/
FSL_EXPORT int fsl_repo_zip_sym_to_filename( fsl_cx * f, char const * sym,
                                             char const * vRootDir,
                                             char const * fileName,
                                             fsl_card_F_visitor_f progressVisitor,
                                             void * progressState);


/**
   Callback state for use with fsl_repo_extract_f() implementations
   to stream a given version of a repository's files, one file at a
   time, to a client. Instances are never created by client code,
   only by fsl_repo_extract() and its delegates, which pass them to
   client-provided fsl_repo_extract_f() functions.
*/
struct fsl_repo_extract_state {
  /**
     The associated Fossil context.
  */
  fsl_cx * f;
  /**
     RID of the checkin version for this file. For a given call to
     fsl_repo_extract(), this number will be the same across all
     calls to the callback function.
  */
  fsl_id_t checkinRid;
  /**
     File-level blob.rid for fc. Can be used with, e.g.,
     fsl_mtime_of_manifest_file().
  */
  fsl_id_t fileRid;
  /**
     Client state passed to fsl_repo_extract(). Its interpretation
     is callback-implementation-dependent.
  */
  void * callbackState;
  /**
     The F-card being iterated over. This holds the repo-level
     metadata associated with the file, other than its RID, which is
     available via this->fileRid.

     Deleted files are NOT reported via the extraction process
     because reporting them accurately is trickier and more
     expensive than it could be. Thus this member's uuid field
     will always be non-NULL.

     Certain operations which use this class, e.g. fsl_repo_ckout()
     and fsl_ckout_update(), will temporarily synthesize an F-card to
     represent the state of a file update, in which case this object's
     contents might not 100% reflect any given db-side state. e.g.
     fsl_ckout_update() synthesizes an F-card which reflects the
     current state of a file after applying an update operation to it.
     In such cases, the fCard->uuid may refer to a repository-side
     file even though the hash of the on-disk file contents may differ
     because of, e.g., a merge.
  */
  fsl_card_F const * fCard;

  /**
     If the fsl_repo_extract_opt object which was used to initiate the
     current extraction has the extractContent member set to false,
     this will be a NULL pointer. If it's true, this member points to
     a transient buffer which holds the full, undelta'd/uncompressed
     content of fc's file record. The content bytes are owned by
     fsl_repo_extract() and are invalidated as soon as this callback
     returns, so the callback must copy/consume them immediately if
     needed.
  */
  fsl_b const * content;

  /**
     These counters can be used by an extraction callback to calculate
     a progress percentage.
  */
  struct {
    /** The current file number, starting at 1. */
    uint32_t fileNumber;
    /** Total number of files to extract. */
    uint32_t fileCount;
  } count;
};
typedef struct fsl_repo_extract_state fsl_repo_extract_state;

/**
   Initialized-with-defaults fsl_repo_extract_state instance, intended
   for const-copy initialization.
*/
#define fsl_repo_extract_state_empty_m {\
  NULL/*f*/, 0/*checkinRid*/, 0/*fileRid*/, \
  NULL/*state*/, NULL/*fCard*/, NULL/*content*/,    \
  {/*count*/0,0} \
}
/**
   Initialized-with-defaults fsl_repo_extract_state instance,
   intended for non-const copy initialization.
*/
FSL_EXPORT const fsl_repo_extract_state fsl_repo_extract_state_empty;

/**
   A callback type for use with fsl_repo_extract(). See
   fsl_repo_extract_state for the meanings of xstate's various
   members.  The xstate memory must be considered invalidated
   immediately after this function returns, thus implementations
   must copy or consume anything they need from xstate before
   returning.

   Implementations must return 0 on success. As a special case, if
   FSL_RC_BREAK is returned then fsl_repo_extract() will stop
   looping over files but will report it as success (by returning
   0). Any other code causes extraction looping to stop and is
   returned as-is to the caller of fsl_repo_extract().

   When returning an error, the client may use fsl_cx_err_set() to
   populate state->f with a useful error message which will
   propagate back up through the call stack.

   @see fsl_repo_extract()
*/
typedef int (*fsl_repo_extract_f)( fsl_repo_extract_state const * xstate );

/**
   Options for use with fsl_repo_extract().
*/
struct fsl_repo_extract_opt {
  /**
     The version of the repostitory to check out. This must be
     the blob.rid of a checkin artifact.
  */
  fsl_id_t checkinRid;
  /**
     The callback to call for each extracted file in the checkin.
     May not be NULL.
  */
  fsl_repo_extract_f callback;
  /**
     Optional state pointer to pass to the callback when extracting.
     Its interpretation is client-dependent.
  */
  void * callbackState;
  /**
     If true, the fsl_repo_extract_state::content pointer passed to
     the callback will be non-NULL and will contain the content of the
     file. If false, that pointer will be NULL. Such extraction is a
     relatively costly operation, so should only be enabled when
     necessary. Some uses cases can delay this decision until the
     callback and only fetch the content for cases which need it.
  */
  bool extractContent;
};

typedef struct fsl_repo_extract_opt fsl_repo_extract_opt;
/**
   Initialized-with-defaults fsl_repo_extract_opt instance, intended
   for intializing via const-copy initialization.
*/
#define fsl_repo_extract_opt_empty_m \
  {0/*checkinRid*/,NULL/*callback*/, \
   NULL/*callbackState*/,false/*extractContent*/}
/**
   Initialized-with-defaults fsl_repo_extract_opt instance,
   intended for intializing new non-const instances.
*/
FSL_EXPORT const fsl_repo_extract_opt fsl_repo_extract_opt_empty;

/**
   Iterates over the file content of a single checkin in a repository,
   sending the appropriate version of each file's contents to a
   client-specified callback.

   For each file in the given checkin, opt->callback() is passed a
   fsl_repo_extract_state instance containing enough information to,
   e.g., unpack the contents to a working directory, add it to a
   compressed archive, or send it to some other destination.

   Returns 0 on success, non-0 on error. It will fail if f has no
   opened repository db.

   If the callback returns any code other than 0 or FSL_RC_BREAK,
   looping over the list of files ends and this function returns
   that value. FSL_RC_BREAK causes looping to stop but 0 is
   returned.

   See fsl_repo_extract_f() for more details about the semantics of
   the callback. See fsl_repo_extract_opt for the documentation of the
   various options.

   Fossil's internal metadata format guarantees that files will be
   passed to the callback in "lexical order" (as defined by fossil's
   manifest format definition). i.e. the files will be passed in
   case-sensitive, alphabetical order, noting that upper-case letters
   sort before lower-case ones.

   Sidebar: this function makes a bitwise copy of the 2nd argument
   before starting its work, just in case the caller gets the crazy
   idea to modify it from the extraction callback. Whether or not
   there are valid/interesting uses for such modification remains to
   be seen. If any are found, this copy behavior may change.
*/
FSL_EXPORT int fsl_repo_extract( fsl_cx * f,
                                 fsl_repo_extract_opt const * opt );

/**
   Equivalent to fsl_tag_an_rid() except that it takes a symbolic
   artifact name in place of an artifact ID as the third
   argumemnt.

   This function passes symToTag to fsl_sym_to_rid(), and on
   success passes the rest of the parameters as-is to
   fsl_tag_an_rid(). See that function the semantics of the other
   arguments and the return value, as well as a description of the
   side effects.
*/
FSL_EXPORT int fsl_tag_sym( fsl_cx * f, fsl_tagtype_e tagType,
                 char const * symToTag, char const * tagName,
                 char const * tagValue, char const * userName,
                 double mtime, fsl_id_t * newId );

/**
   Adds a control record to f's repository that either creates or
   cancels a tag.

   artifactRidToTag is the RID of the record to be tagged.

   tagType is the type (add, cancel, or propagate) of tag.

   tagName is the name of the tag. Must not be NULL/empty.

   tagValue is the optional value for the tag. May be NULL.

   userName is the user's name to apply to the artifact. May not be
   empty/NULL. Use fsl_user_name_guess() to try to figure out a
   proper user name based on the environment. See also:
   fsl_cx_user_get(), but note that the application must first
   use fsl_cx_user_set() to set a context's user name.

   mtime is the Julian Day timestamp for the new artifact. Pass a
   value <=0 to use the current time.

   If newId is not NULL then on success the rid of the new tag control
   artifact is assigned to *newId.

   Returns 0 on success and has about a million and thirteen
   possible error conditions. On success a new artifact record is
   written to the db, its RID being written into newId as described
   above.

   If the artifact being tagged is private, the new tag is also
   marked as private.

*/
FSL_EXPORT int fsl_tag_an_rid( fsl_cx * f, fsl_tagtype_e tagType,
                 fsl_id_t artifactRidToTag, char const * tagName,
                 char const * tagValue, char const * userName,
                 double mtime, fsl_id_t * newId );

/**
    Searches for a repo.tag entry given name in the given context's
    repository db. If found, it returns the record's id. If no record
    is found and create is true then a tag is created and its entry id
    is returned. Returns 0 if it finds no entry, a negative value on
    error, in which case f's error state is updated.
*/
FSL_EXPORT fsl_id_t fsl_tag_id( fsl_cx * f, char const * tag, bool create );

/**
   Returns true if blob rid in f's repository db has an active tag
   with the given id, else returns false.

   Returns false on any sort of error, as well, in which case f's
   error state is updated.
*/
FSL_EXPORT bool fsl_rid_has_tag_id(fsl_cx * f, fsl_id_t rid, fsl_id_t tagId);

/**
   A thin proxy around fsl_rid_has_tag_id() which uses fsl_tag_id() to
   look up the given tag's ID.
*/
FSL_EXPORT bool fsl_rid_has_tag(fsl_cx * f, fsl_id_t rid, char const *zTag);

/**
   Returns true if the checkin with the given rid is a leaf, false if
   not. Returns false if f has no repo db opened, the query fails
   (likely indicating that it is not a repository db), or just about
   any other conceivable non-success case.

   A leaf, by the way, is a commit which has no children in the same
   branch.

   Sidebar: this function calculates whether the RID is a leaf, as
   opposed to checking the "static" (pre-calculated) list of leaves in
   the [leaf] table.
*/
FSL_EXPORT bool fsl_rid_is_leaf(fsl_cx * f, fsl_id_t rid);

/**
   Counts the number of primary non-branch children for the given
   check-in.

   A primary child is one where the parent is the primary parent, not
   a merge parent.  A "leaf" is a node that has zero children of any
   kind. This routine counts only primary children.

   A non-branch child is one which is on the same branch as the parent.

   Returns a negative value on error.
*/
FSL_EXPORT fsl_int_t fsl_count_nonbranch_children(fsl_cx * f,
                                                  fsl_id_t rid);

/**
   Looks for the delta table record where rid==deltaRid, and
   returns that record's srcid via *rv. Returns 0 on success, non-0
   on error. If no record is found, *rv is set to 0 and 0 is
   returned (as opposed to FSL_RC_NOT_FOUND) because that generally
   simplifies the error checking.

   Results are undefined if any pointer argument is NULL.
*/
FSL_EXPORT int fsl_delta_r2s( fsl_cx * f, fsl_id_t deltaRid,
                              fsl_id_t * rv );
/* Deprecated name for fsl_delta_r2s. */
#define fsl_delta_src_id fsl_delta_r2s

/**
   The counterpart of fsl_delta_r2s(): for a given delta.srcid, return
   the associated delta.rid via *rv.  See that function for more
   details.
*/
FSL_EXPORT int fsl_delta_s2r( fsl_cx * f, fsl_id_t deltaRid,
                              fsl_id_t * rv );


/**
   Return true if the given artifact ID should is listed in f's
   shun table or if zUuid is an SHA1 has and f's hash policy
   is set to FSL_HPOLICY_SHUN_SHA1.

   This function has no way to report errors except via the f
   object. If there is an error in this call, f's error state will be
   updated.

   Reminder to self: there is no fsl_is_shunned_rid() because rids
   refer to blob table records and the blob table is not supposed to
   contain shunned artifacts.
*/
FSL_EXPORT bool fsl_is_shunned_uuid(fsl_cx * f, fsl_uuid_cstr zUuid);
/* Old name for fsl_is_shunned_uuid(). */
#define fsl_uuid_is_shunned fsl_is_shunned_uuid


/**
   Compute the "mtime" of the file given whose blob.rid is "fid"
   that is part of check-in "vid".  The mtime will be the mtime on
   vid or some ancestor of vid where fid first appears. Note that
   fossil does not track the "real" mtimes of files, it only
   computes reasonable estimates for those files based on the
   timestamps of their most recent checkin in the ancestry of vid.

   If fid is 0 or less then the D-card time of the artifact with the
   blob.rid == vid is written to pMTime (this is a much less expensive
   operation, by the way).  In this particular case (A) vid may refer
   to any artifact type which has a D-card and (B) FSL_RC_NOT_FOUND is
   returned if vid is not a valid artifact RID.

   On success, if pMTime is not null then the result is written to
   *pMTime.

   Returns 0 on success, non-0 on error. Returns FSL_RC_NOT_FOUND
   if fid is not found in vid.

   This routine is much more efficient if used to answer several
   queries in a row for the same manifest (the vid parameter). It
   is least efficient when it is passed intermixed manifest IDs,
   e.g. (1, 3, 1, 4, 1,...). This is a side-effect of the caching
   used in the computation of ancestors for a given vid.
*/
FSL_EXPORT int fsl_mtime_of_manifest_file(fsl_cx * f, fsl_id_t vid, fsl_id_t fid,
                                          fsl_time_t * pMTime);

/**
   A convenience form of fsl_mtime_of_manifest_file() which looks up
   fc's RID based on its UUID. vid must be the RID of the checkin
   version fc originates from. See fsl_mtime_of_manifest_file() for
   full details - this function simply calculates the 3rd argument
   for that one.
*/
FSL_EXPORT int fsl_mtime_of_F_card(fsl_cx * f, fsl_id_t vid, fsl_card_F const * fc,
                                   fsl_time_t * pMTime);

/**
   Ensures that the given list has capacity for at least n entries. If
   n is 0, li->list and the F-cards it contains are freed and the list
   is zeroed out. Else if the capacity is already at least n, this is
   a no-op. Else li->list is expanded to hold at least n
   elements. Returns 0 on success, FSL_RC_OOM on allocation error.
 */
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.
*/
FSL_EXPORT void fsl_card_F_list_finalize( fsl_card_F_list * li );

/**
   Iterates over all artifacts in f's current repository of the given
   type, passing each one to the given callback. If the callback
   returns non-0, iteration stops and that code is propagated back to
   the caller _unless_ the code is FSL_RC_BREAK, which means to stop
   iteration and return 0.

   The following artifact types are currently supported by this
   operation:

   FSL_SATYPE_CHECKIN, FSL_SATYPE_CONTROL, FSL_SATYPE_WIKI,
   FSL_SATYPE_TICKET, FSL_SATYPE_TECHNOTE, FSL_SATYPE_FORUMPOST

   (CLUSTER and ATTACHMENT are missing only because they're not(?)
   readily findable without parsing every blob in the blob
   table.)

   The decks are iterated over an an unspecified order except for:

   - WIKI and TECHNOTE entries are visited from newest to oldest.

   - TICKET entries are visited from oldest to newest to accommodate
     reconstructing their aggregate state in the callback.

   Each deck is finalized immediately after the callback returns, so
   the callback must not hold any pointers to the deck or its
   contents.

   Returns 0 on success or any number of error codes from lower levels,
   including, but not limited to:

   - FSL_RC_OOM on allocation error
   - FSL_RC_NOT_A_REPO if f has no repository opened.
   - FSL_RC_TYPE if the 2nd argument is invalid or if its type is
     not supported (e.g. FSL_SATYPE_CLUSTER).
   - FSL_RC_MISUSE if the 3rd argument is NULL.

*/
FSL_EXPORT int fsl_deck_foreach(fsl_cx * f, fsl_satype_e type,
                                fsl_deck_visitor_f visitor,
                                void * visitorState);

/**
   Holds options for use with fsl_branch_create().
*/
struct fsl_branch_opt {
  /**
     The checkin RID from which the branch should originate.
  */
  fsl_id_t basisRid;
  /**
     The name of the branch. May not be NULL or empty.
  */
  char const * name;
  /**
     User name for the branch. If NULL, fsl_cx_user_get() will
     be used.
  */
  char const * user;
  /**
     Optional comment (may be NULL). If NULL or empty, a default
     comment is generated (because fossil requires a non-empty
     comment string).
  */
  char const * comment;
  /**
     Optional background color for the fossil(1) HTML timeline
     view.  Must be in \#RRGGBB format, but this API does not
     validate it as such.

     Use of an explicit bgColor is discouraged. This capability
     pre-dates fossil's ability to theme the website via CSS and
     manually-selected colors often visually collide with various
     skins.
  */
  char const * bgColor;
  /**
     The julian time of the branch. If 0 or less, default is the
     current time.
  */
  double mtime;
  /**
     If true, the branch will be marked as private.
  */
  bool isPrivate;
};
typedef struct fsl_branch_opt fsl_branch_opt;
#define fsl_branch_opt_empty_m {                \
    0/*basisRid*/, NULL/*name*/,                \
      NULL/*user*/, NULL/*comment*/,            \
      NULL/*bgColor*/,                          \
      0.0/*mtime*/, 0/*isPrivate*/              \
      }
FSL_EXPORT const fsl_branch_opt fsl_branch_opt_empty;

/**
   Creates a new branch in f's repository. The 2nd paramter holds
   the options describing the branch. The 3rd parameter may be
   NULL, but if it is not then on success the RID of the new
   manifest is assigned to *newRid.

   In Fossil branches are implemented as tags. The branch name
   provided by the client will cause the creation of a tag with
   name name plus a "sym-" prefix to be created (if needed).
   "sym-" denotes that it is a "symbolic tag" (fossil's term for
   "symbolic name applying to one or more checkins,"
   i.e. branches).

   Creating a branch cancels all other branch tags which the new
   branch would normally inherit.

   Returns 0 on success, non-0 on error.

   This function errors with FSL_RC_ALREADY_EXISTS if an open leaf
   with the given branch name already exists. TODO (2026-10-28) is to
   add a fsl_branch_opt flag which tells it to forego that check
   (introduced in [17c0719deb] 2026-10-03).
*/
FSL_EXPORT int fsl_branch_create(fsl_cx * f, fsl_branch_opt const * opt,
                                 fsl_id_t * newRid );

/**
   Checks f's repo db for a setting named 'main-branch'. If
   found. *zOut is set to that string. The mememory is owned by f and
   is retained for later calls to this function, but it may be
   invalidated by certain fsl APIs (namely this very function, if
   forceReload is true, and fsl_cx_finalize()). If forceReload is true
   then any cached value is freed and re-loaded.

   Returns 0 on success. On error, *zOut is not modified. If no such
   setting is found, "trunk" is used.
 */
FSL_EXPORT int fsl_branch_main(fsl_cx *f, char const **zOut, bool forceReload);

/**
   Tries to determine the [filename.fnid] value for the given
   filename.  Returns a positive value if it finds one, 0 if it
   finds none, and some unspecified negative value(s) for any sort
   of error. filename must be a normalized, relative filename (as it
   is recorded by a repo).
*/
FSL_EXPORT fsl_id_t fsl_repo_filename_fnid( fsl_cx * f, char const * filename );

/**
   Resolves client-provided symbol as an artifact's db record ID.
   f must have an opened repository db, and some symbols can only
   be looked up if it has an opened checkout (see the list below).

   Returns 0 and sets *rv to the id if it finds an unambiguous
   match.

   Returns FSL_RC_MISUSE if !sym, !*sym, or !rv.

   Returns FSL_RC_NOT_A_REPO if f has no opened repository.

   Returns FSL_RC_AMBIGUOUS if sym is a partial UUID which matches
   multiple full UUIDs.

   Returns FSL_RC_NOT_FOUND if it cannot find anything.

   Symbols supported by this function:

   - SHA1/3 hash
   - SHA1/3 hash prefix of at least 4 characters
   - Symbolic Name, e.g. branch name
   - "tag:" + symbolic name
   - Date or date-time
   - "date:" + Date or date-time
   - symbolic-name ":" date-time
   - "tip" means the most recent checkin, regardless of its branch
   - "rid:###" resolves to the hash of blob.rid ### if that RID is in
     the database

   The following additional forms are available in local checkouts:

   - "current"
   - "prev" or "previous"
   - "next"

   The following prefix may be applied to the above to modify how
   they are resolved:

   - "root:" prefix resolves to the checkin of the parent branch from
   which the record's branch divered. i.e. the version from which it
   was branched. In the trunk this will always resolve to the first
   checkin.

   - "start:" prefix resolves to the first checkin of the branch to
   which the given checkin belongs. This differs from "root:" by a
   single checkin: the "root:" point is the parent checkin of the
   "start:" point.

   - "merge-in:" TODO - document this once its implications are
   understood.

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

/**
   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
   match and one of any number of possible result codes on error, most
   notably FSL_RC_NOT_FOUND if no match is found.
*/
FSL_EXPORT int fsl_sym_to_uuid( fsl_cx * f, char const * sym,
                                fsl_satype_e type, fsl_uuid_str * rv,
                                fsl_id_t * rid );


/**
   Searches f's repo database for the a blob with the given uuid
   (any unique UUID prefix). On success a positive record ID is
   returned. On error one of several unspecified negative values is
   returned. If no uuid match is found 0 is returned.

   Error cases include: uuid is NULL or empty, uuid does not appear
   to be a full or partial UUID (or is too long), uuid is ambiguous
   (try providing a longer one). f's error state is updated for all
   error cases.

   This implementation is more efficient when given a full, valid UUID
   (one for which fsl_is_uuid() returns true).
*/
FSL_EXPORT fsl_id_t fsl_uuid_to_rid( fsl_cx * f, char const * uuid );

/**
   The opposite of fsl_uuid_to_rid(), this returns the UUID string
   of the given blob record ID. Ownership of the string is passed
   to the caller and it must eventually be freed using
   fsl_free(). Returns NULL on error (invalid arguments or f has no
   repo opened) or if no blob record is found. If no record is
   found, f's error state is updated with an explanation of the
   problem.
*/
FSL_EXPORT fsl_uuid_str fsl_rid_to_uuid(fsl_cx * f, fsl_id_t rid);

/**
   Works like fsl_rid_to_uuid() but assigns the UUID to the given
   buffer, re-using its memory, if any. Returns 0 on success,
   FSL_RC_MISUSE if rid is not positive, FSL_RC_OOM on allocation
   error, and FSL_RC_NOT_FOUND if no blob entry matching the given rid
   is found.
*/
FSL_EXPORT int fsl_rid_to_uuid2(fsl_cx * f, fsl_id_t rid, fsl_b *uuid);

/**
   This works identically to fsl_rid_to_uuid() except that it will
   only resolve to a UUID if an artifact matching the given type has
   that UUID. If no entry is found, f's error state gets updated
   with a description of the problem.

   This can be used to distinguish artifact UUIDs from file blob
   content UUIDs by passing the type FSL_SATYPE_ANY. A non-artifact
   blob will return NULL in that case, but any artifact type will
   match (assuming rid is valid).
*/
FSL_EXPORT fsl_uuid_str fsl_rid_to_artifact_uuid(fsl_cx * f, fsl_id_t rid,
                                                 fsl_satype_e type);
/**
   Returns the raw SQL code for a Fossil global config database.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_config(void);

/**
   Returns the raw SQL code for the "static" parts of a Fossil
   repository database. These are the parts which are immutable
   (for the most part) between Fossil versions. They change _very_
   rarely.

   The SQL names the repository's schema with the placeholder
   {{dbname.repo}}, and tables in REFERENCES and index ON clauses with
   {{bare.repo.NAME}}, so it is meant to be passed as the format string
   of fsl_db_exec_multi() or fsl_cx_exec_multi(), which expand them for
   the database or context. Passed as data (e.g. via "%s"), or to plain
   sqlite3, it does not run as is. It does not set the repository db's
   PRAGMA application_id (252006673), which libfossil sets
   separately for a repository db file of its own.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_repo1(void);

/**
   Returns the raw SQL code for the "transient" parts of a Fossil
   repository database - any parts which can be calculated via data
   held in the primary "static" schemas. These parts are
   occassionally recreated, e.g. via a 'rebuild' of a repository.

   Uses the {{dbname.repo}} and {{bare.repo.NAME}} placeholders: see
   fsl_schema_repo1() for how to run it.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_repo2(void);

/**
   Returns the raw SQL code for a Fossil checkout database.

   Uses the {{dbname.ckout}} and {{bare.ckout.NAME}} placeholders: see
   fsl_schema_repo1() for how to run it. It does not set the checkout
   db's PRAGMA application_id (252006674, 'FSLC'), which libfossil
   sets separately for a checkout db file of its own.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_ckout(void);

/**
   Returns the raw SQL code for a Fossil checkout db's
   _default_ core ticket-related tables.

   TODO: add optional (fsl_size_t*) to return the length.

   @see fsl_cx_schema_ticket()
*/
FSL_EXPORT char const * fsl_schema_ticket(void);

/**
   Returns the raw SQL code for the "forum" parts of a Fossil
   repository database.

   Uses the {{dbname.repo}} and {{bare.repo.NAME}} placeholders: see
   fsl_schema_repo1() for how to run it.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_forum(void);

/**
   If f's opened repository has a non-empty config entry named
   'ticket-table', this returns its text via appending it to
   pOut. If no entry is found, fsl_schema_ticket() is appended to
   pOut.

   Returns 0 on success. On error the contents of pOut must not be
   considered valid but pOut might be partially populated.
*/
FSL_EXPORT int fsl_cx_schema_ticket(fsl_cx * f, fsl_b * pOut);

/**
   Returns the raw SQL code for Fossil ticket reports schemas.
   This gets installed as needed into repository databases.

   Uses the {{dbname.repo}} placeholder: see
   fsl_schema_repo1() for how to run it.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_ticket_reports(void);

/**
   This is a wrapper around fsl_cx_hash_buffer() which looks for a
   matching artifact for the given input blob. It first hashes src
   using f's "alternate" hash and then, if no match is found, tries
   again with f's preferred hash.

   On success (a match is found):

   - Returns 0.

   - If ridOut is not NULL, *ridOut is set to the RID of the matching
     blob.

   - If hashOut is not NULL, *hashOut is set to the hash of the
     blob. Its ownership is transferred to the caller, who must
     eventually pass it to fsl_free().

   If no matching blob is found in the repository, FSL_RC_NOT_FOUND is
   returned (but f's error state is not annotated with more
   information). Returns FSL_RC_NOT_A_REPO if f has no repository
   opened. For more serious errors, e.g. allocation error or db
   problems, another (more serious) result code is returned,
   e.g. FSL_RC_OOM or FSL_RC_DB.

   If FSL_RC_NOT_FOUND is returned and hashOut is not NULL, *hashOut
   is set to the value of f's preferred hash and *hashOut's ownership
   is transferred to the caller. *ridOut is only modified if 0 is
   returned, in which case *ridOut will have a positive value.
*/
FSL_EXPORT int fsl_repo_blob_lookup( fsl_cx * f, fsl_b const * src,
                                     fsl_id_t * ridOut,
                                     fsl_uuid_str * hashOut );

/**
   Returns true if the specified file name ends with any reserved
   name, e.g.: _FOSSIL_ or .fslckout.

   For the sake of efficiency, zFilename must be a canonical name,
   e.g. an absolute or checkout-relative path using only forward slash
   ('/') as a directory separator.

   On Windows builds, this also checks for reserved Windows filenames,
   e.g. "CON" and "PRN".

   nameLen must be the length of zFilename. If it is negative,
   fsl_strlen() is used to calculate it.
*/
FSL_EXPORT bool fsl_is_reserved_fn(const char *zFilename,
                                   fsl_int_t nameLen );

/**
   Uses fsl_is_reserved_fn() to determine whether the filename part of
   zPath is legal for use as an in-repository filename. If it is, 0 is
   returned, else FSL_RC_RANGE (or FSL_RC_OOM) is returned and f's
   error state is updated to indicate the nature of the problem. nFile
   is the length of zPath. If negative, fsl_strlen() is used to
   determine its length.

   If relativeToCwd is true then zPath, if not absolute, is
   canonicalized as if were relative to the current working directory
   (see fsl_getcwd()), else it is assumed to be relative to the
   current checkout (if any - falling back to the current working
   directory). This flag is only relevant if zPath is not absolute and
   if f has a checkout opened. An absolute zPath is used as-is and if
   no checkout is opened then relativeToCwd is always treated as if it
   were true.

   This routine does not validate that zPath lives inside a checkout
   nor that the file actually exists. It does only name comparison and
   only uses the filesystem for purposes of canonicalizing (if needed)
   zPath.

   This routine does not require that f have an opened repo, but if it
   does then this routine compares the canonicalized forms of both the
   repository db and the given path and fails if zPath refers to the
   repository db. Be aware that the relativeToCwd flag may influence
   that test.

   This routine also checks fsl_ckout_manifest_setting() and reports
   any of the files represented by that function's results as being
   reserved. It only treats such names as reserved if they are at the
   top level of the repository - those same names in subdirectories are
   not reserved. If f has no checkout opened and relativeToCwd is true
   then those names are considered to be at the "top" if they are in
   the current directory.
*/
FSL_EXPORT int fsl_reserved_fn_check(fsl_cx * f, const char *zPath,
                                     fsl_int_t nFile, bool relativeToCwd);

/**
   Recompute/rebuild the entire repo.leaf table. This is not normally
   needed, as leaf tracking is part of the crosslinking process, but
   "just in case," here it is.

   The result is the same leaf table which crosslinking every
   check-in in a single batch produces: only check-ins which have a
   branch tag (of any type), and the parents of such check-ins, are
   considered, and each of those is a leaf if it has no child in the
   same branch. A check-in with no branch tag which is not the parent
   of one with a branch tag is never a leaf.

   This can supposedly be expensive (in time) for a really large
   repository. Testing implies otherwise.

   Returns 0 on success. On error f's error state may be updated.
   Results are undefined if f is invalid or has no opened repository.
*/
FSL_EXPORT int fsl_repo_leaves_rebuild(fsl_cx * f);

/**
   Flags for use with fsl_leaves_compute().
*/
enum fsl_leaves_compute_e {
/**
   Compute all leaves regardless of the "closed" tag.
*/
FSL_LEAVES_COMPUTE_ALL = 0,
/**
   Compute only leaves without the "closed" tag.
*/
FSL_LEAVES_COMPUTE_OPEN = 1,
/**
   Compute only leaves with the "closed" tag.
*/
FSL_LEAVES_COMPUTE_CLOSED = 2
};
typedef enum fsl_leaves_compute_e fsl_leaves_compute_e;

/**
   Creates a temporary table named "leaves" if it does not already
   exist, else empties it. Populates that table with the RID of all
   check-ins that are leaves which are descended from the checkin
   referred to by vid.

   A "leaf" is a check-in that has no children in the same branch.
   There is a separate permanent table named [leaf] that contains all
   leaves in the tree. This routine is used to compute a subset of
   that table consisting of leaves that are descended from a single
   check-in.

   The leafMode flag determines behavior associated with the "closed"
   tag, as documented for the fsl_leaves_compute_e enum.

   If vid is <=0 then this function, after setting up or cleaning out
   the [leaves] table, simply copies the list of leaves from the
   repository's pre-computed [leaf] table (see
   fsl_repo_leaves_rebuild()).

   @see fsl_leaves_computed_has()
   @see fsl_leaves_computed_count()
   @see fsl_leaves_computed_latest()
   @see fsl_leaves_computed_cleanup()
*/
FSL_EXPORT int fsl_leaves_compute(fsl_cx * f, fsl_id_t vid,
                                  fsl_leaves_compute_e leafMode);

/**
   Requires that a prior call to fsl_leaves_compute() has succeeded,
   else results are undefined.

   Returns true if the leaves list computed by fsl_leaves_compute() is
   not empty, else false. This is more efficient than checking
   against fsl_leaves_computed_count()>0.
*/
FSL_EXPORT bool fsl_leaves_computed_has(fsl_cx * f);

/**
   Requires that a prior call to fsl_leaves_compute() has succeeded,
   else results are undefined.

   Returns a count of the leaves list computed by
   fsl_leaves_compute(), or a negative value if a db-level error is
   encountered. On errors other than FSL_RC_OOM, f's error state will
   be updated with information about the error.
*/
FSL_EXPORT fsl_int_t fsl_leaves_computed_count(fsl_cx * f);

/**
   Requires that a prior call to fsl_leaves_compute() has succeeded,
   else results are undefined.

   Returns the RID of the most recent checkin from those computed by
   fsl_leaves_compute(), 0 if no entries are found, or a negative
   value if a db-level error is encountered. On errors other than
   FSL_RC_OOM, f's error state will be updated with information about
   the error.
*/
FSL_EXPORT fsl_id_t fsl_leaves_computed_latest(fsl_cx * f);

/**
   Cleans up any db-side resources created by fsl_leaves_compute().
   e.g. drops the temporary table created by that routine. Any errors
   are silenty ignored.
*/
FSL_EXPORT void fsl_leaves_computed_cleanup(fsl_cx * f);

/**
   Returns true if f's current repository has the
   forbid-delta-manifests setting set to a truthy value. Results are
   undefined if f has no opened repository. Some routines behave
   differently if this setting is enabled. e.g. fsl_checkin_commit()
   will never generate a delta manifest and fsl_deck_save() will
   refuse to save a delta. This does not affect parsing or deltas or
   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.

   Delta manifests ARE NOT RECOMMENDED in practice, as described at
   length at:

   https://fossil-scm.org/home/doc/trunk/www/delta-manifests.md

   As of 2026-09, this setting defaults to on/true (previously
   off/false) in both fossil(1) and libfossil, primarily because delta
   manifests break and/or overly-complicate automated extraction of
   information from manifests, e.g. a list of tags, using shell
   scripts, Tcl, and the like.
*/
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_b * manifest,
                                       fsl_b * manifestUuid,
                                       fsl_b * 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 versions 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 * opt,
                                   fsl_annotate_step 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 * opt,
                                    fsl_annotate_step 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.
  */
  uint32_t limitVersions;

  /**
     An approximate number of milliseconds of processing time to limit
     the annotation to. Note that this is measured in CPU time, not
     "wall clock" time. This value is rough minimum approximation,
     and the annotation will stop at the first processing step after which
     this limit has been hit or surpassed.

     Even with this limit in place, the annotation engine may impose a
     minimum number of versions to step through before it enforces
     this limit.

     If both this and limitVersions are set to positive values, the
     first limit which is exceeded is applied.
  */
  uint32_t limitMs;
  /**
     - 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/*limitVersions*/, 0U/*limitMs*/,\
  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;

/**
   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.

   - FSL_RC_NOT_A_REPO if f has no opened repository.

   - FSL_RC_MISUSE if opt->out is NULL.

   - FSL_RC_DIFF_BINARY if a version of the file appears to be
     binary.

   - FSL_RC_RANGE if the version of the file being annotated is
     empty.

   - A db-related code if a database operation fails.

   Except for FSL_RC_OOM and codes returned by opt->out(), f's error
   state describes the failure.

   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.
*/
FSL_EXPORT int fsl_annotate( fsl_cx * f,
                             fsl_annotate_opt const * opt );


/** Convenience typedef and forward decl. */
typedef struct fsl_rebuild_opt fsl_rebuild_opt;

/**
   Metrics related to a repository rebuild.
*/
struct fsl_rebuild_metrics {
  /**
     The number of phantom artifacts seen during rebuild.
  */
  fsl_size_t phantomCount;
  /**
     Counts of each blob type seen during rebuild.  The FSL_SATYPE_ANY
     slot (0) counts non-artifact blobs.
  */
  fsl_size_t counts[FSL_SATYPE_count];
  /**
     The accumulated sizes of each blob type seen during rebuild. The
     FSL_SATYPE_ANY slot (0) counts non-artifact blobs.
  */
  fsl_size_t sizes[FSL_SATYPE_count];
};
typedef struct fsl_rebuild_metrics fsl_rebuild_metrics;

#define fsl_rebuild_metrics_empty_m { \
    .phantomCount = 0,                \
    .counts = {0,0,0,0,0,0,0,0,0},    \
    .sizes = {0,0,0,0,0,0,0,0,0}      \
  }

/**
   State for use with the fsl_rebuild_f() callback type.
*/
struct fsl_msg_rebuild {
  /**
     Fossil context for which this rebuild is being performed.
  */
  fsl_cx * f;
  /**
     The options object used for this invocation of fsl_repo_rebuild().
  */
  fsl_rebuild_opt const * opt;
  /**
     An _approximate_ upper bound on the number of files
     fsl_repo_rebuild() will process. This number is very likely
     somewhat larger than the number of times which opt->callback()
     will be called, but it is close enough to give some indication of
     how far along a rebuild is.

     This number may be higher than the real value because it's a fast
     approximation. Getting an exact count for the case before a
     rebuild is not always possible: the info needed to get an exact
     count is derived from the result of a rebuild.
  */
  fsl_size_t artifactCount;
  /**
     One-based counter of total artifacts processed so far. After
     rebuilding is finished, opt->callback will be called one final
     time with this value set to 0. The callback may use the value 0
     to recognize that this is post-rebuild step and finalize any
     output or whatever it wants to do.
  */
  fsl_size_t stepNumber;

  /**
     The `blob.rid` value of the just-processed blob. If stepNumber is 0,
     this will be 0.
  */
  fsl_id_t rid;

  /**
     The size of the just-processed blob, -1 if it is a phantom
     blob, or 0 when this object is part of a FSL_MSG_REBUILD_DONE
     message.
  */
  fsl_int_t blobSize;

  /**
     Set to FSL_SATYPE_INVALID if the just-processed blob is _not_ a
     fossil artifact. This will never be set to FSL_SATYPE_ANY.

     (API discrepancy: fsl_rebuild_metrics maps FSL_SATYPE_ANY to
     non-artifact blobs.)
  */
  fsl_satype_e artifactType;

  /**
     This is only non-0 for FSL_MSG_REBUILD_DONE messages, in which
     case it holds the result code of the overall rebuild process.
     This will only be set to non-0 once, if at all, in a given
     rebuild run.
  */
  int errCode;

  /**
     Metrics from the rebuild. On each rebuild step callback call,
     these will contain the updated metrics.
  */
  fsl_rebuild_metrics metrics;
};
/** Convenience typedef. */
typedef struct fsl_msg_rebuild fsl_msg_rebuild;

/** Initialized-with-defaults fsl_msg_rebuild structure, intended for
    const-copy initialization. */
#define fsl_msg_rebuild_empty_m { \
    .f = NULL, .opt = NULL, .artifactCount = 0, \
    .stepNumber = 0, .rid = 0, .blobSize = -1, \
    .artifactType = FSL_SATYPE_INVALID, \
    .errCode = 0, \
    .metrics = fsl_rebuild_metrics_empty_m \
  }

/** Initialized-with-defaults fsl_msg_rebuild structure, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_msg_rebuild fsl_msg_rebuild_empty;

/**
   Callback for use with fsl_repo_rebuild() in order to report
   progress. It must return 0 on success, and any non-0 results will
   abort the rebuild and be propagated back to the caller.

   Each time this is called, state->stepNumber will be incremented, starting
   at 1. After rebuilding is complete, it is called with a stepNumber
   of 0 to give the callback a chance to do any final bookkeeping or output
   cleanup or whatever.

   TODO: replace this with the fsl_msg interface and use
   fsl_msg_listener configured for the being-rebuilt fsl_cx.
*/
typedef int (*fsl_rebuild_f)(fsl_msg_rebuild const * state);

/**
   Options for the rebuild process.
*/
struct fsl_rebuild_opt {
  /**
     Scan artifacts in a random order (generally only of use in testing
     the library's code). This is primarily for testing that the library
     can handle its inputs in an arbitrary order.
  */
  bool randomize;
  /**
     True if clusters should be created.

     NOT YET IMPLEMENTED.
  */
  bool createClusters;
  /**
     If true, the savepoint started by the rebuild process will end in
     a rollback even on success.
  */
  bool dryRun;
  /**
     If true, the rebuild hashes each artifact's full content and
     fails with FSL_RC_CONSISTENCY if it does not match the artifact's
     hash. The rebuild already expands every artifact once, so this
     costs only the hashing. fsl_clone() uses this instead of
     verify-at-commit.
  */
  bool verifyHashes;
};

/** Initialized-with-defaults fsl_rebuild_opt structure, intended for
    const-copy initialization. */
#define fsl_rebuild_opt_empty_m {\
  .randomize=false, .createClusters=false, .dryRun=false, \
  .verifyHashes=false \
}

/** Initialized-with-defaults fsl_rebuild_opt structure, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_rebuild_opt fsl_rebuild_opt_empty;

/**
   "Rebuilds" the current repository database. This involves _at least_
   the following:

   - DROPPING all transient repository tables. ALL tables in the db
     which do not specifically belong to fossil and do not start with
     the name `fx_` _will be dropped_.

   - Recreating all transient tables from immutable state in the
     database.

   - Updating the schema, if needed, from "older" versions of the
     fossil schema to the "current" one. This library does not
     currently check for updates which need to be made to a decade-old
     schema, however! That is, schema changes which were introduced
     10+ years ago are not currently addressed by this library
     because, frankly, it's not expected that anyone using this
     library will be using it with such ancient repositories (and
     those who do can rebuild it once with fossil(1) to update it).

   - Crosslinking all blobs which appear to be artifacts (meaning they
     can be parsed as such). Any crosslink handlers registered via
     fsl_xlink_listener() will be called.

   If opt is NULL then fsl_rebuild_opt_empty is used.

   Returns 0 on success, non-0 on error (with any number of potential
   result codes from the db or crosslinking layers). Returns
   FSL_RC_NOT_A_REPO if f has no opened repository. An error while
   processing an artifact is reported with that artifact's rid and
   hash. A blob which does not parse as an artifact is not an error:
   it is treated as opaque content. It pushes its own
   transaction and will roll that back on non-0, so it "shouldn't"
   leave a mess on error. On error it does _not_ put any higher-level
   transaction into rollback mode.

   If opt->dryRun is true then it also rolls back the transaction but
   it is not treated as an error and the rollback does not affect
   higher levels of the transaction stack

   During the rebuild process, fsl_msg messages of types
   FSL_MSG_REBUILD_STEP and FSL_MSG_REBUILD_DONE may be fired.  The
   latter is only fired if the former is.

   This operation honors interruption via fsl_cx_interrupt() but, due
   to intricacies of timing, it's possible that a triggered interrupt
   gets trumped by another error which happens while the check for the
   interrupt flag is pending. In both cases this function could return
   a non-0 code, though.
*/
FSL_EXPORT int fsl_repo_rebuild(fsl_cx * f, fsl_rebuild_opt const * opt);

/**
   Sets the journal mode of f's repository db to zMode, which must be
   "wal", "delete", "truncate" or "persist". WAL mode is a property of the db
   file and stays set for all later connections from libfossil or fossil(1).

   SQLite commits a WAL db before the dbs in DELETE mode, so a check-in
   interrupted between the two leaves the checkout db behind the repo db. The
   next check-in detects this and fails with FSL_RC_WOULD_FORK, and
   fsl_ckout_update() moves the checkout to the new check-in. At
   synchronous=NORMAL, the in-tree SQLite's default for a WAL db, SQLite does
   not sync the WAL at each commit, so a power loss could instead leave the
   checkout db recording a check-in which the repo db has lost. While a
   checkout db is attached, libfossil sets the repo db to synchronous=FULL,
   which syncs the WAL before the checkout db commit. SQLite can't change 
   synchronous levels inside a transaction.

   Only the repo db can be in WAL mode. If libfossil finds a checkout db
   in WAL mode, libfossil resets the db back to DELETE on opening it. If
   a checkout db was permitted to be in WAL mode, SQLite's lack of atomic
   commit guarantee means that the checkout could commit before the repo,
   resulting in data loss.

   This function must not be called inside a transaction, including one on a
   host db handle (see fsl_cx_host_db()). Returns 0 on success,
   FSL_RC_NOT_A_REPO if f has not opened a repository, FSL_RC_MISUSE
   inside a transaction, for any other zMode, or for a repository
   which is tables of a host's main db (fsl_repo_open_host()), whose
   journal mode is the host's, and FSL_RC_LOCKED if SQLite cannot
   change the mode, e.g. while another connection has the db open.
*/
FSL_EXPORT int fsl_repo_journal_mode_set(fsl_cx * f, char const * zMode);

/**
   Tries to determine the branch name of the given rid, which is
   assumed to refer to a checkin artifact. If it cannot find one and
   doFallback is true then it looks for the `main-branch`
   repository-level config setting and uses that (falling back to
   "trunk" if that setting is not set).

   On success it returns 0 and sets `*zOut` to the branch name,
   transfering ownership of those bytes to the caller (who must
   eventually pass them to fsl_free()). If doFallback is false and no
   direct branch name is found then it sets `*zOut` to NULL. If
   doFallback is true then, on success, `*zOut` will always be set to
   some non-NULL value. On error `*zOut` is not modified.

   On error it may return FSL_RC_NOT_A_REPO, FSL_RC_OOM, or any number
   of db-side error codes.
*/
FSL_EXPORT int fsl_branch_of_rid(fsl_cx * f, fsl_id_t rid,
                                 bool doFallback, char ** zOut );

/** Convenience typedef and obligatory forward declaration. */
typedef struct fsl_cidiff_state fsl_cidiff_state;

/**
   Callback type for use with fsl_cidiff(). It must return 0 on
   success or a value from the fsl_rc_e enum on error.  On error it
   "should" update the error state in the corresponding fsl_cx object
   by passing state->f to fsl_cx_err_set() (or equivalent).
*/
typedef int (*fsl_cidiff_f)(fsl_cidiff_state const *state);

/**
   Options for use with fsl_cidiff().
*/
struct fsl_cidiff_opt {
  /**
     Checkin version (RID) for "version 1".
  */
  fsl_id_t v1;
  /**
     Checkin version (RID) for "version 2". This checkin need not have
     any relationship with version 1, in terms of SCM-side lineage.
  */
  fsl_id_t v2;
  /**
     Callback to call on each iteration step.
  */
  fsl_cidiff_f callback;
  /**
     Opaque state for the callback. It can be accessed
     from the callback via arg->opt->callbackState.
  */
  void * callbackState;
};

/** Convenience typedef. */
typedef struct fsl_cidiff_opt fsl_cidiff_opt;

/** Initialized-with-defaults fsl_cidiff_opt structure, intended for
    const-copy initialization. */
#define fsl_cidiff_opt_empty_m {0,0,0,0}

/** Initialized-with-defaults fsl_cidiff_opt structure, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_cidiff_opt fsl_cidiff_opt_empty;

/**
   Descriptors for the type of information being reported for each
   step of fsl_cidiff() iteration, as reported via the
   fsl_cidiff_state::changes attribute.
*/
enum fsl_cidiff_e {
/**
   Indicates that the v1 and v2 files are the same. Specifically,
   this means:

   - Same current names, compared case-sensitively.
     fsl_card_F::priorName values are ignored for this
   - Same permissions.
   - Same hash.
*/
FSL_CIDIFF_NONE = 0,
/**
   Indicates that the hashes of the v1 and v2 files
   differ.
*/
FSL_CIDIFF_FILE_MODIFIED = 0x0001,
/**
   Indicates that the v2 file was renamed.

   Caveats:

   - If v1 and v2 are not immediate relatives in the SCM DAG
     sense. e.g. when comparing a version X and unrelated version Y,
     or version X and X+30, it is possible that a rename goes
     unreported via fsl_cidiff or that it gets misdiagnosed. e.g. if
     version X renames file A to B and version X+100 renames file C to
     A, it will be reported as a rename. Detecting the true reality of
     such cases is remarkably challenging, requiring going through the
     entire history which links v1 and v2.

   - Pedantically speaking, if v1 and v2 are unrelated in the SCM
     DAG, "renames" are not possible but will be reported as such
     if their names happen to match up.
*/
FSL_CIDIFF_FILE_RENAMED  = 0x0002,
/**
   Indicates that the permissions of the current file
   differ between v1 and v2. This is only set if
   both versions have a given file (by name, as opposed
   to hash).
*/
FSL_CIDIFF_FILE_PERMS    = 0x0004,
/**
   Indicates that the file is in v2 but not v1. If v1 and v2
   are unrelated versions or are not immediate DAG neighbors,
   this might also indicate that a file from v1 was renamed
   in v2.
*/
FSL_CIDIFF_FILE_ADDED    = 0x0010,
/**
   Indicates that the file is in v1 but not v2. If v1 and v2
   are unrelated versions or are not immediate DAG neighbors,
   this might also indicate that a file from v1 was renamed
   in v2.
*/
FSL_CIDIFF_FILE_REMOVED  = 0x0020
};
/** Convenience typedef. */
typedef enum fsl_cidiff_e fsl_cidiff_e;
/**
   Holds the state for a single iteration step of fsl_cidiff.
*/
struct fsl_cidiff_state {
  /**
     The associated fsl_cx instance.
  */
  fsl_cx * f;
  /**
     The options object passed to fsl_cidiff().
  */
  fsl_cidiff_opt const *opt;
  /**
     Denotes the type of this step in the iteration.

     Before fsl_cidiff() starts its loop over F-card changes,
     it calls the callback once with this value set to 0. The intent is to
     give the caller an opporuntity to do any required setup, e.g.
     outputing a report header. The
     fc1 and fc2 members will both be NULL, but the d1 and d2
     members will be set.

     For each step of the F-card iteration, stepType will be set to
     FSL_RC_STEP_ROW.

     After successful difference iteration, fsl_cidiff() calls its
     callback with stepType set to FSL_RC_STEP_DONE. The intent is to
     give the caller an opporuntity to do any required cleanup, e.g.
     outputing a report footer. The fc1 and fc2 members will both be
     NULL, but the d1 and d2 members will be set.
  */
  int stepType;
  /**
     Describes the change(s) being reported by the current
     iteration step, as a bitmask of fsl_cidiff_e values.
  */
  int changes;
  /**
     The file, if any, corresponding to this->v1. This will be NULL
     this->changeType is FSL_CIDIFF_FILE_ADDED.
  */
  fsl_card_F const * fc1;
  /**
     The file, if any, corresponding to this->v2. This will be NULL
     this->changeType is FSL_CIDIFF_FILE_REMOVED.
  */
  fsl_card_F const * fc2;
  /**
     The deck corresponding to this->opt->v1. It is strictly forbidden
     for this->callback to manipulate this object. Specifically, any
     traversal of its F-card list will invalidate the iteration being
     done by fsl_cidiff(). Read-only operations on other state of the
     deck are legal.
  */
  fsl_deck const * d1;
  /**
     The deck corresponding to this->opt->v2. See the docs for
     this->d1 for important details.
  */
  fsl_deck const * d2;
};

/** Initialized-with-defaults fsl_cidiff_state structure, intended for
    const-copy initialization. */
#define fsl_cidiff_state_empty_m {\
    NULL/*f*/,NULL/*opt*/,             \
    0/*stepType*/,FSL_CIDIFF_NONE/*changes*/, \
    NULL/*fc1*/,NULL/*fc2*/,    \
    NULL/*d1*/,NULL/*d2*/     \
  }

/** Initialized-with-defaults fsl_cidiff_state structure, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_cidiff_state fsl_cidiff_state_empty;

/**
   A utility for reporting the differences between the manifests of
   two checkins.

   This loads the fsl_deck instances for each version opt->v1 and
   opt->v2, then calls opt->callback for each step of the
   difference-checking process. It only inspects and reports the
   difference between _exactly_ v1 and _exactly_ v2, not the
   difference between the chain of SCM DAG relatives (if any) between
   the two.

   It is not required that v1 and v2 be related in the SCM DAG but its
   report of differences may be misleading if v1 and v2 are either
   unrelated or separated by more than 1 step in the DAG. See the docs
   for fsl_cidiff_e for cases known to be potentially confusing.

   Returns 0 on success. If the callback returns non-0, that result is
   propagated back to the caller. It may otherwise return any number of
   othe result codes including, but not limited to:

   - FSL_RC_OOM on allocation error

   - FSL_RC_NOT_A_REPO if f has no opened repository.

   - FSL_RC_TYPE if either of the given versions is not a checkin.

   - FSL_RC_NOT_FOUND if either of given versions is not found in the
   repository.


   Potential TODO: add fsl_deck_diff() which takes two decks, instead
   of RIDs, to compare. This function would just be a proxy for that
   one, loading the given RIDs and passing on the decks. That would
   require a significantly larger set of possible change-type values
   and would require much type-specific handling (e.g. maybe reporting
   J-card differences for a pair of ticket decks).
*/
FSL_EXPORT int fsl_cidiff(fsl_cx * f, fsl_cidiff_opt const * opt);


/**
   Configuration parameters for fsl_repo_create().  Always
   copy-construct these from fsl_repo_create_opt_empty
   resp. fsl_repo_create_opt_empty_m in order to ensure proper
   behaviour vis-a-vis default values.

   TODOs:

   - Add project name/description, and possibly other
   configuration bits.

   - Allow client to set password for default user (currently set
   randomly, as fossil(1) does).
*/
struct fsl_repo_create_opt {
  /**
     The file name for the new repository.
  */
  char const * filename;
  /**
     Fossil user name for the admin user in the new repo.  If NULL,
     defaults to the Fossil context's user (see
     fsl_cx_user_get()). If that is NULL, it defaults to
     "root" for historical reasons.
  */
  char const * username;

  /**
     The comment text used for the initial commit. If NULL or empty
     (starts with a NUL byte) then no initial check is
     created. fossil(1) is largely untested with that scenario (but
     it seems to work), so for compatibility it is not recommended
     that this be set to NULL.
  */
  char const * commitMessage;

  /**
     Mime type for the commit message (manifest N-card). Manifests
     support this but fossil(1) has never (as of 2025-07) made use of
     it. It is provided for completeness but should, for
     compatibility's sake, probably not be set, as the fossil UI may
     not honor it. The implied default is text/x-fossil-wiki. Other
     ostensibly legal values include text/plain and text/x-markdown.
     This API will accept any value, but results are technically
     undefined with any values other than those listed above.
  */
  char const * commitMessageMimetype;

  /**
     If not NULL and not empty, fsl_repo_create() will use this
     repository database to copy the configuration, copying over
     the following settings:

     - The reportfmt table, overwriting any existing entries.

     - The user table fields (cap, info, mtime, photo) are copied for
       the "system users": anonymous, nobody, developer, reader.

     - The vast majority of the config table is copied, arguably more
       than it should (e.g. the 'manifest' setting).
  */
  char const * configRepo;

  /**
     If false, fsl_repo_create() will fail if this->filename
     already exists.
  */
  bool allowOverwrite;

  /**
     If true, the new repo will not have a "project-code" config
     entry. Only set this to true when the next operation on the
     new repo will be an inbound clone.
  */
  bool elideProjectCode;

  /**
     If not NULL, the new repository is not a db file but the tables of
     the main db of f's host db handle (fsl_cx_host_db()) whose names
     start with this prefix, as fsl_repo_open_host() describes, and
     filename is not used. f must not be NULL, and allowOverwrite must
     be false (else FSL_RC_MISUSE): to start a repository afresh, drop
     its tables first. The tables are created in one transaction which
     holds the main db's write lock from before its checks, and the
     main db may then have no table, index, trigger or view whose name
     starts with the prefix (ignoring case), else
     FSL_RC_ALREADY_EXISTS. The initial check-in follows in a
     transaction of its own. The main db's application_id is not set.
  */
  char const * hostTablePrefix;
};
typedef struct fsl_repo_create_opt fsl_repo_create_opt;

/** Initialized-with-defaults fsl_repo_create_opt struct, intended
    for in-struct initialization. */
#define fsl_repo_create_opt_empty_m { \
    .filename=NULL,                   \
    .username=NULL,                   \
    .commitMessage=NULL,              \
    .commitMessageMimetype=NULL,      \
    .configRepo=NULL,                 \
    .allowOverwrite=false,            \
    .elideProjectCode=false,          \
    .hostTablePrefix=NULL             \
  }

/** Initialized-with-defaults fsl_repo_create_opt struct, intended
    for copy-initialization. */
FSL_EXPORT const fsl_repo_create_opt fsl_repo_create_opt_empty;

/**
   Creates a new repository database using the options provided in the
   second argument. If f is not NULL, it must be a valid context
   instance, though it need not have an opened checkout/repository. If
   f has an opened repo or checkout, this routine closes them but that
   closing _will fail_ if a transaction is currently active.

   If f is NULL, a temporary context is used for creating the
   repository, in which case the caller will not have access to
   detailed error information (only the result code) if this operation
   fails. In that case, the resulting repository file will, on
   success, be found at the location referred to by opt.filename.

   The opt argument may not be NULL. For opt->hostTablePrefix, see
   that member.

   If opt->allowOverwrite is false (0) and the file exists, it fails
   with FSL_RC_ALREADY_EXISTS, otherwise is creates/overwrites the
   file. This is a destructive operation if opt->allowOverwrite is
   true, so be careful: the existing database will be truncated and
   re-created.

   This operation installs the various "static" repository schemas
   into the db, sets up some default settings, and installs a
   default user.

   This operation always closes any repository/checkout opened by f
   because setting up the new db requires wiring it to f to set up
   some of the db-side infrastructure. The one exception is if
   argument validation fails, in which case f's repo/checkout-related
   state are not modified. Note that closing will fail if a
   transaction is currently active and that, in turn, will cause this
   operation to fail.

   See the fsl_repo_create_opt docs for more details regarding the
   creation options.

   On success, 0 is returned and f (if not NULL) is left with the
   new repository opened and ready for use. On error, f's error
   state is updated and any number of the FSL_RC_xxx codes may be
   returned - there are no less than 30 different _potential_ error
   conditions on the way to creating a new repository.

   If initialization of the repository fails, this routine will
   attempt to remove its partially-initialize corpse from the
   filesystem but will ignore any errors encountered while doing so.

   Example usage:

   ```
   fsl_repo_create_opt opt = fsl_repo_create_opt_empty;
   int rc;
   opt.filename = "my.fossil";
   // ... any other opt.xxx you want to set, e.g.:
   // opt.user = "fred";
   // Assume fsl is a valid fsl_cx instance:
   rc = fsl_repo_create(fsl, &opt);
   if(rc) { ...error... }
   else {
     fsl_db * db = fsl_cx_db_repo(f);
     assert(db); // == the new repo db
   ...
   }
   ```

   @see fsl_repo_open()
   @see fsl_repo_close()
*/
FSL_EXPORT int fsl_repo_create(fsl_cx * f, fsl_repo_create_opt const * opt );

/**
   UNTESTED.

   Returns true if f has an opened repository database which is
   opened in read-only mode, else returns false.
*/
FSL_EXPORT bool fsl_repo_is_readonly(fsl_cx const * f);

/**
   Searches for matching blob records for a fossil ticket ID. (A
   ticket's ID is the value of its K-card.) The given ticket ID must
   be a full-length ticket ID (40 characters of lower-case hex) or an
   unambiguous prefix.

   If at least one match is found, it returns 0 and updates the 3rd
   argument: `*ridList` is assigned to an array of fsl_id_t
   (`blob.rid` values) terminated by an entry with the value
   0. Ownership of the array is passed to the caller, who must
   eventually pass it to fsl_free(). The entries are ordered from
   oldest to newest (based on their `tagxref.mtime` value).

   On error it may return:

   - FSL_RC_OOM on allocation error.
   - FSL_RC_RANGE if the given ticket ID is longer than FSL_STRLEN_SHA1.
   - FSL_RC_AMBIGUOUS if the ticket ID prefix would match multiple distinct
     ticket IDs. This result is not possible if passed a full-length ticket
     ID.
   - FSL_RC_NOT_FOUND if no match is found.
   - FSL_RC_NOT_A_REPO if f has no repository opened.
   - Any number of db-related errors if something goes horribly wrong
     in the db layer.

   On error, the 3rd argument is not modified.
*/
FSL_EXPORT int fsl_tkt_id_to_rids(fsl_cx * f, char const * tktId,
                                  fsl_id_t ** ridList);

/**
   Models user permissions precisely as fossil(1) does. Most of these
   do not apply to the library - they are "app-level" permissions.
   Some very few are honored by the library, namely those relevant for
   sync support.  The app-level permissions are exposed here so that
   app-level code can handle those in ways compatible with fossil(1),
   while leaving the library to handle the permission storage (via the
   `user.cap` repository db field).
*/
struct fsl_uperm {
 bool setup;            /* s: use Setup screens on web interface */
 bool admin;            /* a: administrative permission */
 bool password;         /* p: change password */
 bool write;            /* i: xfer inbound. check-in */
 bool read;             /* o: xfer outbound. check-out */
 bool hyperlink;        /* h: enable the display of hyperlinks */
 bool clone;            /* g: clone */
 bool readWiki;         /* j: view wiki via web */
 bool newWiki;          /* f: create new wiki via web */
 bool appendWiki;       /* m: append to wiki via web */
 bool writeWiki;        /* k: edit wiki via web */
 bool moderateWiki;     /* l: approve and publish wiki content (Moderator) */
 bool readTicket;       /* r: view tickets via web */
 bool newTicket;        /* n: create new tickets */
 bool appendTicket;     /* c: append to tickets via the web */
 bool writeTicket;      /* w: make changes to tickets via web */
 bool moderateTicket;   /* q: approve and publish ticket changes (Moderator) */
 bool attach;           /* b: add attachments */
 bool ticketReport;     /* t: create new ticket report formats */
 bool readAddr;         /* e: read email addresses or other private data */
 bool zip;              /* z: download zipped artifact via /zip URL */
 bool privateContent;   /* x: can send and receive private content */
 bool writeUnversioned; /* y: can push unversioned content */
 bool readForum;        /* 2: Read forum posts */
 bool writeForum;       /* 3: Create new forum posts */
 bool trustedForum;     /* 4: Post to forums not subject to moderation */
 bool moderateForum;    /* 5: Moderate (approve or reject) forum posts */
 bool adminForum;       /* 6: Grant capability 4 to other users */
 bool emailAlert;       /* 7: Sign up for email notifications */
 bool announce;         /* A: Send announcements */
 bool chat;             /* C: read or write the chatroom */
 bool debug;            /* D: show extra Fossil debugging features */
  /* These last two represent capabilities inherited from predefined
     users. */
 bool xReader;          /* u: Inherit all privileges of "reader" */
 bool xDeveloper;       /* v: Inherit all privileges of "developer" */
};

/**
   Helper for mass-handling of fsl_uperm permissions (e.g. generating
   switch/case blocks).  Usage:

   1) #define a macro which takes two argument: the fsl_uperm member
     name (identifier) and its corresponding capabilities character
     (as a char literal).

   2) Invoke fsl_uperm_map_base(THAT_MACRO_NAME).

   The (1) macro will be invoked one time per fsl_uperm member,
   passing it (memberName,aChar). No commas or semicolons are emited
   between calls, so they need to be included in the definition of (1)
   if they're relevant.

   This macro does not include the "inehrits from" permissions
   (xReader, xDeveloper). Use fsl_uperm_map_inherited(M) or
   fsl_uperm_map_all(M) to include those.
*/
#define fsl_uperm_map_base(M)        \
  M(setup,'s') M(admin,'a') M(password,'p')              \
  M(write,'i') M(read,'o') M(hyperlink,'h') M(clone,'g') \
  M(readWiki,'j') M(newWiki,'f') M(appendWiki,'m') M(writeWiki,'k') \
  M(moderateWiki,'l') M(readTicket,'r') M(newTicket,'n') M(appendTicket,'c') \
  M(writeTicket,'w') M(moderateTicket,'q') M(attach,'b') M(ticketReport,'t') \
  M(readAddr,'e') M(zip,'z') M(privateContent,'x') M(writeUnversioned,'y') \
  M(readForum,'2') M(writeForum,'3') M(trustedForum,'4') M(moderateForum,'5') \
  M(adminForum,'6') M(emailAlert,'7') M(announce,'A') M(chat,'C') \
  M(debug,'D')

/**
   Like fsl_uperm_map_base() but only includes the "inherits from"
   members.
*/
#define fsl_uperm_map_inherited(M) \
  M(xReader,'u') M(xDeveloper,'v')

/**
   A combination of fsl_uperm_map_base() and
   fsl_uperm_map_inherited().
*/
#define fsl_uperm_map_all(M) \
  fsl_uperm_map_base(M) fsl_uperm_map_inherited(M)

/** @internal */
#define fsl__uperm_map_init(M,CH) .M=false,

/**
   Const-copy initializer for a fsl_uperm.
*/
#define fsl_uperm_empty_m { fsl_uperm_map_all(fsl__uperm_map_init) }

/**
   A fsl_uperm instance with all members set to false.
*/
extern const fsl_uperm fsl_uperm_empty;
/**
   A fsl_uperm instance with all members set to true except for the
   "inherits from" properties (xReader and xDeveloper), as those
   permissions are already implied in the setting of all other
   permissions to true.
*/
extern const fsl_uperm fsl_uperm_all;

/**
   Adds any permissions specified in zCap to pTgt. It does not
   modify permissions which are not in zCap.

   Returns 0 on success, non-0 on error. If zCap contains any
   unhandled characters it returns FSL_RC_RANGE, with the exception of
   spaces and tabs, which it ignores. It is not an error if zCap is
   empty or contains only spaces/tabs. If f is not NULL, f's error
   state describes the failure.

   If it returns non-0, pTgt's state is not well-defined. It may have
   been partially updated before the failure.

   Any given permission letter may imply other permissions. e.g.  the
   'a' and 's' permissions imply most others.

   f is optional (may be NULL) unless zCap contains 'u' or 'v', in
   which case f is required in order to collect the permissions for
   the the "reader" resp. "developer" user. If f is NULL in those
   cases, FSL_RC_MISUSE is returned. If f has no opened repo in those
   cases, FSL_RC_NOT_A_REPO is returned.
*/
FSL_EXPORT int fsl_uperm_add(fsl_cx * f, fsl_uperm * pTgt, char const *zCap);


/**
   Fetches f's current project code. On success, assigns it to *pOut
   and returns 0. Caches the result for future calls. Each repository
   has a project code which is shared across all of its clones, and
   fossil will not clone between repositories with differing project
   codes.

   The returned memory is owned by f and invalidated any time the
   project code needs to be re-read. Hypothetically that never happens
   within the lifetime of a given context's repository being open, but
   stranger things have happened. i.e. copy it if needed rather than
   relying on a long lifetime.
*/
FSL_EXPORT int fsl_repo_project_code( fsl_cx * f, char const **pOut );


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_REPO_H_INCLUDED */
/* end of file include/fossil-scm/repo.h */
/* start of file include/fossil-scm/checkout.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_CHECKOUT_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_CHECKOUT_H_INCLUDED
/*
  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-FileType: Code

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

/** @file checkout.h

    fossil-checkout.h declares APIs specifically dealing with
    checkout-side state, as opposed to purely repository-db-side state
    or non-content-related APIs.
*/


#if defined(__cplusplus)
extern "C" {
#endif


/**
   Tries to open a checked-out fossil repository db in the given
   directory (or "." if dirName is NULL). This routine canonicalizes
   its dirName argument using fsl_file_canonical_name(), then passes
   that and checkParentDirs on to fsl_ckout_db_search() to find a
   checkout db, so see that routine for how it searches.

   If this routine finds/opens a checkout, it also tries to open
   the repository database from which the checkout derives, and
   fails if it cannot. The library never allows a checkout to be
   opened without its corresponding repository partner because
   a checkout has hard dependencies on the repo's state.

   Returns 0 on success. If there is an error opening or validating
   the checkout or its repository db, f's error state will be
   updated. Error codes/conditions include:

   - FSL_RC_MISUSE if f is NULL.

   - FSL_RC_ACCESS if f already has an opened checkout.

   - FSL_RC_OOM if an allocation fails.

   - FSL_RC_NOT_FOUND if no checkout is found.

   - FSL_RC_NOT_A_REPO if a checkout is found but its repository db
   is not recorded in it, is not found, or is not a valid
   repository.

   - FSL_RC_RANGE if dirname is not NULL but has a length of 0.

   - Various codes from fsl_getcwd() (if dirName is NULL).

   - Various codes if opening the associated repository DB fails.

   TODO: there's really nothing in the architecture which restricts a
   checkout db to being in the same directory as the checkout, except
   for some historical bits which "could" be refactored. It "might be
   interesting" to eventually provide a variant which opens a checkout
   db file directly. We have the infrastructure, just need some
   refactoring. It "shouldn't" require any trickery or
   incompatibilities with fossil(1).
*/
FSL_EXPORT int fsl_ckout_open_dir( fsl_cx * const f, char const * dirName,
                                   bool checkParentDirs );


/**
   Searches the given directory (or the current directory if dirName
   is 0) for a fossil checkout database file named one of (_FOSSIL_,
   .fslckout).  If it finds one, it returns 0 and appends the file's
   path to pOut if pOut is not 0.  If neither is found AND if
   checkParentDirs is true an then it moves up the path one directory
   and tries again, until it hits the root of the dirPath (see below
   for a note/caveat).

   If dirName is NULL then it behaves as if it had been passed the
   absolute path of the current directory (as determined by
   fsl_getcwd()).

   This function does no normalization of dirName. Because of that...

   Achtung: if dirName is relative, this routine might not find a
   checkout where it would find one if given an absolute path (because
   it traverses the path string given it instead of its canonical
   form). Whether this is a bug or a feature is not yet clear. When in
   doubt, use fsl_file_canonical_name() to normalize the directory
   name before passing it in here. If it turns out that we always want
   that behaviour, this routine will be modified to canonicalize the
   name.

   This routine can return at least the following error codes:

   - FSL_RC_NOT_FOUND: either no checkout db was found or the given
   directory was not found.

   - FSL_RC_RANGE if dirName is an empty string. (We could arguably
   interpret this as a NULL string, i.e. the current directory.)

   - FSL_RC_OOM if allocation of a filename buffer fails.

   TODO?

   - Why was the decision made not to canonicalize dirName from here?
   We might want to change that.

*/
FSL_EXPORT int fsl_ckout_db_search( char const * dirName,
                                    bool checkParentDirs,
                                    fsl_b * const pOut );

/**
   Returns version information for the current checkout.

   If f has an opened checkout then...

   If uuid is not NULL then *uuid is set to the UUID of the opened
   checkout, or NULL if there is no checkout. If rid is not NULL, *rid
   is set to the record ID of that checkout, or 0 if there is no
   checkout (or the current checkout is from an empty repository). The
   returned uuid bytes and rid are owned by f and valid until the
   library updates its checkout state to a newer checkout version
   (essentially unpredictably). When in doubt about lifetime issues,
   copy the UUID immediately after calling this if they will be needed
   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 * const rid,
                                       fsl_uuid_cstr * const uuid );

/**
   If f has an opened checkout, a copy of its current branch name is returned,
   otherwise f's error state is set to to FSL_RC_NOT_A_CKOUT and 0
   is returned.

   Ownership of the returned string is transfered to the caller, who
   must eventually pass it to fsl_free().

   It may return 0 for various errors, e.g. for a db error or
   OOM. fsl_cx_err_code() and friends can be used to determine what
   failed.
 */
FSL_EXPORT char * fsl_ckout_current_branch(fsl_cx * f);

/**
   Given a fsl_cx with an opened checkout, and a file/directory name,
   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.

   As a special case, if zOrigName refers to the top-level checkout
   directory, it resolves to either "." or "./", depending on whether
   zOrigName contains a trailing slash.

   If relativeToCwd is true then the filename is canonicalized
   based on the current working directory (see fsl_getcwd()),
   otherwise f's current checkout directory is used as the virtual
   root.

   If the input name contains a trailing slash, it is retained in
   the output sent to pOut except in the top-dir case mentioned
   above.

   Returns 0 on success, meaning that the value appended to pOut
   (if not NULL) is a syntactically valid checkout-relative path.

   Returns FSL_RC_RANGE if zOrigName points to a path outside
   of f's current checkout root.

   Returns FSL_RC_NOT_A_CKOUT if f has no checkout opened.

   Returns FSL_RC_MISUSE if !zOrigName, FSL_RC_OOM on an allocation
   error.

   This function does not validate whether or not the file actually
   exists, only that its name is potentially valid as a filename
   for use in a checkout (though other, downstream rules might prohibit that, e.g.
   the filename "..../...." is not valid but is not seen as invalid by
   this function). (Reminder to self: we could run the end result through
   fsl_is_simple_pathname() to catch that?)
*/
FSL_EXPORT int fsl_ckout_filename_check( fsl_cx * const f, bool relativeToCwd,
                                         char const * zOrigName, fsl_b * const pOut );

/**
   Convenience typedef and required forward decl.
 */
typedef struct fsl_ckout_manage_opt fsl_ckout_manage_opt;

/**
   State passed to fsl_ckout_manage_f() callback.
*/
struct fsl_ckout_manage_state {
  /**
     The fsl_cx instance for the correspnding fsl_ckout_manage()
     call.
  */
  fsl_cx * f;
  /**
     The options object passed to the corresponding call to
     fsl_ckout_manage(). This is provided primarily for access to
     its callbackState member. The client must never modify any state
     in this opt object other than the callbackState or to use other
     APIs of this->f.
  */
  fsl_ckout_manage_opt const * opt;
  /**
     The name of the file being managed, relative to the root of the
     checkout. fsl_cx_stat2() can be used to transform it to an
     absolute path, if needed. Given a fsl_ckout_manage_state
     named `ms`, that call would look like:

     ```
     fsl_b_reuse(&yourBuffer);
     // ^^^ noting that fsl_cx_stat2() APPENDS to the buffer.
     int rc = fsl_cx_stat2(ms->f, false, ms->filename,
                           NULL, &yourBuffer, true);
     // ^^^ noting that the stat "should not" fail in this case
     // because fsl_ckout_manage() has validated that the file
     // exists.
     ```
  */
  char const * filename;
};

/**
   Convenience typedef.
*/
typedef struct fsl_ckout_manage_state fsl_ckout_manage_state;

/**
   Callback type for use with fsl_ckout_manage_opt(). It should
   inspect the given (`mst->filename`) using whatever criteria it likes, set
   *include to true or false to indicate whether the filename is okay
   to include the current add-file-to-repo operation, and return 0.

   If it returns non-0 the add-file-to-repo process will end and that
   error code will be reported to its caller. Such result codes must
   come from the FSL_RC_xxx family. They may report details of
   the error via fsl_cx_err_set() with the `mst->f` object.

   It will be passed a name which is relative to the top-most checkout
   directory.

   The final argument is not used by the library, but is passed on
   as-is from the fsl_ckout_manage_opt::callbackState pointer which
   is passed to fsl_ckout_manage().
*/
typedef int (*fsl_ckout_manage_f)(fsl_ckout_manage_state const *mst,
                                  bool *include);
/**
   Options for use with fsl_ckout_manage().
*/
struct fsl_ckout_manage_opt {
  /**
     The file or directory name to add. If it is a directory, the add
     process will recurse into it.

     Note that filenames need to be passed in their "proper" case for
     the current platform. fsl_filename_preferred_case() case be used
     to do that, but that functionality is not currently part of the
     fsl_ckout_manage() inner workings (that may change at some
     point). fsl_cx_is_case_sensitive() can be used to determine
     whether or not case-sensitivity is preferred for the current
     repository.
  */
  char const * filename;
  /**
     Whether to evaluate the given name as relative to the current working
     directory or to the current checkout root.

     This makes a subtle yet important difference in how the name is
     resolved. CLI apps which take file names from the user from
     within a checkout directory will generally want to set
     relativeToCwd to true. GUI apps, OTOH, will possibly need it to
     be false, depending on how they resolve and pass on the
     filenames.
  */
  bool relativeToCwd;
  /**
     Whether or not to check the name(s) against the 'ignore-globs'
     config setting (if set).
  */
  bool checkIgnoreGlobs;
  /**
     Optional predicate function which may be called for each
     to-be-added filename. It is only called if:

     - It is not NULL (obviously) and...

     - The file is not already in the checkout database and...

     - The is-internal-name check passes (see
     fsl_reserved_fn_check()) and...

     - If checkIgnoreGlobs is false or the name does not match one of
     the ignore-globs values and...

     - No part of the name's directory part is a symlink or other
     non-directory. As in fossil(1), such files are never added.

     The name it is passed is relative to the checkout root.

     Because the callback is called only if other options have not
     already excluded the file, the client may use the callback to
     report to the user (or otherwise record) exactly which files
     get added.
  */
  fsl_ckout_manage_f callback;

  /**
     State to be passed to this->callback.
  */
  void * callbackState;

  /**
     These counts are updated by fsl_ckout_manage() to report
     what it did.
  */
  struct {
    /**
       Number of files actually added by fsl_ckout_manage().
    */
    uint32_t added;
    /**
       Number of files which were requested to be added but were only
       updated because they had previously been added. An update
       un-deletes the vfile table entry and sets its mtime, but does
       not currently change its executable-bit or is-it-a-symlink
       state. A new entry records both. A symlink is added as a
       symlink if the allow-symlinks setting is on, else as the file
       it points to, as fossil(1) does.
    */
    uint32_t updated;
    /**
       The number of files skipped over for addition. This includes
       files which meet any of these criteria:

       - fsl_reserved_fn_check() fails.

       - If the checkIgnoreGlobs option is true and a filename matches
         any of those globs.

       - Part of the name's directory part is a symlink or other
         non-directory, e.g. "ld/f" where "ld" is a symlink to a
         directory.

       - The client-provided callback says not to include the file.
    */
    uint32_t skipped;
  } counts;
};
/**
   Initialized-with-defaults fsl_ckout_manage_opt instance,
   intended for use in const-copy initialization.
*/
#define fsl_ckout_manage_opt_empty_m {\
    NULL/*filename*/, true/*relativeToCwd*/, true/*checkIgnoreGlobs*/, \
    NULL/*callback*/, NULL/*callbackState*/,                         \
    {/*counts*/ 0/*added*/, 0/*updated*/, 0/*skipped*/}               \
  }
/**
   Initialized-with-defaults fsl_ckout_manage_opt instance,
   intended for use in non-const copy initialization.
*/
FSL_EXPORT const fsl_ckout_manage_opt fsl_ckout_manage_opt_empty;

/**
   Adds the given filename or directory (recursively) to the current
   checkout vfile list of files as a to-be-added file, or updates an
   existing record if one exists.

   This function ensures that opt->filename gets canonicalized and can
   be found under the checkout directory, and fails if no such file
   exists (checking against the canonicalized name). Filenames are all
   filtered through fsl_reserved_fn_check() and may have other filters
   applied to them, as determined by the options object.

   Each filename which passes through the filters is passed to
   the opt->callback (if not NULL), which may perform a final
   filtering check and/or alert the client about the file being
   queued.

   The options object is non-const because this routine updates
   opt->counts when it adds, updates, or skips a file. On each call,
   it updated opt->counts without resetting it (as this function is
   typically called in a loop). This function does not modify any
   other entries of that object and it requires that the object not be
   modified (e.g. via opt->callback()) while it is recursively
   processing. To reset the counts between calls, if needed:

   ```
   opt->counts = fsl_ckout_manage_opt_empty.counts;
   ```

   Returns 0 on success, non-0 on error.

   Files queued for addition this way can be unqueued before they are
   committed using fsl_ckout_unmanage().

   To avoid Significant Grief, this routine automatically skips any
   directories under opt->filename which appear to be fossil checkout
   roots unless that directory is f's current checkout directory, into
   which it will recurse normally.

   @see fsl_ckout_unmanage()
   @see fsl_reserved_fn_check()
*/
FSL_EXPORT int fsl_ckout_manage( fsl_cx * const f,
                                 fsl_ckout_manage_opt * const opt );

/**
   Convenience typedef and required forward decl.
 */
typedef struct fsl_ckout_unmanage_opt fsl_ckout_unmanage_opt;

/**
   State passed to fsl_ckout_unmanage_f() callback.
*/
struct fsl_ckout_unmanage_state {
  /**
     The fsl_cx instance for the correspnding fsl_ckout_unmanage()
     call.
  */
  fsl_cx * f;
  /**
     The options object passed to the corresponding call to
     fsl_ckout_unmanage(). This is provided primarily for access to
     its callbackState member. The client must never modify any state
     in this opt object other than the callbackState or to use other
     APIs of this->f.
  */
  fsl_ckout_unmanage_opt const * opt;
  /**
     The name of the file being unmanaged, relative to the root of the
     checkout. fsl_cx_stat2() can be used to transform it to an
     absolute path, if needed. Given a fsl_ckout_unmanage_state
     named `ums`, that call would look like:

     ```
     fsl_b_reuse(&yourBuffer);
     // ^^^ noting that fsl_cx_stat2() APPENDS to the buffer.
     int rc = fsl_cx_stat2(ums->f, false, ums->filename,
                           NULL, &yourBuffer, true);
     // ^^^ noting that the stat will legitimately and harmlessly
     // fail if the file does not exist, so this error can
     // normally be ignored.
     ```

     Without allow-symlinks, fsl_cx_stat2() follows a symlink, so it
     also fails for a dangling one. A client which wants to unlink
     the file should stat() the link itself instead.
  */
  char const * filename;
};

/** Convenience typedef. */
typedef struct fsl_ckout_unmanage_state fsl_ckout_unmanage_state;


/**
   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").

   If it returns non-0 the unmanage process will end and that error
   code will be reported to its caller. Such result codes must come
   from the FSL_RC_xxx family. They may report details of the error
   via fsl_cx_err_set() with the `ums->f` object.

   The object passed to it will hold the name of the file being
   unmanaged, relative to the top-most checkout directory. The client
   is free to unlink the file from the filesystem if they like - the
   library does not do so automatically
*/
typedef int (*fsl_ckout_unmanage_f)(fsl_ckout_unmanage_state const * ums);

/**
   Options for use with fsl_ckout_unmanage().
*/
struct fsl_ckout_unmanage_opt {
  /**
     The file or directory name to add. If it is a directory, the add
     process will recurse into it. See also this->vfileIds.
  */
  char const * filename;
  /**
     An alternative to assigning this->filename is to point
     this->vfileIds to a bag of vfile.id values. If this member is not
     NULL, fsl_ckout_unmanage() will ignore this->filename.

     @see fsl_filename_to_vfile_ids()
  */
  fsl_id_bag const * vfileIds;
  /**
     Whether to evaluate this->filename as relative to the current
     working directory (true) or to the current checkout root
     (false). This is ignored when this->vfileIds is not NULL.

     This makes a subtle yet important difference in how the name is
     resolved. CLI apps which take file names from the user from
     within a checkout directory will generally want to set
     relativeToCwd to true. GUI apps, OTOH, will possibly need it to
     be false, depending on how they resolve and pass on the
     filenames.
  */
  bool relativeToCwd;
  /**
     If true, fsl_vfile_changes_scan() is called to ensure that
     the filesystem and vfile tables agree. If the client code has
     called that function, or its equivalent, since any changes were
     made to the checkout then this may be set to false to speed up
     the rm process.
  */
  bool scanForChanges;
  /**
     Optional predicate function which will be called after each
     file is made unmanaged.

     The name it is passed is relative to the checkout root.
  */
  fsl_ckout_unmanage_f callback;
  /**
     State to be passed to this->callback.
  */
  void * callbackState;
};
/**
   Initialized-with-defaults fsl_ckout_unmanage_opt instance,
   intended for use in const-copy initialization.
*/
#define fsl_ckout_unmanage_opt_empty_m {\
    NULL/*filename*/, NULL/*vfileIds*/,\
    true/*relativeToCwd*/,true/*scanForChanges*/, \
    NULL/*callback*/, NULL/*callbackState*/ \
}
/**
   Initialized-with-defaults fsl_ckout_unmanage_opt instance,
   intended for use in non-const copy initialization.
*/
FSL_EXPORT const fsl_ckout_unmanage_opt fsl_ckout_unmanage_opt_empty;

/**
   The converse of fsl_ckout_manage(), this queues a file for removal
   from the current checkout. Unlike fsl_ckout_manage(), this routine
   does not ensure that opt->filename actually exists - it only
   normalizes zFilename into its repository-friendly form and passes
   it through the vfile table.

   If opt->filename refers to a directory then this operation queues
   all files under that directory (recursively) for removal. In this
   case, it is irrelevant whether or not opt->filename ends in a
   trailing slash.

   Returns 0 on success, any of a number of non-0 codes on error.
   Returns FSL_RC_MISUSE if !opt->filename or !*opt->filename.
   Returns FSL_RC_NOT_A_CKOUT if f has no opened checkout.

   If opt->callback is not NULL, it is called for each
   newly-unamanaged entry. The intention is to provide it the
   opportunity to notify the user, record the filename for later use,
   remove the file from the filesystem, etc. If it returns non-0, the
   unmanaging process will fail with that code and any pending
   transaction will be placed into a rollback state.

   This routine does not actually remove any files from the
   filesystem, it only modifies the vfile table entry so that the
   file(s) will be removed from the SCM by the commit process. If
   opt->filename is an entry which was previously
   fsl_ckout_manage()'d, but not yet committed, or any such entries
   are found under directory opt->filename, they are removed from the
   vfile table. i.e. this effective undoes the add operation.

   @see fsl_ckout_manage()
*/
FSL_EXPORT int fsl_ckout_unmanage( fsl_cx * f,
                                  fsl_ckout_unmanage_opt const * opt );

/**
   Hard-coded range of values of the vfile.chnged db field.
   These values are part of the fossil schema and must not
   be modified.
*/
enum fsl_vfile_change_e {
  /** File is unchanged. */
  FSL_VFILE_CHANGE_NONE = 0,
  /** File edit. */
  FSL_VFILE_CHANGE_MOD = 1,
  /** File changed due to a merge. */
  FSL_VFILE_CHANGE_MERGE_MOD = 2,
  /** File added by a merge. */
  FSL_VFILE_CHANGE_MERGE_ADD = 3,
  /** File changed due to an integrate merge. */
  FSL_VFILE_CHANGE_INTEGRATE_MOD = 4,
  /** File added by an integrate merge. */
  FSL_VFILE_CHANGE_INTEGRATE_ADD = 5,
  /** File became executable but has unmodified contents. */
  FSL_VFILE_CHANGE_IS_EXEC = 6,
  /** File became a symlink whose target equals its old contents. */
  FSL_VFILE_CHANGE_BECAME_SYMLINK = 7,
  /** File lost executable status but has unmodified contents. */
  FSL_VFILE_CHANGE_NOT_EXEC = 8,
  /** File lost symlink status and has contents equal to its old target. */
  FSL_VFILE_CHANGE_NOT_SYMLINK = 9
};
typedef enum fsl_vfile_change_e fsl_vfile_change_e;

/**
   Change-type flags for use with fsl_ckout_changes_visit() and
   friends.

   TODO: consolidate this with fsl_vfile_change_e insofar as possible.
   There are a few checkout change statuses not reflected in
   fsl_vfile_change_e.
*/
enum fsl_ckout_change_e {
/**
   Sentinel placeholder value.
*/
FSL_CKOUT_CHANGE_NONE = 0,
/**
   Indicates that a file was modified in some unspecified way.
*/
FSL_CKOUT_CHANGE_MOD = FSL_VFILE_CHANGE_MOD,
/**
   Indicates that a file was modified as the result of a merge.
*/
FSL_CKOUT_CHANGE_MERGE_MOD = FSL_VFILE_CHANGE_MERGE_MOD,
/**
   Indicates that a file was added as the result of a merge.
*/
FSL_CKOUT_CHANGE_MERGE_ADD = FSL_VFILE_CHANGE_MERGE_ADD,
/**
   Indicates that a file was modified as the result of an
   integrate-merge.
*/
FSL_CKOUT_CHANGE_INTEGRATE_MOD = FSL_VFILE_CHANGE_INTEGRATE_MOD,
/**
   Indicates that a file was added as the result of an
   integrate-merge.
*/
FSL_CKOUT_CHANGE_INTEGRATE_ADD = FSL_VFILE_CHANGE_INTEGRATE_ADD,
/**
   Indicates that the file gained the is-executable trait
   but is otherwise unmodified.
*/
FSL_CKOUT_CHANGE_IS_EXEC = FSL_VFILE_CHANGE_IS_EXEC,
/**
   Indicates that the file has changed to a symlink.
*/
FSL_CKOUT_CHANGE_BECAME_SYMLINK = FSL_VFILE_CHANGE_BECAME_SYMLINK,
/**
   Indicates that the file lost the is-executable trait
   but is otherwise unmodified.
*/
FSL_CKOUT_CHANGE_NOT_EXEC = FSL_VFILE_CHANGE_NOT_EXEC,
/**
   Indicates that the file was previously a symlink but is
   now a plain file.
*/
FSL_CKOUT_CHANGE_NOT_SYMLINK = FSL_VFILE_CHANGE_NOT_SYMLINK,
/**
   Indicates that a file was added.
*/
FSL_CKOUT_CHANGE_ADDED = FSL_CKOUT_CHANGE_NOT_SYMLINK + 1000,
/**
   Indicates that a file was removed from SCM management.
*/
FSL_CKOUT_CHANGE_REMOVED,
/**
   Indicates that a file is missing from the local checkout.
*/
FSL_CKOUT_CHANGE_MISSING,
/**
   Indicates that a file was renamed.
*/
FSL_CKOUT_CHANGE_RENAMED,
/**
   Indicates that the name of a managed file exists in the local
   checkout but is neither a file nor a symlink, e.g. it is a
   directory. With the allow-symlinks setting off, a symlink to a
   directory falls into this category. A dangling symlink is
   reported as FSL_CKOUT_CHANGE_MISSING. This corresponds to
   fossil(1)'s NOT_A_FILE status.
*/
FSL_CKOUT_CHANGE_NOT_A_FILE
};

typedef enum fsl_ckout_change_e fsl_ckout_change_e;

/**
   This is equivalent to calling fsl_vfile_changes_scan() with the
   arguments (f, -1, 0).

   @see fsl_ckout_changes_visit()
   @see fsl_vfile_changes_scan()
*/
FSL_EXPORT int fsl_ckout_changes_scan(fsl_cx * f);

/**
   A typedef for visitors of checkout status information via
   fsl_ckout_changes_visit(). Implementions will receive the
   last argument passed to fsl_ckout_changes_visit() as their
   first argument. The second argument indicates the type of change
   and the third holds the repository-relative name of the file.

   If changes is FSL_CKOUT_CHANGE_RENAMED then origName will hold
   the original name, else it will be NULL.

   Implementations must return 0 on success, non-zero on error. On
   error any looping performed by fsl_ckout_changes_visit() will
   stop and this function's result code will be returned.

   @see fsl_ckout_changes_visit()
*/
typedef int (*fsl_ckout_changes_f)(void * state, fsl_ckout_change_e change,
                                      char const * filename,
                                      char const * origName);

/**
   Compares the changes of f's local checkout against repository
   version vid (checkout version if vid is negative). For each
   change detected it calls visitor(state,...) to report the
   change.  If visitor() returns non-0, that code is returned from
   this function. If doChangeScan is true then
   fsl_ckout_changes_scan() is called by this function before
   iterating, otherwise it is assumed that the caller has called
   that or has otherwise ensured that the checkout db's vfile table
   has been populated.

   If the callback returns FSL_RC_BREAK, this function stops iteration
   and returns 0.

   Returns 0 on success.

   @see fsl_ckout_changes_scan()
*/
FSL_EXPORT int fsl_ckout_changes_visit( fsl_cx * f, fsl_id_t vid,
                                           bool doChangeScan,
                                           fsl_ckout_changes_f visitor,
                                           void * state );
/**
   A bitmask of flags for fsl_vfile_changes_scan().
*/
enum fsl_ckout_sig_e {
/**
   The empty flags set.
*/
FSL_VFILE_CKSIG_NONE = 0,

/**
   Non-file/non-link FS objects trigger an error.
*/
FSL_VFILE_CKSIG_ENOTFILE = 0x001,
/**
   Verify file content using hashing, regardless of whether or not
   file timestamps differ.
*/
FSL_VFILE_CKSIG_HASH = 0x002,
/**
   For unchanged or changed-by-merge files, set the mtime to last
   check-out time, as determined by fsl_mtime_of_manifest_file().
*/
FSL_VFILE_CKSIG_SETMTIME = 0x004,
/**
   Indicates that when populating the vfile table, it should be not be
   cleared of entries for other checkins. Normally we want to clear
   all versions except for the one we're working with, but at least
   a couple of use cases call for having multiple versions in vfile at
   once. Many algorithms generally assume only a single checkin's
   worth of state is in vfile and can get confused if that is not the
   case.
*/
FSL_VFILE_CKSIG_KEEP_OTHERS = 0x008,
/**
   If set and fsl_vfile_changes_scan() is passed a version other than
   the pre-call checkout version, it will, when finished, write the
   given version in the "checkout" setting of the ckout.vvar table,
   effectively switching the checkout to that version. It does not do
   this by default because it is sometimes necessary to have two
   versions in the vfile table at once and the operation doing so
   needs to control which version number is the current checkout.
*/
FSL_VFILE_CKSIG_WRITE_CKOUT_VERSION = 0x010
};

/**
    This function populates (if needed) the vfile table of f's
    checkout db for the given checkin version ID then compares files
    listed in it against files in the checkout directory, updating
    vfile's status for the current checkout version id as its goes. If
    vid is<=0 then the current checkout's RID is used in its place
    (note that 0 is the RID of an initial empty repository!).

    cksigFlags must be 0 or a bitmask of fsl_ckout_sig_e values.

    This is a relatively memory- and filesystem-intensive operation,
    and should not be performed more often than necessary. Many SCM
    algorithms rely on its state being correct, however, so it's
    generally better to err on the side of running it once too often
    rather than once too few times.

    Returns 0 on success, non-0 on error.

    BUG: this does not properly catch one particular corner-case
    change, where a file has been replaced by a same-named non-file
    (symlink or directory).
*/
FSL_EXPORT int fsl_vfile_changes_scan(fsl_cx * const f, fsl_id_t vid,
                                      unsigned cksigFlags);

/**
   If f has an opened checkout which has local changes noted in its
   checkout db state (the vfile table), returns true, else returns
   false. Note that this function does not do the filesystem scan to
   check for changes, but checks only the db state. Use
   fsl_vfile_changes_scan() to perform the actual scan (noting that
   library-side APIs which update that state may also record
   individual changes or automatically run a scan).
*/
FSL_EXPORT bool fsl_ckout_has_changes(fsl_cx * const f);

/**
   Callback type for use with fsl_checkin_queue_opt for alerting a
   client about exactly which files get enqueued/dequeued via
   fsl_checkin_enqueue() and fsl_checkin_dequeue().

   This function gets passed the checkout-relative name of the file
   being enqueued/dequeued and the client-provided state pointer which
   was passed to the relevant API. It must return 0 on success. If it
   returns non-0, the API on whose behalf this callback is invoked
   will propagate that error code back to the caller.

   The intent of this callback is simply to report changes to the
   client, not to perform validation. Thus such callbacks "really
   should not fail" unless, e.g., they encounter an OOM condition or
   some such. Any validation required by the client should be
   performed before calling fsl_checkin_enqueue()
   resp. fsl_checkin_dequeue().
*/
typedef int (*fsl_checkin_queue_f)(const char * filename, void * state);

/**
   Options object type used by fsl_checkin_enqueue() and
   fsl_checkin_dequeue().
*/
struct fsl_checkin_queue_opt {
  /**
     File or directory name to enqueue/dequeue to/from a pending
     checkin.
  */
  char const * filename;
  /**
     If true, filename (if not absolute) is interpreted as relative to
     the current working directory, else it is assumed to be relative
     to the top of the current checkout directory.
  */
  bool relativeToCwd;

  /**
     If not NULL then this->filename and this->relativeToCwd are
     IGNORED and any to-queue filename(s) is/are added from this
     container. It is an error (FSL_RC_MISUSE) to pass an empty bag.
     (Should that be FSL_RC_RANGE instead?)

     The bag is assumed to contain values from the vfile.id checkout
     db field, refering to one or more files which should be queued
     for the pending checkin. It is okay to pass IDs for unmodified
     files or to queue the same files multiple times. Unmodified files
     may be enqueued but will be ignored by the checkin process if, at
     the time the checkin is processed, they are still unmodified.
     Duplicated entries are simply ignored for the 2nd and subsequent
     inclusion.

     @see fsl_ckout_vfile_ids()
  */
  fsl_id_bag const * vfileIds;

  /**
     If true, fsl_vfile_changes_scan() is called to ensure that the
     filesystem and vfile tables agree. If the client code has called
     that function, or its equivalent, since any changes were made to
     the checkout then this may be set to false to speed up the
     enqueue process. This is only used by fsl_checkin_enqueue(), not
     fsl_checkin_dequeue().
  */
  bool scanForChanges;

  /**
     If true, only flagged-as-modified files will be enqueued by
     fsl_checkin_enqueue(). By and large, this should be set to
     true. Setting this to false is generally only intended/useful for
     testing.
  */
  bool onlyModifiedFiles;

  /**
     It not NULL, is pass passed the checkout-relative filename of
     each enqueued/dequeued file and this->callbackState. See the
     callback type's docs for more details.
  */
  fsl_checkin_queue_f callback;

  /**
     Opaque client-side state for use as the 2nd argument to
     this->callback.
  */
  void * callbackState;

  /* TODO (2023-02-02): any state necessary for indicating that this
     checking should be flagged as "private".
   */
};

/** Convenience typedef. */
typedef struct fsl_checkin_queue_opt fsl_checkin_queue_opt;

/** Initialized-with-defaults fsl_checkin_queue_opt structure, intended for
    const-copy initialization. */
#define fsl_checkin_queue_opt_empty_m { \
  NULL/*filename*/,true/*relativeToCwd*/,    \
  NULL/*vfileIds*/,                                 \
  true/*scanForChanges*/,true/*onlyModifiedFiles*/,   \
  NULL/*callback*/,NULL/*callbackState*/      \
}

/** Initialized-with-defaults fsl_checkin_queue_opt structure, intended for
    non-const copy initialization. */
extern const fsl_checkin_queue_opt fsl_checkin_queue_opt_empty;

/**
   Adds one or more files to f's list of "selected" files - those
   which should be included in the next commit (see
   fsl_checkin_commit()).

   Warning: if this function is not called before
   fsl_checkin_commit(), then fsl_checkin_commit() will select all
   modified, fsl_ckout_manage()'d, fsl_ckout_unmanage()'d, or renamed
   files by default.

   opt->filename must be a non-empty NUL-terminated string. The
   filename is canonicalized via fsl_ckout_filename_check() - see that
   function for the meaning of the opt->relativeToCwd parameter. To
   queue all modified files in a checkout, set opt->filename to ".",
   opt->relativeToCwd to false, and opt->onlyModifiedFiles to true.
   "Modified" includes any which are pending deletion, are
   newly-added, or for which a rename is pending.

   The resolved name must refer to either a single vfile.pathname
   value in the current vfile table or to a checkout-root-relative
   directory. All matching filenames which refer to modified files (as
   recorded in the vfile table) are queued up for the next commit.
   If opt->filename is NULL, empty, or ("." and opt->relativeToCwd is false)
   then all files in the vfile table are checked for changes.

   If opt->scanForChanges is true then fsl_vfile_changes_scan() is
   called before starting to ensure that the vfile entries are up to
   date. If the client app has "recently" run that (or its
   equivalent), that (slow) step can be skipped by setting
   opt->scanForChanges to false before calling this

   Note that after this returns, any given file may still be modified
   by the client before the commit takes place, and the changes on
   disk at the point of the fsl_checkin_commit() are the ones which
   get saved (or not).

   For each resolved entry which actually gets enqueued (i.e. was not
   already enqueued and which is marked as modified), opt->callback
   (if it is not NULL) is passed the checkout-relative file name and
   the opt->callbackState pointer.

   Returns 0 on success, FSL_RC_MISUSE if either pointer is NULL, or
   *zName is NUL. Returns FSL_RC_OOM on allocation error. It is not
   inherently an error for opt->filename to resolve to no queue-able
   entries. A client can check for that case, if needed, by assigning
   opt->callback and incrementing a counter in that callback. If the
   callback is never called, no queue-able entries were found.

   On error f's error state might (depending on the nature of the
   problem) contain more details.

   @see fsl_checkin_is_enqueued()
   @see fsl_checkin_dequeue()
   @see fsl_checkin_discard()
   @see fsl_checkin_commit()
*/
FSL_EXPORT int fsl_checkin_enqueue(fsl_cx * f,
                                   fsl_checkin_queue_opt const * opt);

/**
   The opposite of fsl_checkin_enqueue(), this opt->filename,
   which may resolve to a single name or a directory, from the checkin
   queue. Returns 0 on succes. This function does no validation on
   whether a given file(s) actually exist(s), it simply asks the
   internals to clean up matching strings from the checkout's vfile
   table. Specifically, it does not return an error if this operation
   finds no entries to dequeue.

   If opt->filename is empty or NULL then ALL files are unqueued from
   the pending checkin.

   If opt->relativeToCwd is true (non-0) then opt->filename is
   resolved based on the current directory, otherwise it is resolved
   based on the checkout's root directory.

   If opt->filename is not NULL or empty, this functions runs the
   given path through fsl_ckout_filename_check() and will fail if that
   function fails, propagating any error from that function. Ergo,
   opt->filename must refer to a path within the current checkout.

   @see fsl_checkin_enqueue()
   @see fsl_checkin_is_enqueued()
   @see fsl_checkin_discard()
   @see fsl_checkin_commit()
*/
FSL_EXPORT int fsl_checkin_dequeue(fsl_cx * const f,
                                   fsl_checkin_queue_opt const * opt);

/**
   Returns true if the file named by zName is in f's current file
   checkin queue. If NO files are in the current selection queue then
   this routine assumes that ALL files are implicitely selected. As
   long as at least one file is enqueued (via fsl_checkin_enqueue())
   then this function only returns true for files which have been
   explicitly enqueued.

   If relativeToCwd then zName is resolved based on the current
   directory, otherwise it assumed to be related to the checkout's
   root directory.

   This function returning true does not necessarily indicate that
   the file _will_ be checked in at the next commit. If the file has
   not been modified at commit-time then it will not be part of the
   commit.

   This function honors the fsl_cx_is_case_sensitive() setting
   when comparing names.

   Achtung: this does not resolve directory names like
   fsl_checkin_enqueue() and fsl_checkin_dequeue() do. It
   only works with file names.

   Results are undefined if f is NULL.

   @see fsl_checkin_enqueue()
   @see fsl_checkin_dequeue()
   @see fsl_checkin_discard()
   @see fsl_checkin_commit()
*/
FSL_EXPORT bool fsl_checkin_is_enqueued(fsl_cx * const f,
                                        char const * zName,
                                        bool relativeToCwd);

/**
   Discards any state accumulated for a pending checking,
   including any files queued via fsl_checkin_enqueue()
   and tags added via fsl_checkin_T_add().

   @see fsl_checkin_enqueue()
   @see fsl_checkin_dequeue()
   @see fsl_checkin_is_enqueued()
   @see fsl_checkin_commit()
   @see fsl_checkin_T_add()
*/
FSL_EXPORT void fsl_checkin_discard(fsl_cx * const f);

/**
   Parameters for fsl_checkin_commit().

   Checkins are created in a multi-step process:

   - fsl_checkin_enqueue() queues up a file or directory for
   commit at the next commit.

   - fsl_checkin_dequeue() removes an entry, allowing
   UIs to toggle files in and out of a checkin before
   committing it.

   - fsl_checkin_is_enqueued() can be used to determine whether
   a given name is already enqueued or not.

   - fsl_checkin_T_add() can be used to T-cards (tags) to a
   deck. Branch tags are intended to be applied via the
   fsl_checkin_opt::branch member.

   - fsl_checkin_discard() can be used to cancel any pending file
   enqueuings, effectively cancelling a commit (which can be
   re-started by enqueuing another file).

   - fsl_checkin_commit() creates a checkin for the list of enqueued
   files (defaulting to all modified files in the checkout!). It
   takes an object of this type to specify a variety of parameters
   for the check.

   Note that this API uses the terms "enqueue" and "unqueue" rather
   than "add" and "remove" because those both have very specific
   (and much different) meanings in the overall SCM scheme.
*/
struct fsl_checkin_opt {
  /**
     The commit message. May not be empty - the library
     forbids empty checkin messages. It must be valid UTF-8:
     fsl_checkin_commit() fails with FSL_RC_RANGE otherwise.
  */
  char const * message;

  /**
     The optional mime type for the message. Only set
     this if you know what you're doing.
  */
  char const * messageMimeType;

  /**
     The user name for the checkin. If NULL or empty, it defaults to
     fsl_cx_user_get(). If that is NULL, a FSL_RC_RANGE error is
     triggered.
  */
  char const * user;

  /**
     If not NULL, makes the checkin the start of a new branch with
     this name.
  */
  char const * branch;

  /**
     If this->branch is not NULL, this is applied as its "bgcolor"
     propagating property. If this->branch is NULL then this is
     applied as a one-time color tag to the checkin.

     It must be NULL, empty, or in a form usable by HTML/CSS,
     preferably \#RRGGBB form. Length-0 values are ignored (as if
     they were NULL).
  */
  char const * bgColor;

  /**
     If true, the checkin will be marked as private, otherwise it
     will be marked as private or public, depending on whether or
     not it inherits private content.
  */
  bool isPrivate;

  /**
     Whether or not to calculate an R-card. Doing so is very
     expensive (memory and I/O) but it adds another layer of
     consistency checking to manifest files. In practice, the R-card
     is somewhat superfluous and the cost of calculating it has
     proven painful on very large repositories. fossil(1) creates an
     R-card for all checkins but does not require that one be set
     when it reads a manifest.
  */
  bool calcRCard;

  /**
     Tells the checkin to close merged-in branches (merge type of
     0). INTEGRATE merges (type=-4) are always closed by a
     checkin. This does not apply to CHERRYPICK (type=-1) and
     BACKOUT (type=-2) merges.
  */
  bool integrate;

  /**
     If true, allow a file to be checked in if it contains
     fossil-style merge conflict markers, else fail if an attempt is
     made to commit any files with such markers.
  */
  bool allowMergeConflict;

  /**
     A hint to fsl_checkin_commit() about whether it needs to scan the
     checkout for changes. Set this to false ONLY if the calling code
     calls fsl_ckout_changes_scan() (or equivalent,
     e.g. fsl_vfile_changes_scan()) immediately before calling
     fsl_checkin_commit(). fsl_checkin_commit() requires a non-stale
     changes scan in order to function properly, but it's a
     computationally slow operation so the checkin process does not
     want to duplicate it if the application has recently done so.
  */
  bool scanForChanges;

  /**
     NOT YET IMPLEMENTED! TODO!

     If true, files which are removed from the SCM by this checkin
     should be removed from the filesystem.

     Reminder to self: when we do this, incorporate
     fsl_rm_empty_dirs().
  */
  bool rmRemovedFiles;

  /**
     If true, the checkin's db savepoint is rolled back after it's
     complete, effectively meaning that the checkin does not take
     place (but all of the work involved happens). This unfortunately
     has to put any pending transactions into pending-rollback mode,
     too, because of $REASONS.
  */
  bool dryRun;

  /**
     Warning: use of delta manifests is not recommended by Fossil's
     current (2026) primary maintainers, and has not been for many
     years.

     Whether to allow (or try to force) a delta manifest or not. 0
     means no deltas allowed - it will not generate a baseline
     manifest. Greater than 0 forces generation of a delta if
     possible (if one can be readily found) even if doing so would not
     save a notable amount of space. Less than 0 means to
     decide via some heuristics.

     A "readily available" baseline means either the current checkout
     is a baseline or has a baseline. In either case, we can use that
     as a baseline for a delta. i.e. a baseline "should" generally be
     available except on the initial checkin, which has neither a
     parent checkin nor a baseline.

     The current behaviour for "auto-detect" mode is: it will generate
     a delta if a baseline is "readily available" _and_ the repository
     has at least one delta already. Once it calculates a delta form,
     it calculates whether that form saves any appreciable
     space/overhead compared to whether a baseline manifest was
     generated. If so, it discards the delta and re-generates the
     manifest as a baseline. The "force" behaviour (deltaPolicy>0)
     bypasses the "is it too big?" test, and is only intended for
     testing, not real-life use.

     Caveat: if the repository has the "forbid-delta-manifests" set to
     a true value, this option is ignored: that setting takes
     priority. Similarly, it will not create a delta in a repository
     unless a delta has been "seen" in that repository before or this
     policy is set to >0. When a checkin is created with a delta
     manifest, that fact gets recorded in the repository's config
     table.

     CAVEAT: delta manifests have some advantages and may not actually
     save much (if any) repository space because the lower-level delta
     framework already compresses parent versions of artifacts
     tightly. For more information see:

     https://fossil-scm.org/home/doc/tip/www/delta-manifests.md
  */
  int deltaPolicy;

  /**
     Time of the checkin. If 0 or less, the time of the
     fsl_checkin_commit() call is used.
  */
  double julianTime;

  /**
     If false, fsl_checkin_commit() fails with FSL_RC_RANGE if the
     check-in's time (see julianTime) is earlier than that of its
     parent or of any merge parent, as fossil(1) commit does without
     --allow-older. If true, it allows that check-in.
  */
  bool allowOlder;

  /**
     If this is not NULL then the committed manifest will include a
     tag which closes the branch. The value of this string will be
     the value of the "closed" tag, and the value may be an empty
     string. The intention is that this gets set to a comment about
     why the branch is closed, but it is in no way mandatory.
  */
  char const * closeBranch;

  /**
     Tells fsl_checkin_commit() to dump the generated manifest to
     this file. Intended only for debugging and testing. Checking in
     will fail if this file cannot be opened for writing.
  */
  char const * dumpManifestFile;
  /*
    fossil(1) has many more options. We might want to wrap some of
    it up in the "incremental" state (f->ckin.mf).

    TODOs:

    A callback mechanism which supports the user cancelling
    the checkin. It is (potentially) needed for ops like
    confirming the commit of CRNL-only changes.

    2021-03-09: we now have fsl_confirmer for this but currently no
    part of the checkin code needs a prompt.
  */
};

/**
   Empty-initialized fsl_checkin_opt instance, intended for use in
   const-copy constructing.
*/
#define fsl_checkin_opt_empty_m {               \
  .message = NULL,                            \
  .messageMimeType = NULL,                  \
  .user = NULL,                             \
  .branch = NULL,                           \
  .bgColor = NULL,                          \
  .isPrivate = false,                           \
  .calcRCard = true,                           \
  .integrate = false,                           \
  .allowMergeConflict = false,\
  .scanForChanges = true,\
  .rmRemovedFiles = false,\
  .dryRun = false, \
  .deltaPolicy = 0,                        \
  .julianTime = 0.0,                        \
  .allowOlder = false,                      \
  .closeBranch = NULL,                      \
  .dumpManifestFile = NULL               \
}

/**
   Empty-initialized fsl_checkin_opt instance, intended for use in
   copy-constructing. It is important that clients copy this value
   (or fsl_checkin_opt_empty_m) to cleanly initialize their
   fsl_checkin_opt instances, as this may set default values which
   (e.g.) a memset() would not.
*/
FSL_EXPORT const fsl_checkin_opt fsl_checkin_opt_empty;

/**
   This creates and saves a "checkin manifest" for the current
   checkout.

   Its primary inputs is a list of files to commit. This list is
   provided by the client by calling fsl_checkin_enqueue() one or
   more times.  If no files are explicitely selected (enqueued) then
   it calculates which local files have changed vs the current
   checkout and selects all of those.

   Non-file inputs are provided via the opt parameter.

   As in fossil(1), except on Windows, the permissions (executable
   bit or symlink) of each selected file are taken from the
   filesystem. Those of unselected files, and on Windows those of all
   files, are carried over from the current checkout version. With
   the allow-symlinks setting on (fsl_cx_allows_symlinks()), a
   symlink is committed as a symlink, its content being the name it
   points to, and is not checked for merge conflict markers. With the
   setting off, a symlink is followed and committed as the file it
   points to.

   On success, it returns 0 and...

   - If newRid is not NULL, it is assigned the new checkin's RID
   value.

   - If newUuid is not NULL, it is assigned the new checkin's UUID
   value. Ownership of the bytes is passed to the caller, who must
   eventually pass them to fsl_free() to free them.

   Note that the new RID and UUID can also be fetched afterwards by
   calling fsl_ckout_version_info().

   On error non-0 is returned and f's error state may (depending on
   the nature of the problem) contain details about the problem.
   Note, however, that any error codes returned here may have arrived
   from several layers down in the internals, and may not have a
   single specific interpretation here. When possible/practical, f's
   error state gets updated with a human-readable description of the
   problem.

   opt->dryRun: does not work properly, at least partially due to
   stale internal caches.

   ACHTUNG: all pending checkin state is cleared by this function
   unless it fails basic argument validation. This means any queued
   files or tags need to be re-applied if the client wants to try
   again. That is somewhat of a bummer, but this behaviour is the only
   way we can ensure that then the pending checkin state does not get
   garbled on a second use. When in doubt about the state, the client
   should call fsl_checkin_discard() to clear it before try to
   re-commit. (Potential TODO: add a success/fail state flag to the
   checkin state and only clean up on success? OTOH, since something
   in the state likely caused the problem, we might not want to do
   that.)

   Some of the more notable, potentially not obvious, error
   conditions:

   - Trying to commit against a closed leaf: FSL_RC_ACCESS. Doing so
   is not permitted by fossil(1), so we disallow it here.

   - An empty/NULL user name or commit message: FSL_RC_MISSING_INFO.
   In these cases f's error state describes the problem.

   - Only some of the files changed by a pending merge are enqueued:
   FSL_RC_MISUSE.

   - Some resource is not found (e.g. an expected RID/UUID could not
   be resolved): FSL_RC_NOT_FOUND. This would generally indicate
   some sort of data consistency problem. i.e. it's quite possibly
   very bad if this is returned.

   - If no enqueued file actually changed, or the checkin would
   result in no file-level changes vis-a-vis the current checkout,
   FSL_RC_NOOP is returned.

   BUGS:

   - It cannot currently properly distinguish a "no-op" commit, one in
   which no files were modified or only their permissions were
   modifed.

   TODO:

   - Honor the opt->dryRun flag. Getting this working has proven tricky
     because of stale cache issues.

   @see fsl_checkin_enqueue()
   @see fsl_checkin_dequeue()
   @see fsl_checkin_discard()
   @see fsl_checkin_T_add()
*/
FSL_EXPORT int fsl_checkin_commit(fsl_cx * f, fsl_checkin_opt const * opt,
                                  fsl_id_t * newRid, fsl_uuid_str * newUuid);

/**
   Works like fsl_deck_T_add(), adding the given tag information to
   the pending checkin state. Returns 0 on success, non-0 on error. A
   checkin may, in principal, have any number of tags, and this may be
   called any number of times to add new tags to the pending
   commit. This list of tags gets cleared by a successful
   fsl_checkin_commit() or by fsl_checkin_discard(). Decks require
   that each tag be distinct from each other (none may compare
   equivalent), but that check is delayed until the deck is output
   into its final artifact form.

   @see fsl_checkin_enqueue()
   @see fsl_checkin_dequeue()
   @see fsl_checkin_commit()
   @see fsl_checkin_discard()
   @see fsl_checkin_T_add2()
*/
FSL_EXPORT int fsl_checkin_T_add( fsl_cx * f, fsl_tagtype_e tagType,
                                   fsl_uuid_cstr uuid, char const * name,
                                   char const * value);

/**
   Works identically to fsl_checkin_T_add() except that it takes its
   argument in the form of a T-card object.

   On success ownership of t is passed to mf. On error (see
   fsl_deck_T_add()) ownership is not modified.

   Results are undefined if either argument is NULL or improperly
   initialized.
*/
FSL_EXPORT int fsl_checkin_T_add2( fsl_cx * f, fsl_card_T * t );

/**
   Clears all contents from f's checkout database, including the vfile
   table, vmerge table, and some of the vvar table. The tables are
   left intact. Returns 0 on success, non-0 if f has no checkout or for
   a database error.
*/
FSL_EXPORT int fsl_ckout_clear_db(fsl_cx *f);

/**
   Returns the base name of the current platform's checkout database
   file. That is "_FOSSIL_" on Windows and ".fslckout" everywhere
   else. The returned bytes are static.

   TODO: an API which takes a dir name and looks for either name
*/
FSL_EXPORT char const *fsl_preferred_ckout_db_name(void);

/**
   File-overwrite policy values for use with fsl_ckup_opt and friends.
*/
enum fsl_file_overwrite_policy_e {
/** Indicates that an error should be triggered if a file would be
    overwritten. */
FSL_OVERWRITE_ERROR = 0,
/**
   Indicates that files should always be overwritten.
*/
FSL_OVERWRITE_ALWAYS,
/**
   Indicates that files should never be overwritten, and silently
   skipped over. This is almost never what one wants to do.
*/
FSL_OVERWRITE_NEVER
};
typedef enum fsl_file_overwrite_policy_e fsl_file_overwrite_policy_e;

/**
   State values for use with fsl_ckup_state::fileRmInfo.
*/
enum fsl_ckup_rm_state_e {
/**
   Indicates that the file was not removed in a given checkout.
   Guaranteed to have the value 0 so that it is treated as boolean
   false. No other entries in this enum have well-defined values.
*/
FSL_CKUP_RM_NOT = 0,
/**
   Indicates that a file was removed from a checkout but kept
   in the filesystem because it was locally modified.
*/
FSL_CKUP_RM_KEPT,
/**
   Indicates that a file was removed from a checkout and the
   filesystem, with the caveat that failed attempts to remove from the
   filesystem are ignored for Reasons but will be reported as if the
   unlink worked.
*/
FSL_CKUP_RM
};
typedef enum fsl_ckup_rm_state_e fsl_ckup_rm_state_e;

/**
  Under construction. Work in progress...

  Options for "opening" a fossil repository database. That is,
  creating a new fossil checkout database and populating its schema,
  _without_ checking out any files. (That latter part is up for
  reconsideration and this API might change in the future to check
  out files after creating/opening the db.)
*/
struct fsl_repo_open_ckout_opt {
  /**
     Name of the target directory, which must already exist (in the
     context's checkout storage, if one is installed: see
     fsl_cx_ckout_fs()). May be relative to the current directory,
     e.g. ".". May be NULL, in which case the current directory is
     assumed. The current directory is not changed.
  */
  char const * targetDir;

  /**
     The filename, with no directory components, of the desired
     checkout db name, which is resolved relative to targetDir. An
     absolute name is used as is. For the time being, always leave this NULL and
     let the library decide. It "might" (but probably won't) be
     interesting at some point to allow the client to specify a
     different name (noting that that would be directly incompatible
     with fossil(1)).
  */
  char const * ckoutDbFile;

  /**
     Policy for how to handle overwrites of files extracted from a
     newly-opened checkout.

     Potential TODO: replace this with a fsl_confirmer, though that
     currently seems like overkill for this particular case.
  */
  fsl_file_overwrite_policy_e fileOverwritePolicy;

  /**
     fsl_repo_open_ckout() installs the fossil checkout schema. If
     this is true it will forcibly replace any existing relevant
     schema components in the checkout db, otherwise it will fail when
     it tries to overwrite an existing schema and cannot.
  */
  bool dbOverwritePolicy;

  /**
     If true, the checkout-open process will look for an opened
     checkout in the target directory and its parents (recursively)
     and fail with FSL_RC_ALREADY_EXISTS if one is found.
  */
  bool checkForOpenedCkout;

  /**
     If not NULL, the checkout's tables (vvar, vfile, vmerge, stash,
     stashfile, the fsl_undo tables, ...) are not kept in a checkout
     db of their own but are tables of the host's main db whose names
     start with this prefix, e.g. "fslwc_work_" makes
     main.fslwc_work_vfile. Nothing is ATTACHed for the checkout, and
     the host's own tables, including any named like checkout tables
     without the prefix, are not touched. This lets one host db hold
     several working copies, each with a prefix of its own, alongside
     the host's own tables.

     Only for a context bound to a host db handle (fsl_cx_host_db())
     whose repository is opened, and whose main db is a file, so that
     a check-in commits to it and the repository together. Otherwise
     fsl_repo_open_ckout() fails with FSL_RC_MISUSE resp.
     FSL_RC_UNSUPPORTED. ckoutDbFile must then be NULL. The prefix
     must match [A-Za-z_][A-Za-z0-9_]*, so that the prefixed names are
     identifiers without quoting, and must not start with "sqlite_"
     (in any case), else FSL_RC_RANGE.

     The prefix is the working copy's namespace: since some checkout
     table names end in others (fsl_undo_vfile, old_stash), and some
     tables (the stash's and undo's) are only created when first used,
     a prefix may neither be the start of another working copy's or a
     repository's (fsl_repo_open_host()) nor start with one, ignoring
     case (FSL_RC_ALREADY_EXISTS). That holds for the prefixes of other
     contexts on the same handle, for that of this context's
     repository, and for those of the working copies and repositories
     recorded in the main db (each P for which it has tables Pvfile and
     Pvvar, the latter with a 'ckout-root' row, resp. Pblob and Pconfig,
     the latter with a 'content-schema' row).

     If the main db has this prefix's vvar table, the working copy is
     reopened. Its vfile and vmerge tables must exist (else
     FSL_RC_CONSISTENCY), it must belong to this repository by
     project-code, and its version's rid must have the hash it recorded
     there, which a clone (the same project-code, other rids) need not
     (else FSL_RC_REPO_MISMATCH; a repository which was moved reopens,
     and its new file name is recorded, the only write of a reopen),
     and targetDir must be its directory, compared with symbolic links
     resolved and, where file names are case-insensitive
     (fsl_cx_is_case_sensitive()), without regard to case (else
     FSL_RC_MISUSE). targetDir need not be
     empty, nothing is created, and the checkout's state (its version,
     ignore lists, ...) is loaded as for fsl_ckout_open_dir().
     Otherwise a new working copy is created, in one transaction which
     holds the main db's write lock from before its checks, and the
     main db may then have no table, index or trigger whose name
     starts with the prefix (ignoring case), else
     FSL_RC_ALREADY_EXISTS: so it never adopts or drops a table of the
     host's or of another working copy. Its vvar records the
     repository's file name ("repository"; for a repository in the
     host db, see fsl_repo_open_host()) and project-code
     ("project-code") and the checkout's directory ("ckout-root").
     dbOverwritePolicy must be false (else FSL_RC_MISUSE): to start a
     working copy afresh, drop its tables first.

     The checkout's directory is targetDir as given (it is not derived
     from a db file's name), which must exist in the checkout's
     storage (fsl_cx_ckout_fs()). fsl_cx_db_file_ckout() then returns
     the main db's file name, and that file and its -journal, -wal and
     -shm files, however they are spelled through symbolic links, are
     reserved names (fsl_reserved_fn_check()). The main
     db's settings are left as they are: its application_id is not
     set, and its journal mode is not changed (a check-in fails if it
     is not a rollback journal mode). Closing the checkout drops none
     of the tables.

     The schema's REFERENCES clauses name the prefixed tables, but
     foreign keys are not enforced: libfossil requires PRAGMA
     foreign_keys=OFF on a host's handle.
  */
  char const * hostTablePrefix;
};
typedef struct fsl_repo_open_ckout_opt fsl_repo_open_ckout_opt;

/**
  Empty-initialized fsl_repo_open_ckout_opt const-copy constructer.
*/
#define fsl_repo_open_ckout_opt_m { \
  NULL/*targetDir*/, NULL/*ckoutDbFile*/, \
  FSL_OVERWRITE_ERROR/*fileOverwritePolicy*/, \
  false/*dbOverwritePolicy*/,               \
  -1/*checkForOpenedCkout*/,             \
  NULL/*hostTablePrefix*/                \
}

/**
  Empty-initialised fsl_repo_open_ckout_opt instance. Clients should copy
  this value (or fsl_repo_open_ckout_opt_empty_m) to initialise
  fsl_repo_open_ckout_opt instances for sane default values.
*/
FSL_EXPORT const fsl_repo_open_ckout_opt fsl_repo_open_ckout_opt_empty;

/**
   Opens a checkout db for use with the currently-connected repository
   or creates a new checkout db. If opening an existing one, it gets
   "stolen" from any repository it might have been previously mapped
   to.

   - Requires that f have an opened repository db and no opened
     checkout. Returns FSL_RC_NOT_A_REPO if no repo is opened and
     FSL_RC_MISUSE if a checkout *is* opened.

   - Creates/re-uses a .fslckout DB in the dir opt->targetDir. The
     directory must be NULL or already exist, else FSL_RC_NOT_FOUND is
     returned. If opt->dbOverwritePolicy is false then it fails with
     FSL_RC_ALREADY_EXISTS if that directory already contains a
     checkout db.

   Note that this does not extract any SCM'd files from the
   repository, it only opens (and possibly creates) the checkout
   database.

   Pending:

   - If opening an existing checkout db for a different repo then
   delete the STASH and UNDO entries, as they're not valid for a
   different repo.
*/
FSL_EXPORT int fsl_repo_open_ckout( fsl_cx * const f,
                                    fsl_repo_open_ckout_opt const * opt );

typedef struct fsl_ckup_state fsl_ckup_state;
/**
   A callback type for use with fsl_ckup_state.  It gets called via
   fsl_repo_ckout() and fsl_ckout_update() to report progress of the
   extraction process. It gets called after one of those functions has
   successfully extracted a file or skipped over it because the file
   existed and the checkout options specified to leave existing files
   in place. It must return 0 on success, and non-0 will end the
   extraction process, propagating that result code back to the
   caller. If this callback fails, the checkout's contents may be left
   in an undefined state, with some files updated and others not.  All
   database-side data will be consistent (the transaction is rolled
   back) but filesystem-side changes may not be.
*/
typedef int (*fsl_ckup_f)( fsl_ckup_state const * cState );

/**
   This enum lists the various types of individual file change states
   which can happen during a checkout, update, or merge.
*/
enum fsl_ckup_fchange_e {
/** Sentinel value. */
FSL_CKUP_FCHANGE_INVALID = -1,
/** Was unchanged between the previous and updated-to version,
    so no change was made to the on-disk file. This is the
    only entry in the enum which is guaranteed to have a specific
    value: 0, so that it can be used as a boolean false. */
FSL_CKUP_FCHANGE_NONE = 0,
/**
   Added to SCM in the updated-to version.
*/
FSL_CKUP_FCHANGE_ADDED,
/**
   Added to SCM in the current checkout version and carried over into
   the updated-to version.
*/
FSL_CKUP_FCHANGE_ADD_PROPAGATED,
/**
   Removed from SCM in the updated-to to version OR in the checked-out
   version but not yet committed. a.k.a. it became "unmanaged."

   Do we need to differentiate between those cases?
*/
FSL_CKUP_FCHANGE_RM,
/**
   Removed from the checked-out version but not yet commited,
   so was carried over to the updated-to version.
*/
FSL_CKUP_FCHANGE_RM_PROPAGATED,
/** Updated or replaced without a merge by the checkout/update
    process. */
FSL_CKUP_FCHANGE_UPDATED,
/** Merge was not performed because at least one of the inputs appears
    to be binary. The updated-to version overwrites the previous
    version in this case.
*/
FSL_CKUP_FCHANGE_UPDATED_BINARY,
/** Updated with a merge by the update process. */
FSL_CKUP_FCHANGE_MERGED,
/** Special case of FSL_CKUP_FCHANGE_MERGED. Merge was performed
    and conflicts were detected. The newly-updated file will contain
    conflict markers.

    @see fsl_b_contains_merge_marker()
*/
FSL_CKUP_FCHANGE_CONFLICT_MERGED,
/** Added in the current checkout but also contained in the
    updated-to version. The local copy takes precedence.
*/
FSL_CKUP_FCHANGE_CONFLICT_ADDED,
/**
   Added by the updated-to version but a local unmanaged copy exists.
   The local copy is overwritten, per historical fossil(1) convention
   (noting that fossil has undo support to allow one to avoid loss of
   such a file's contents).

   TODO: use confirmer here to ask user whether to overwrite.
*/
FSL_CKUP_FCHANGE_CONFLICT_ADDED_UNMANAGED,
/** Edited locally but removed from updated-to version. Local
    edits will be left in the checkout tree. */
FSL_CKUP_FCHANGE_CONFLICT_RM,
/** Cannot merge if one or both of the update/updating verions of a
    file is a symlink. The updated-to version overwrites the previous
    version in this case.

    We probably need a better name for this.
*/
FSL_CKUP_FCHANGE_CONFLICT_SYMLINK,
/**
   Indicates that a merge of binary content was requested.

   TODO: figure out why UPDATE uses the target version, instead of
   triggering an error here, and why MERGE does not do the same.
   fossil(1) simply skips over, with a warning, binaries during a
   merge.
*/
FSL_CKUP_FCHANGE_CONFLICT_BINARY,
/** File was renamed in the updated-to version. If a file is both
    modified and renamed, it is flagged as renamed instead
    of modified. */
FSL_CKUP_FCHANGE_RENAMED,
/** Locally modified. This state appears only when
    "updating" a checkout to the same version. */
FSL_CKUP_FCHANGE_EDITED
};
typedef enum fsl_ckup_fchange_e fsl_ckup_fchange_e;

/**
   State to be passed to fsl_ckup_f() implementations via
   calls to fsl_repo_ckout() and fsl_ckout_update().
*/
struct fsl_ckup_state {
  /**
     The core SCM state for the just-extracted file. Note that its
     content member will be NULL: the content is not passed on via
     this interface because it is only loaded for files which require
     overwriting.

     An update process may synthesize content for extractState->fCard
     which do not 100% reflect the file on disk. Of primary note here:

     1) fCard->uuid will refer to the hash of the updated-to
     version, as opposed to the hash of the on-disk file (which may
     differ due to having local edits merged in). 

     2) For the update process, fCard->priorName will be NULL unless
     the file was renamed between the original and updated-to
     versions, in which case priorName will refer to the original
     version's name.
  */
  fsl_repo_extract_state const * extractState;
  /**
     Optional client-dependent state for use in the fsl_ckup_f()
     callback. This is copies from the corresponding
     fsl_ckup_opt::callbackState member.
  */
  void * callbackState;

  /**
     Vaguely describes the type of change the current call into
     the fsl_ckup_f() represents. The full range of values is
     not valid for all operations. Specifically:

     Checkout only uses:

     FSL_CKUP_FCHANGE_NONE
     FSL_CKUP_FCHANGE_UPDATED
     FSL_CKUP_FCHANGE_RM

     For update operations all (or most) values are potentially
     possible.

     If this has a value of FSL_CKUP_FCHANGE_RM,
     this->fileRmInfo will provide a bit more detail.
  */
  fsl_ckup_fchange_e fileChangeType;

  /**
     Indicates whether the file was removed by the process:

     - FSL_CKUP_RM_NOT = Was not removed.

     - FSL_CKUP_RM_KEPT = Was removed from the checked-out version but
     left in the filesystem because the confirmer said to.

     - FSL_CKUP_RM = Was removed from the checkout and the filesystem.

     When this->dryRun is true, this specifies whether the file would
     have been removed.
  */
  fsl_ckup_rm_state_e fileRmInfo;

  /**
     If fsl_repo_ckout()'s or fsl_ckout_update()'s options specified
     that the mtime should be set on each updated file, this holds
     that time. If the file existed and was not overwritten, it is set
     to that file's time. Else it is set to the current time (which
     may differ by a small fraction of a second from the file-write
     time because we avoid stat()'ing it again after writing). If
     this->fileRmInfo indicates that a file was removed, this might
     (depending on availability of the file in the filesystem at the
     time) be set to 0.

     When running in dry-run mode, this value may be 0, as we may not
     have a file in place which we can stat() to get it, nor a db
     entry from which to fetch it.

     This option is ignored for merge operations.
  */
  fsl_time_t mtime;

  /**
     The size of the extracted file, in bytes. If the file was removed
     from the filesystem (or removal was at least attempted) then this
     is set to -1.
  */
  fsl_int_t size;

  /**
     True if the current checkout/update is running in dry-run mode,
     else false. See fsl_ckup_opt::dryRun for details.
  */
  bool dryRun;
};

/**
   Options for use with fsl_repo_ckout() and
   fsl_ckout_update(). i.e. for checkout and update.
*/
struct fsl_ckup_opt {
  /**
     The version of the repostitory to check out or update. This must
     be the blob.rid of a checkin artifact.
  */
  fsl_id_t checkinRid;

  /**
     Gets called once per checked-out or updated file, passed a
     fsl_ckup_state instance with information about the
     checked-out file and related metadata. May be NULL.
  */
  fsl_ckup_f callback;

  /**
     State to be passed to this->callback via the
     fsl_ckup_state::callbackState member.
   */
  void * callbackState;

  /**
     An optional "confirmer" for answering questions about file
     overwrites and deletions posed by the checkout process.
     By default this confirmer of the associated fsl_cx instance
     is used.

     Caveats:

     - This is not currently used by the update process, only
     checkout.

     - If this->setMTime is true, the mtime is NOT set for any files
     which already exist and are skipped due to the confirmer saying
     to leave them in place.

     - Similarly, if the confirmer says to never overwrite files,
     permissions on existing files are not modified. fsl_repo_ckout()
     does not (re)write unmodified files, and thus may leave such
     files with different permissions. That's on the to-fix list.
  */
  fsl_confirmer confirmer;

  /**
     If true, the checkout/update processes will calculate the
     (synthetic) mtime of each extracted file and set its mtime. This
     is a relatively expensive operation which calculates the
     "effective mtime" of each file by calculating it: Fossil does not
     record file timestamps, instead treating files as if they had the
     timestamp of the most recent checkin in which they were added or
     modified.

     It's generally a good idea to let the update process stamp the
     _current_ time on modified files, in order to avoid any hiccups
     with build processes which rely on accurate times
     (e.g. Makefiles). When doing a clean checkout, it's often
     interesting to see the "original" times, though.
  */
  bool setMtime;

  /**
     A hint to fsl_repo_ckout() and fsl_ckout_update() about whether
     it needs to scan the checkout for changes. Set this to false ONLY
     if the calling code calls fsl_ckout_changes_scan() (or
     equivalent, e.g. fsl_vfile_changes_scan()) immediately before
     calling fsl_repo_ckout() or fsl_ckout_update(), as those require
     a non-stale changes scan in order to function properly.
  */
  bool scanForChanges;

  /**
     If true, the extraction process will "go through the motions" but
     will not write any files to disk. It will perform I/O such as
     stat()'ing to see, e.g., if it would have needed to overwrite a
     file.
  */
  bool dryRun;
};
typedef struct fsl_ckup_opt fsl_ckup_opt;

/**
  Empty-initialized fsl_ckup_opt const-copy constructor.
*/
#define fsl_ckup_opt_m {\
  -1/*checkinRid*/, NULL/*callback*/, NULL/*callbackState*/,  \
  fsl_confirmer_empty_m/*confirmer*/,\
  false/*setMtime*/, true/*scanForChanges*/,false/*dryRun*/ \
}

/**
  Empty-initialised fsl_ckup_opt instance. Clients should copy
  this value (or fsl_ckup_opt_empty_m) to initialise
  fsl_ckup_opt instances for sane default values.
*/
FSL_EXPORT const fsl_ckup_opt fsl_ckup_opt_empty;

/**
   A fsl_repo_extract() proxy which extracts the contents of the
   repository version specified by opt->checkinRid to the root
   directory of f's currently-opened checkout. i.e. it performs a
   "checkout" operation.

   For each extracted entry, cOpt->callback (if not NULL) will be
   passed a (fsl_ckup_state const*) which contains a pointer
   to the fsl_repo_extract_state and some additional metadata
   regarding the extraction. The value of cOpt->callbackState will be
   set as the callbackState member of that fsl_ckup_state
   struct, so that the client has a way of passing around app-specific
   state to that callback.

   After successful completion, the process will report (see below)
   any files which were part of the previous checkout version but are
   not part of the current version, optionally removing them from the
   filesystem (depending on the value of opt->rmMissingPolicy). It
   will IGNORE ANY DELETION FAILURE of files it attempts to
   delete. The reason it does not fail on removal error is because
   doing so would require rolling back the transaction, effectively
   undoing the checkout, but it cannot roll back any prior deletions
   which succeeded. Similarly, after all file removal is complete, it
   attempts to remove any now-empty directories left over by that
   process, also silently ignoring any errors. If the cOpt->dryRun
   option is specified, it will "go through the motions" of removing
   files but will not actually attempt filesystem removal. For
   purposes of the callback, however, it will report deletions as
   having happened (but will also set the dryRun flag on the object
   passed to the callback).

   After unpacking the SCM-side files, it may write out one or more
   manifest files, as described for fsl_ckout_manifest_write(), if the
   'manifest' config setting says to do so.

   As part of the file-removal process, AFTER all "existing" files are
   processed, it calls cOpt->callback() (if not NULL) for each removed
   file, noting the following peculiarities in the
   fsl_ckup_state object which is passed to it for those
   calls:

   - It is called after the processing of "existing" files. Thus the
   file names passed during this step may appear "out of order" with
   regards to the others (which are guaranteed to be passed in lexical
   order, though whether it is case-sensitive or not depends on the
   repository's case-sensitivity setting).

   - fileRmInfo will indicate that the file was removed from the
   checkout, and whether it was actually removed or retained in the
   filesystem. This will indicate filesystem-level removal even when
   in dry-run mode, though in that case no filesystem-level removal is
   actually attempted.

   - extractState->fileRid will refer to the file's blob's RID for the
   previous checkout version.

   - extractState->content will be NULL.

   - extractState->callbackState will be NULL.

   - extractState->fCard will refer to the pre-removal state of the
   file. i.e. the state as it was in the checkout prior to this
   function being called.

   Returns 0 on success. Returns FSL_RC_NOT_A_REPO if f has no opened
   repo, FSL_RC_NOT_A_CKOUT if no checkout is opened. If
   cOpt->callback is not NULL and returns a non-0 result code,
   extraction ends and that result is returned. If it returns non-0 at
   any point after basic argument validation, it rolls back all
   changes or sets the current transaction stack into a rollback
   state.

   @see fsl_repo_open_ckout()
*/
FSL_EXPORT int fsl_repo_ckout(fsl_cx * f, fsl_ckup_opt const * cOpt);


/**
   UNDER CONSTRUCTION.

   Performs an "update" operation on f's currenly-opened
   checkout. Performing an update is similar to performing a checkout,
   the primary difference being that an update will merge local file
   modifications into any newly-updated files, whereas a checkout will
   overwrite them.

   TODO?: fossil(1)'s update permits a list of files, in which case it
   behaves differently: it updates the given files to the version
   requested but leaves the checkout at its current version. To be
   able to implement that we either need clients to call this in a
   loop, changing opt->filename on each call (like how we do
   fsl_ckout_manage()) or we need a way for them to pass on the list
   of files/dir in the opt object.

   @see fsl_repo_ckout().
*/
FSL_EXPORT int fsl_ckout_update(fsl_cx * f, fsl_ckup_opt const *opt);


/**
   Tries to calculate a version to update the current checkout version
   to, preferring the tip of the current checkout's branch.

   On success, 0 is returned and *outRid is set to the calculated RID,
   which may be 0, indicating that no errors were encountered but no
   version could be calculated.

   On error, non-0 is returned, outRid is not modified, and f's error
   state is updated.

   Returns FSL_RC_NOT_A_CKOUT if f has no checkout opened and
   FSL_RC_NOT_A_REPO if no repo is opened.

   If it calculates that there are multiple viable descendants it
   returns FSL_RC_AMBIGUOUS and f's error state will contain a list of
   the UUIDs (or UUID prefixes) of those descendants.

   Sidebar: to get the absolute latest version, irrespective of the
   branch, use fsl_sym_to_rid() to resolve the symbolic name "tip".
*/
FSL_EXPORT int fsl_ckout_calc_update_version(fsl_cx * f, fsl_id_t * outRid);

/**
   Bitmask used by fsl_ckout_manifest_setting() and
   fsl_ckout_manifest_write().
*/
enum fsl_cx_manifest_mask_e {
/** Coresponds to the file "manifest". */
FSL_MANIFEST_MAIN = 0x001,
/** Coresponds to the file "manifest.uuid". */
FSL_MANIFEST_UUID = 0x010,
/** Coresponds to the file "manifest.tags". */
FSL_MANIFEST_TAGS = 0x100
};
typedef enum fsl_cx_manifest_mask_e fsl_cx_manifest_mask_e;

/**
   Returns a bitmask representing which manifest files, if any, will
   be written when opening or updating a checkout directory, as
   specified by the repository's 'manifest' configuration setting, and
   sets *m to a bitmask indicating which of those are enabled. It
   first checks for a versioned setting then, if no versioned setting
   is found, a repository-level setting.

   A truthy setting value (1, "on", "true") means to write the
   manifest and manifest.uuid files. A string with any of the letters
   'r', 'u', or 't' means to write the [r]aw, [u]uid, and/or [t]ags
   file(s), respectively.

   If the manifest setting is falsy or not set, *m is set to 0, else
   *m is set to a bitmask representing which file(s) are considered to
   be auto-generated for this repository:

   - FSL_MANIFEST_MAIN = manifest
   - FSL_MANIFEST_UUID = manifest.uuid
   - FSL_MANIFEST_TAGS = manifest.tags

   Any db-related or allocation errors while trying to fetch the
   setting are silently ignored.

   For performance's sake, since this is potentially called often from
   fsl_reserved_fn_check(), this setting is currently cached by this
   routine (in the fsl_cx object), but that ignores the fact that the
   manifest setting can be modified at any time, either in a versioned
   setting file or the repository db, and may be modified from outside
   the library. There's a tiny back-door for working around that: if m
   is NULL, the cache will be flushed and no other work will be
   performed. Thus the following approach can be used to force a fresh
   check for that setting:

   ```
   fsl_ckout_manifest_setting(f, NULL); // clears caches, does nothing else
   fsl_ckout_manifest_setting(f, &myInt); // loads/caches the setting
   ```
*/
FSL_EXPORT void fsl_ckout_manifest_setting(fsl_cx *f, int *m);

/**
   Might write out the files manifest, manifest.uuid, and/or
   manifest.tags for the current checkout to the the checkout's root
   directory. The 2nd-4th arguments are interpreted as follows:

   0: Do not write that file.

   >0: Always write that file.

   <0: Use the value of the "manifest" config setting (see
   fsl_ckout_manifest_setting()) to determine whether or not to write
   that file.

   As each file is written, its mtime is set to that of the checkout
   version. (Forewarning: that behaviour may change if it proves to be
   problematic vis a vis build processes.)

   Returns 0 on success, non-0 on error:

   - FSL_RC_NOT_A_CKOUT if no checkout is opened.

   - FSL_RC_RANGE if the current checkout RID is 0 (indicating a fresh,
   empty repository).

   - Various potential DB/IO-related error codes.

   If the final argument is not NULL then it will be updated to
   contain a bitmask representing which files, if any, were written:
   see fsl_ckout_manifest_setting() for the values. It is updated
   regardless of success or failure and will indicate which file(s)
   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 * const f,
                                        int manifest,
                                        int manifestUuid,
                                        int manifestTags,
                                        int * const wroteWhat );

/**
   Returns true if f has an opened checkout and the given absolute
   path is rooted in that checkout, else false. As a special case, it
   returns false if the path _is_ the checkout root unless zAbsPath
   has a trailing slash. (The checkout root is always stored with a
   trailing slash because that simplifies its internal usage.)

   Note that this is strictly a string comparison, not a
   filesystem-level operation.
*/
FSL_EXPORT bool fsl_is_rooted_in_ckout(fsl_cx * const f, char const * const zAbsPath);

/**
   Works like fsl_is_rooted_in_ckout() except that it returns 0 on
   success, and on error updates f with a description of the problem
   and returns non-0: FSL_RC_RANGE or (if updating the error state
   fails) FSL_RC_OOM.
 */
FSL_EXPORT int fsl_is_rooted_in_ckout2(fsl_cx * const f, char const * const zAbsPath);

/**
   Change-type values for use with fsl_ckout_revert_f() callbacks.
*/
enum fsl_ckout_revert_e {
/** Sentinel value. */
FSL_REVERT_NONE = 0,
/**
   File was previously queued for addition but unqueued
   by the revert process.
*/
FSL_REVERT_UNMANAGE,
/**
   File was previously queued for removal but unqueued by the revert
   process. If the file's contents or permissions were also reverted
   then the file is reported as FSL_REVERT_PERMISSIONS or
   FSL_REVERT_CONTENTS instead.
*/
FSL_REVERT_REMOVE,
/**
   File was previously scheduled to be renamed, but the rename was
   reverted. The name reported to the callback is the original one.
   If a file was both modified and renamed, it will be flagged as
   renamed instead of modified, for consistency with the usage of
   fsl_ckup_fchange_e's FSL_CKUP_FCHANGE_RENAMED.

   FIXME: this does not mean that the file on disk was actually
   renamed (if needed). That is TODO, pending addition of code to
   perform renames.
*/
FSL_REVERT_RENAME,
/** File's permissions (only) were reverted. */
FSL_REVERT_PERMISSIONS,
/**
   File's contents reverted. This value trumps any others in this
   enum. Thus if a file's permissions and contents were reverted,
   or it was un-renamed and its contents reverted, it will be
   reported using this enum entry.
*/
FSL_REVERT_CONTENTS
};
typedef enum fsl_ckout_revert_e fsl_ckout_revert_e;
/**
   Callback type for use with fsl_ckout_revert(). For each reverted
   file it gets passed the checkout-relative filename, type of change,
   and the callback state pointer which was passed to
   fsl_ckout_revert(). If it returns non-0, the revert process will
   end in an error and that code will be propagated back to the
   caller.  In such cases, any files reverted up until that point will
   still be reverted on disk but the reversion in the database will be
   rolled back. A change scan (e.g. fsl_ckout_changes_scan()) will
   restore balance to that equation, but these callbacks should only
   return non-0 in for catastrophic failure.
*/
typedef int (*fsl_ckout_revert_f)( char const *zFilename,
                                   fsl_ckout_revert_e changeType,
                                   void * callbackState );

/**
   Options for passing to fsl_ckout_revert().
*/
struct fsl_ckout_revert_opt {
  /**
     File or directory name to revert. See also this->vfileIds.
  */
  char const * filename;
  /**
     An alternative to assigning this->filename is to point
     this->vfileIds to a bag of vfile.id values. If this member is not
     NULL, fsl_ckout_revert() will ignore this->filename.

     @see fsl_filename_to_vfile_ids()
  */
  fsl_id_bag const * vfileIds;
  /**
     Interpret filename as relative to cwd if true, else relative to
     the current checkout root. This is ignored when this->vfileIds is
     not NULL.
  */
  bool relativeToCwd;
  /**
     If true, fsl_vfile_changes_scan() is called to ensure that
     the filesystem and vfile tables agree. If the client code has
     called that function, or its equivalent, since any changes were
     made to the checkout then this may be set to false to speed up
     the revert process.
  */
  bool scanForChanges;

  /**
     Optional callback to notify the client of what gets reverted.
  */
  fsl_ckout_revert_f callback;
  /**
     State for this->callback.
  */
  void * callbackState;
};
typedef struct fsl_ckout_revert_opt fsl_ckout_revert_opt;
/**
   Initialized-with-defaults fsl_ckout_revert_opt instance,
   intended for use in const-copy initialization.
*/
#define fsl_ckout_revert_opt_empty_m { \
  NULL/*filename*/,NULL/*vfileIds*/,true/*relativeToCwd*/,true/*scanForChanges*/, \
  NULL/*callback*/,NULL/*callbackState*/      \
}
/**
   Initialized-with-defaults fsl_ckout_revert_opt instance,
   intended for use in non-const copy initialization.
*/
FSL_EXPORT const fsl_ckout_revert_opt fsl_ckout_revert_opt_empty;

/**
   Reverts changes to checked-out files, replacing their
   on-disk versions with the current checkout's version.

   If zFilename refers to a directory, all managed files under that
   directory are reverted (if modified). If zFilename is NULL or
   empty, all modifications in the current checkout are reverted.

   If a file has been added but not yet committed, the add
   is un-queued but the file is otherwise untouched. If the
   file has been queued for removal, this removes it from
   that queue as well as restores its contents.

   If a rename is pending for the given filename, the name may match
   either its original name or new name. Whether or not that will
   actually work when file A is renamed to B and file C is renamed to
   A is anyone's guess. (Noting that (fossil mv) won't allow that
   situation to exist in the vfile table for a single checkout
   version, so it seems safe enough.)

   If the 4th argument is not NULL then it is called for each revert
   (_after_ the revert happens) to report what was done with that
   file. It gets passed the checkout-relative name of each reverted
   file. The 5th argument is not interpreted by this function but is
   passed on as-is as the final argument to the callback. If the
   callback returns non-0, the revert process is cancelled, any
   pending transaction is set to roll back, and that error code is
   returned. Note that cancelling a revert mid-process will leave file
   changes made by the revert so far in place, and thus the checkout
   db and filesystem will be in an inconsistent state until
   fsl_vfile_changes_scan() (or equivalent) is called to restore
   balance to the world.

   Files which are not actually reverted because their contents or
   permissions were not modified on disk are not reported to the
   callback unless the reversion was the un-queuing of an ADD or
   REMOVE operation.

   Returns 0 on success, any number of non-0 results on error.

   [tag:bug:revert-merge-hiccup] (2024-09-13): it is possible, via
   merging and copying modified files between multiple checkouts of
   the same repo, to get the tree into a state where this function has
   no files to revert and therefore does not clear the merge
   state. This condition is very tricky to trigger, and has only been
   seen once in the wild. "The problem" with fixing that is that
   whether or not we need to do a _full_ wipe of the merge state (as
   opposed to just wiping merge state of individual files) depends
   largely on information which (A) this function does have and (B) is
   onerous for the caller to figure out and provide (namely, whether
   it's a full revert or not). As this bug is so rare, we'll leave it
   for now and ponder potential solutions. As of 2024-09-13, this bug
   is believed to have been adequately resolved, but exactly how it
   was initially triggered is unclear, so we don't have a test which
   proves it is resolved.
*/
FSL_EXPORT int fsl_ckout_revert( fsl_cx * const f,
                                 fsl_ckout_revert_opt const * opt );

/**
   Expects f to have an opened checkout and zName to be the name of
   an entry in the vfile table where vfile.vid == vid. If vid<=0 then
   the current checkout RID is used. This function does not do any
   path resolution or normalization on zName and checks only for an
   exact match (honoring f's case-sensitivity setting - see
   fsl_cx_case_sensitive_set()).

   On success it returns 0 and assigns *vfid to the vfile.id value of
   the matching file.  If no match is found, 0 is returned and *vfile
   is set to 0. Returns FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_RANGE if zName is not a simple path (see
   fsl_is_simple_pathname()), and any number of codes for db-related
   errors.

   This function matches only vfile.pathname, not vfile.origname,
   because it is possible for a given name to be in both fields (in
   different records) at the same time.
*/
FSL_EXPORT int fsl_filename_to_vfile_id( fsl_cx * const f, fsl_id_t vid,
                                         char const * zName,
                                         fsl_id_t * const vfid );

/**
   Searches the `vfile` table where `vfile.vid=vid` for a name which
   matches `zName` or all `vfile` entries found under a subdirectory
   named `zName` (with no trailing slash). `zName` must be relative to
   the checkout root. As a special case, if `zName` is `NULL`, empty,
   or `"."` then all files in `vfile` with the given `vid` are
   selected. For each entry it finds, it adds the `vfile.id` to
   `dest`. If `vid<=0` then the current checkout RID is used.

   If `changedOnly` is `true` then only entries which have been marked
   in the `vfile` table as having some sort of change are included, so
   if `true` then fsl_ckout_changes_scan() (or equivalent) must have
   been "recently" called to ensure that state is up to do. This routine
   only checks the `vfile` table for "is changed" state, it does not
   do filesystem-level checks on the files.

   This search honors the context-level case-sensitivity setting (see
   fsl_cx_case_sensitive_set()).

   Returns 0 on success. Not finding anything is not treated as an
   error, though we could arguably return `FSL_RC_NOT_FOUND` for the
   cases which use this function. In order to determine whether or not
   any results were actually found, compare `dest->entryCount` before
   and after calling this.

   This function matches only `vfile.pathname`, not `vfile.origname`,
   because it is possible for a given name to be in both fields (in
   different records) at the same time.

   @see fsl_ckout_vfile_ids()
*/
FSL_EXPORT int fsl_filename_to_vfile_ids( fsl_cx * const f, fsl_id_t vid,
                                          fsl_id_bag * const dest,
                                          char const * zName,
                                          bool changedOnly);

/**
   This is a variant of fsl_filename_to_vfile_ids() which accepts
   filenames in a more flexible form than that routine. This routine
   works exactly like that one except for the following differences:

   1) The given filename and the relativeToCwd arguments are passed to
   by fsl_ckout_filename_check() to canonicalize the name and ensure
   that it points to someplace within f's current checkout.

   2) Directory names passed to it may optionally end in an trailing
   slash.

   3) Because of (1), zName may not be NULL or empty. To fetch all of
   the vfile IDs for the current checkout, pass a zName of "."  and
   relativeToCwd=false.

   Returns 0 on success, else:

   - FSL_RC_MISUSE if zName is NULL or empty.
   - FSL_RC_OOM on allocation error.
   - FSL_RC_NOT_A_CKOUT if f has no opened checkout.
   - FSL_RC_RANGE if the given name points outside of the checkout.
*/
FSL_EXPORT int fsl_ckout_vfile_ids( fsl_cx * const f, fsl_id_t vid,
                                    fsl_id_bag * const dest, char const * zName,
                                    bool relativeToCwd, bool changedOnly );


/**
   This "mostly internal" routine (re)populates f's checkout vfile
   table with all files from the given checkin manifest. If
   manifestRid is 0 or less then the current checkout's RID is
   used. If vfile already contains any content for the given checkin,
   it is left intact (and several processes rely on that behavior to
   keep it from nuking, e.g., as-yet-uncommitted queued add/rm
   entries).

   Returns 0 on success, any number of codes on any of many potential
   errors.

   f must not be NULL and must have opened checkout and repository
   databases. In debug builds it will assert that that is so.

   If the 3rd argument is true, any entries in vfile for checkin
   versions other than the one specified in the 2nd argument are
   cleared from the vfile table. That is _almost_ always the desired
   behavior, but there are rare cases where vfile needs to temporarily
   (for the duration of a single transaction) hold state for multiple
   versions.

   If the 4th argument is not NULL, it gets assigned the number of
   blobs from the given version which are currently missing from the
   repository due to being phantoms (as opposed to being shunned).

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_OOM on allocation error, FSL_RC_DB for db-related problems,
   et.al.

   Misc. notes:

   - This does NOT update the "checkout" vvar table entry because this
   routine is sometimes used in contexts where we need to briefly
   maintain two vfile versions and keep the previous checkout version.

   - Apps must take care to not leave more than one version in the
   vfile table for longer than absolutely needed. They "really should"
   use fsl_vfile_unload() to clear out any version they load with this
   routine.

   @see fsl_vfile_unload()
   @see fsl_vfile_unload_except()
*/
FSL_EXPORT int fsl_vfile_load(fsl_cx * const f, fsl_id_t manifestRid,
                              bool clearOtherVersions,
                              uint32_t * missingCount);

/**
   Clears out all entries in the current checkout's vfile table with
   the given vfile.vid value. If vid<=0 then the current checkout RID
   is used (which is never a good idea from client-side code!).

   ACHTUNG: never do this without understanding the consequences. It
   can ruin the current checkout state.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if f has no checkout
   opened, FSL_RC_DB on any sort of db-related error (in which case
   f's error state is updated with a description of the problem).

   @see fsl_vfile_load()
   @see fsl_vfile_unload_except()
*/
FSL_EXPORT int fsl_vfile_unload(fsl_cx * const f, fsl_id_t vid);

/**
   A counterpart of fsl_vfile_unload() which removes all vfile
   entries where vfile.vid is not the given vid. If vid is <=0 then
   the current checkout RID is used.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if f has no checkout
   opened, FSL_RC_DB on any sort of db-related error (in which case
   f's error state is updated with a description of the problem).

   @see fsl_vfile_load()
   @see fsl_vfile_unload()
*/
FSL_EXPORT int fsl_vfile_unload_except(fsl_cx * const f, fsl_id_t vid);


/**
   Performs a "fingerprint check" between f's current checkout and
   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.).

   As a special case, this is a no-op for a newly-created repo, as
   those cannot yet have a fingerprint.

   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 * const 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_b * 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. This can happen if,
     e.g. fc's file has been renamed, but not yet checked in, in the
     current checkout. A _potential_ TODO is to check for a
     (`vfile.origname=fc->name`) record and use `vfile.pathname` for
     the stat() call.

   - 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 * const repoMtime,
                                      fsl_time_t * const localMtime);

/**
   File change types for use with fsl_merge_state::fileChangeType.

   Terminology used in some of the descriptions:

   - (P) is the "pivot" - the common ancestor for the merge.
   - (M) is the version being merged in to...
   - (V) is current checkout version into which (M) is being merged.

   Maintenance reminder: this enum's values must start at 0 and
   increment sequentially, and FSL_MERGE_FCHANGE_count must be the
   final entry. This is to enable the creation of arrays, e.g. for
   keeping track (client-side) of how many times a given change type
   has been seen during a given merge run.
*/
enum fsl_merge_fchange_e {
/**
    Not currently used. Merge does not (and cannot without some
    surgery) report state of files unaffected by a merge. This entry
    exists for the case that that changes. This is the only entry in
    the enum which is guaranteed to have a specific value: 0, so that
    it can be used as a boolean false. */
FSL_MERGE_FCHANGE_NONE = 0,
/**
   File was added to (V) from (M).
*/
FSL_MERGE_FCHANGE_ADDED,
/**
   File content was copied as-is from (M) to (V).
*/
FSL_MERGE_FCHANGE_COPIED,
/**
   File was removed from (V) via (M). a.k.a. it became "unmanaged."
*/
FSL_MERGE_FCHANGE_RM,
/**
   Content from (M) was merged into (V).
*/
FSL_MERGE_FCHANGE_MERGED,
/**
   Special case of FSL_MERGE_FCHANGE_MERGED. Merge was performed from
   (M) to (V) and conflicts were detected. The newly-updated file will
   contain conflict markers.

    @see fsl_b_contains_merge_marker()
*/
FSL_MERGE_FCHANGE_CONFLICT_MERGED,
#if 0
/** Added in the current checkout but also contained in the
    updated-to version. The local copy takes precedence.
*/
FSL_MERGE_FCHANGE_CONFLICT_ADDED,
#endif
/**
   Added to (V) by (M) but a local unmanaged copy exists.
   The local copy is overwritten, per historical fossil(1) convention
   (noting that fossil has undo support to allow one to avoid loss of
   such a file's contents).
*/
FSL_MERGE_FCHANGE_CONFLICT_ADDED_UNMANAGED,
#if 0
/*
  Fossil deletes merged-over removed files, regardless of whether
  they're locally edited, so we'll do the same for now (noting that
  fossil has undo support which can hypothetically save that case
  from data loss). fsl_ckout_update() does not do so, but has extra
  infastructure to deal with this. */
/** Edited locally but removed from merged-in version. Local
    edits will be left in the checkout tree. */
FSL_MERGE_FCHANGE_CONFLICT_RM,
#endif
/**
   Cannot merge if one or both of the update/updating versions of a
   file is a symlink.

   This case needs re-thinking. fossil(1) simply skips such merges
   with a warning but no error. This library has no warning mechanism
   other than to pass this code on to the fsl_merge_f() callback,
   so that's what we do.

   For UPDATE ops, the updated-to version overwrites the previous
   version in this case. Why merge doesn't do that isn't clear, but
   it's probably because we can have any number of merge parents and
   choosing which one to use in the merge/replace case would be
   impossible.
*/
FSL_MERGE_FCHANGE_CONFLICT_SYMLINK,
/**
   Indicates that a merge of binary content was requested. We
   cannot merge binaries, so this indicates that the file in question
   was skipped over for merge purposes.

   fossil(1) simply skips over, with a warning, binaries during a
   merge, so we do the same (for lack of a better option).
*/
FSL_MERGE_FCHANGE_CONFLICT_BINARY,
/**
   File was renamed in the updated-to version. If a file is both
   modified and renamed, it will be reported twice: once for each type
   of change. The new name is reported via fsl_merge_state::filename
   and the previous name via fsl_merge_state::priorName.
*/
FSL_MERGE_FCHANGE_RENAMED,
/**
   This is the number of entries in this enum, for purposes of creating,
   e.g. arrays of counters. This entry is never reported via a
   fsl_merge_state::fileChangeType.
*/
FSL_MERGE_FCHANGE_count
};
typedef enum fsl_merge_fchange_e fsl_merge_fchange_e;

/** Reqired forward decl. */
typedef struct fsl_merge_opt fsl_merge_opt;

/**
   UNDER CONSTRUCTION! INCOMPLETE!

   A type for passing state to fsl_merge_f callbacks during
   fsl_ckout_merge() processing.

   For each step of a merge operation which affects a file,
   state reflecting that change is set in one of these objects
   and it is passed to the fsl_merge_f implementation supplied by
   the caller.

   Unlike fsl_ckout_update(), fsl_ckout_merge() reports only files
   which are affected by a merge, not unmodified files.  Whether
   that's a bug or a feature is not yet clear, but the merge algorithm
   does not, as is, support reporting unaffected files.

   Due to the complexity and intricacy of the merge operation, it is
   possible that any given file will get passed to the fsl_merge_f()
   callback more than once with a different
   fsl_merge_state::fileChangeType value. Most notably, a file which
   has been modified and renamed may be passed on one with
   FSL_MERGE_FCHANGE_COPIED and once with FSL_MERGE_FCHANGE_RENAMED.
   Whether that's a bug or a feature is as-yet undecided, but
   (A) fossil(1) does it that way and (B) _not_ doing that would
   require some rearchitecting.
*/
struct fsl_merge_state {
  /**
     The fsl_cx object for which the current merge is running.
   */
  fsl_cx * f;
  /**
     The options object which drives the current fsl_ckout_merge()
     run.
  */
  fsl_merge_opt const * opt;

  /**
     The checkout-relative name of the file affected by the merge.
     These bytes are invalidated after the fsl_merge_f() callback
     returns, so must be copied if the client requires them for later.
  */
  char const * filename;

  /**
     If this->fileChangeType is FSL_MERGE_FCHANGE_RENAMED then
     this is the previous name of the file, else it is NULL.
  */
  char const * priorName;
  
  /**
     Indicates the state of the file currently being merged.  Merge
     does not support the full range fo fsl_ckup_fchange_e
     values. TODO: list which it does or create a new enum which
     enumerates only merge-specific change types.
  */
  fsl_merge_fchange_e fileChangeType;

  /**
     Indicates whether the current file was removed. A state of
     FSL_CKUP_RM_KEPT and fileChangeType of FSL_MERGE_FCHANGE_RM
     indicates that the file has become unmanaged but the local
     copy was retained because it was flagged as locally modified.
  */
  fsl_ckup_rm_state_e fileRmInfo;
};
typedef struct fsl_merge_state fsl_merge_state;

/**
   Callback type for use with fsl_merge_opt and fsl_ckout_merge().
*/
typedef int (*fsl_merge_f)(fsl_merge_state const * const);

/**
   Merge type enum for use with fsl_merge_opt::mergeType.

   The values of these entries are fossil-magic values for the
   `vmerge.id` db field and must stay in sync with fossil's
   definition.
*/
enum fsl_merge_type_e {
/**
   Indicates a normal merge.
*/
FSL_MERGE_TYPE_NORMAL = 0,
/**
   Indicates an "integrate" merge, which tells the next checkin
   operation to apply a "closed" tag to the checkin from which this
   merge is performed (effectively closing its branch).

   Certain merge-time state will force this merge type to silently
   behave like FSL_MERGE_TYPE_NORMAL:

   - If the being-merged-in content is marked as private.
   - If the being-merged-in content is not a leaf.
*/
FSL_MERGE_TYPE_INTEGRATE = -4,
/**
   Indicates a cherrypick merge, pulling in only the changes made to a
   specific checkin without otherwise inheriting its lineage.
*/
FSL_MERGE_TYPE_CHERRYPICK = -1,
/**
   Indicates a backout merge, a reverse cherrypick, backing out any
   changes which were added by the corresponding
   fsl_merge_opt::mergeRid.
*/
FSL_MERGE_TYPE_BACKOUT = -2
};
typedef enum fsl_merge_type_e fsl_merge_type_e;

/**
   UNDER CONSTRUCTION.

   Options for use with fsl_ckout_merge().
*/
struct fsl_merge_opt {
  /**
     The version of the repostitory to merge into the current
     checkout. This must be the `blob.rid` of a checkin artifact.
  */
  fsl_id_t mergeRid;
  /**
     The version of the most recent common ancestor. Must normally be
     0. The default is calculated automatically based on
     this->mergeRid and this->mergeType.

     This corresponds to fossil(1)'s `--baseline` merge flag.

     fsl_ckout_merge() will fail if this is >0 and it does not refer
     to a checkin version or if this->mergeType is
     FSL_MERGE_TYPE_CHERRYPICK.
  */
  fsl_id_t baselineRid;
  /**
     Specifies the merge type to perform. Certain merge-internal logic
     may override this. Specifically, integrate-merges may be treated
     as regular merges, as documented for FSL_MERGE_TYPE_INTEGRATE.
  */
  fsl_merge_type_e mergeType;
  /**
     Gets called once per merge-updated file, passed a fsl_ckup_state
     instance with information about the merged file and related
     metadata. May be NULL, in which case the merge process will do as
     much work as it can, even if that means doing certain
     questionable things (such as skipping updates of binary files or
     symlinks because it refuses to merge them). As a rule of thumb,
     if fossil(1) performs a given "questional" merge features without
     generating an error, fsl_ckout_merge() does as well. This
     callback gives clients a chance to decide that certain states
     _Simply Will Not Stand_ and cancel the merge by returning non-0
     (preferably after calling fsl_cx_err_set() on the passed-in
     fsl_merge_state::f object).

     The callback is called after any on-disk changes are made to
     the file, e.g. merging, file permissions, renaming, etc. However,
     when this->dryRun is true, filesystem-level changes are skipped.
  */
  fsl_merge_f callback;
  /**
     Client-defined state for use with this->callback.
  */
  void * callbackState;
  /**
     A hint to fsl_ckout_merge() about whether it needs to scan the
     checkout for changes. Set this to false ONLY if the calling code
     calls fsl_ckout_changes_scan() (or equivalent,
     e.g. fsl_vfile_changes_scan()) immediately before calling
     fsl_ckout_merge(), as that function requires a non-stale changes
     scan in order to function properly.
  */
  bool scanForChanges;
  /**
     If true, the extraction process will "go through the motions" but
     will not write any files to disk. It may still perform I/O such
     as stat()'ing to see, e.g., if it would have needed to overwrite
     a file. When in dry-run, this->callback is still called as if
     dry-run mode were not in effect. Thus the on-disk state may not
     actually reflect what the callback sees when dry-run mode is
     active.
  */
  bool dryRun;
  /**
     This flag is not part of the public API and will be removed
     once the merge operation's development has settled down.
  */
  unsigned short debug;
  /**
     TODO:

     - How to handle fossil's --binary GLOBPATTERN flag. Plain string
     or a glob list object or a stateful predicate function or... ?

     We currently rely entirely on the global `binary-glob` setting.
  */
};
/** Initialized-with-defaults fsl_merge_opt structure, intended for
    const-copy initialization. */
#define fsl_merge_opt_empty_m \
  {-1/*mergeRid*/,0/*baselineRid*/, \
   FSL_MERGE_TYPE_NORMAL/*mergeType*/, \
   NULL/*callback*/, NULL/*callbackState*/, \
   true/*scanForChanges*/, \
   false/*dryRun*/,0/*debug*/}
/** Initialized-with-defaults fsl_merge_opt structure, intended for
    non-const copy initialization. */
extern const fsl_merge_opt fsl_merge_opt_empty;

/**
   UNDER CONSTRUCTION and not yet well-tested.

   Performs a "merge" operation on the current checkout, merging in
   version opt->mergeRid. If that version has already been merged,
   this call has no SCM-related side effects.

   Returns 0 on success, any number of non-0 codes on error,
   including, _but not limited to_:

   - FSL_RC_NOT_A_CKOUT if f has no opened checkout.

   - FSL_RC_OOM on allocation error.

   - FSL_RC_TYPE if opt->mergeRid or opt->baselineRid do to refer to
     a checkin.

   - FSL_RC_PHANTOM if a file participating in the merge is
     a phantom.

   - FSL_RC_RANGE if the to-be-merged-in RID is the same as the
     current checkout RID or the same as the pivot/baseline of
     the merge.

   - FSL_RC_NOT_FOUND if no common ancestor can be found for use as a
     basis for the merge.

   - FSL_RC_MISUSE if the current checkout is empty (has an RID of 0).

   - Any number of DB- or I/O-related codes, as well as codes from
     underlying APIs such as fsl_vfile_changes_scan().

   For all but the most trivial argument validation errors or
   allocation errors, f's error state will be updated with a
   description of the problem.

   TODOs and potential TODOs:

   - There are certain illegal combinations of merge state which may
     require adding new result codes for. e.g. a no-op merge.

   - Empty directories may be left behind when a merge removes all
     files in a directory. fsl_ckout_update() handles that case but
     fsl_ckout_merge() currently does not.

*/
FSL_EXPORT int fsl_ckout_merge(fsl_cx * const f, fsl_merge_opt const * const opt);

/**
   If zDirName is a directory name which contains what appears to
   be a fossil checkout database (noting that only a cursory check is done - the
   db is not opened and validated), the name of that database file (minus
   the directory part) is returned, else NULL is returned. The returned bytes
   are static.

   @see fsl_ckout_dbnames()
*/
FSL_EXPORT char const * fsl_is_top_of_ckout(char const *zDirName);

/**
   Returns an array of strings with the base names of valid fossil checkout
   databases. The array is terminated by a NULL element.

   As of this writing, and for the foreseeable future, the list is
   comprised of only 3 elements, {".fslckout", "_FOSSIL_", NULL}, but
   the order of the non-NULL elements is unspecified by the interface.
*/
FSL_EXPORT char const ** fsl_ckout_dbnames(void);

/** Convenience typedef. */
typedef struct fsl_ckout_rename_opt fsl_ckout_rename_opt;
/**
   Callback type for use with fsl_ckout_rename(). It gets called once per
   iteration of a rename operation, along with the original options object
   for the rename and:

   - zSrcName is the checkout-relative original name of the file.
   - zDestname is the checkout-relative new name of the file.

   Both strings are owned by the calling operation and will be freed
   soon after this call returns. If the client needs them, they must
   make copies.

   It must returns 0 on success. If it returns non-0 then the current
   renaming op is cancelled (rolled back) and the result code is
   propagated back to the caller of fsl_ckout_rename().

   This gets called immediately after the associated db record is
   modified and before the filesystem move (if any) is performed.

   Design note: ideally the callback would be called after the
   filesystem move, but the way the moves are currently processed (as
   a batch after the db updates, noting that those updates may trigger
   variou error conditions) precludes that. Alternately, we could
   delay the callback until the file-move phase (noting that the
   file-move step is optional), and that might be a sensible change to
   make.
*/
typedef int (*fsl_ckout_rename_f)(fsl_cx *, fsl_ckout_rename_opt const *,
                                  char const * zSrcName, char const *zDestName);

/**
   Options object for use with fsl_ckout_rename().
*/
struct fsl_ckout_rename_opt {
  /**
     The source filename(s) or directory name(s) to rename. The
     contents of this list _must not_ be modified while
     fsl_ckout_rename() is running (e.g. via a callback function).
  */
  fsl_list const * src;
  /**
     The target filename or directory name to rename to.
  */
  char const * dest;
  /**
     If true, src and dest are resolved/normalized based on the current
     working directory, else they must be relative to the top of the
     checkout.
  */
  bool relativeToCwd;
  /**
     If true fsl_ckout_rename() will attempt to move files within the
     filesystem. If false, it will only do the db-side renaming.
  */
  bool doFsMv;
  /**
     If true, fsl_ckout_rename() will not perform any lasting
     operations but will "go through the motions" with the exception
     of actually attempting to move files on disk (if doFsMv is
     true). It will still report errors in this mode, with the
     exception that filesystem-level moving is not attempted so
     potential failures there cannot be detected.

     Achtung: in dry-run mode it will trigger a rollback of any
     pending transaction which is opened before fsl_ckout_rename() is
     called.
  */
  bool dryRun;
  /** Optional callback. May be NULL. */
  fsl_ckout_rename_f callback;
  /** Optional state for the callback. */
  void * callbackState;
};

/** Initialized-with-defaults fsl_ckout_rename_opt structure, intended for
    const-copy initialization. */
#define fsl_ckout_rename_opt_empty_m {NULL,NULL,true,false,false,NULL,NULL}

/** Initialized-with-defaults fsl_ckout_rename_opt structure, intended for
    non-const copy initialization. */
extern const fsl_ckout_rename_opt fsl_ckout_rename_opt_empty;

/**
   This routine renames one or more SCM-managed files matching all
   entries in opt->src to opt->dest within the current checkout. This
   updates the current checkout's vfile table with the changes, and
   optionally attempts to move the files within the filesystem, but
   does not commit anything, so the change may still be reverted later
   on.

   If an entry in opt->src matches an existing directory name within
   the SCM-managed file list, this function assumes that all files
   under that directory are to be moved.

   If opt->relativeToCwd is true then the destination name and all
   opt->src names are canonicalized based on the current working
   directory (see fsl_getcwd()), otherwise they are assumed to be
   relative to f's current checkout directory.

   If opt->dest refers to an _existing_ directory, when an opt->src
   entry refers to a directory then that whole directory, including the
   directory name part, is renamed. If opt->dest does not exist in the
   filesystem and if opt->src resolves to multiple inputs, opt->dest is
   assumed to be a new target directory but the renaming behavior of
   the opt->src files differs. Examples:

   - Case 1: opt->dest refers to an existing directory: moving
     directory foo/bar to baz will result in baz/bar.

   - Case 2: opt->dest does not refer to an existing directory: moving
   directory foo/bar to baz results in baz with the previous contents
   of foo/bar.

   Why? Because that's how fossil(1) does it.

   This function matches opt->src entries only against
   `vfile.pathname`, not `vfile.origname`.

   If opt->doFsMv is true then the final operation this function
   attempts is to rename source files to their new destination. It
   will only attempt this in cases where (A) the original file exists
   and (B) the destination file does _not_ exist. Any errors generated
   during this filesystem-level rename/move step _are ignored_ for two
   reasons: 1) fossil(1) does it that way and (2) after moving any
   files, trying to roll back and undo the filesystem-level operations
   would add a significant amount of complexity and new errror cases
   (what happens when a try-to-undo-rename fails?).

   Returns 0 on succcess. Potential errors include:

   - FSL_RC_OOM on allocation error.

   - FSL_RC_NOT_A_CKOUT if f has no opened checkout.

   - FSL_RC_MISUSE: opt->src contains multiple entries but the
   destination is not an _existing_ directory.

   - FSL_RC_ALREADY_EXISTS: cannot rename because the destination name
   is already in use by another record.

   - FSL_RC_TYPE: opt->dest refers to a non-directory and an opt->src
   entry refers to a directory.

   - Any potential DB-related errors.

   BUGS/Shortcomings:

   - If it fails moving files in the filesystem, it might have
   successfully already moved one or more source files, and those
   moves are not undone.

   - Depending on the case-sensitivity of the repo and the filesystem,
   it might (UNTESTED) fail to rename a file if the new name differs
   only in its case (e.g. `README.TXT` to `README.txt`). Those
   relavant code renames such vfile entries but leaves the filesystem
   entries intact because fossil(1) does it that way.

   - If it moves a whole directory full of files it leaves any
   original directories intact. Improving this is on the TODO list.
   Often, such directories have contents (e.g. compiled/generated/temp
   files) and cannot be removed.
*/
FSL_EXPORT int fsl_ckout_rename(fsl_cx * const f,
                                fsl_ckout_rename_opt const * opt);

/**
   Undoes a rename scheduled by fsl_ckout_rename(). zNewName is the
   current (renamed) name of the file.

   If relativeToCwd is true then zNewName is canonicalized based on
   the current working directory (see fsl_getcwd()), otherwise it is
   assumed to be relative to f's current checkout directory.

   On success, or if no such pending rename is found, it returns 0.
   If it actually performs a db-level rename then it sets
   `*didSomething` to true if didSomething is not NULL. It should
   arguably return FSL_RC_NOT_FOUND (or some such) if no matching
   rename is pending, but that currently feels overly-pedantic.

   If doFsMv is true and a db entry is renamed and a file with the
   new name exists in the filesystem then this function will
   _delete_ any file which has the original name and rename the zNewName
   file to its reverted name. If that fails, the operation as a
   whole will fail and the db changes will be rolled back. Note,
   however, that a file deleted by this operation cannot be recovered
   and that the deletion must be done before the rename is attempted.

   On error, returns any of a wide array of non-0 result codes, only
   two of which can come directly from this function: FSL_RC_OOM or
   FSL_RC_NOT_A_CKOUT. Any other non-zero result codes are propagated
   errors from lower-level code.
*/
FSL_EXPORT int fsl_ckout_rename_revert(fsl_cx * const f,
                                       char const * zNewName,
                                       bool relativeToCwd, bool doFsMv,
                                       bool *didSomething);

/**
    Fetches the vfile.pathname value for the given vfile.id
    entry. Results are undefined if f does not have an opened
    checkout. On success returns 0 and sets `*zOut` to the name,
    transfering ownership to the caller (who must eventually pass it
    to fsl_free()). If absolute is true then the returned name has the
    checkout dir prepended to it, else it is relative to the top of
    the repo.

    Potential TODO: this routine is in no way optimized for heavy use
    within an app, expecting to be only rarely used, e.g. in
    conjunction with fsl_ckout_rename()-like ops. If it sees any
    significant use it should be refactored to use a cached statement.
*/
FSL_EXPORT int fsl_vfile_pathname(fsl_cx * const f, fsl_id_t vfid,
                                  bool absolute, char **zOut);


/**
   Callback type for fsl_ckout_fs::xDirList(). It is called once per
   entry of the listed directory, with the entry's name (no directory
   part, not "." or ".."). If it returns non-0, the listing stops and
   xDirList() must return that value.
*/
typedef int (*fsl_ckout_fs_dir_f)(void * cbState, char const * zEntry);

/**
   Storage for a checkout's files: a set of operations through which
   the library's checkout code (checkout, update, merge, revert,
   stash, undo, commit and the change scan) reads and writes the
   files of the working copy, installed per context with
   fsl_cx_ckout_fs(). The default, fsl_ckout_fs_os, is the
   filesystem.

   It covers the working copy's files only. The checkout, repository
   and config databases are SQLite's business, and the current
   directory is still the filesystem's.

   All names are absolute, UTF-8, with '/' as the separator and no
   trailing '/', as the library builds them from the checkout
   directory. Each operation
   returns 0 on success or a FSL_RC_xxx code. Every operation which
   looks up a name (xStat(), xRead(), xUnlink(), xRename()'s source)
   must return FSL_RC_NOT_FOUND for a name which does not exist,
   because the library's callers branch on it.

   A storage with no symlinks (xSymlinkRead and xSymlinkCreate NULL)
   holds a link as a regular file containing the link's target, as
   the filesystem does on platforms without symlinks.

   Members other than xExecSet, xMtimeSet, xSymlinkRead,
   xSymlinkCreate, xCopy, xHash and xWriteBlob are required.
*/
struct fsl_ckout_fs {
  /**
     The version of this struct the implementation was written
     against: 1 or 2. Version 2 added xWriteBlob. Later versions may
     add members at the end. The library reads no member a struct's
     version does not have, so a version 1 struct may be allocated
     without the later members.
  */
  int iVersion;
  /**
     Populates *tgt with the type, size, mtime and permissions of
     zName. If derefLinks is true and zName is a symlink, it describes
     the link's target. Storage which has no symlinks ignores
     derefLinks.
  */
  int (*xStat)(void * state, char const * zName, fsl_fstat * tgt,
               bool derefLinks);
  /**
     Replaces tgt's contents with the full contents of file zName.
  */
  int (*xRead)(void * state, char const * zName, fsl_b * tgt);
  /**
     Creates or replaces file zName with the n bytes at src. zName's
     directory is created first by the library, via xMkdir().

     A storage wrapping another one (e.g. one from
     fsl_cx_ckout_fs_get() with some members replaced) to see every
     write must wrap xWriteBlob too, if the wrapped storage has one:
     the library writes the files of a checked-out version through
     xWriteBlob, not xWrite, when it is not NULL.
  */
  int (*xWrite)(void * state, char const * zName, void const * src,
                fsl_size_t n);
  /** Removes file zName. */
  int (*xUnlink)(void * state, char const * zName);
  /** Renames file zFrom to zTo, replacing zTo if it exists. */
  int (*xRename)(void * state, char const * zFrom, char const * zTo);
  /** Creates directory zName, whose parent exists. */
  int (*xMkdir)(void * state, char const * zName);
  /** Removes directory zName if it is empty, else fails. */
  int (*xRmdir)(void * state, char const * zName);
  /** Calls cb() for each entry of directory zDir. */
  int (*xDirList)(void * state, char const * zDir,
                  fsl_ckout_fs_dir_f cb, void * cbState);
  /**
     Sets or clears file zName's executable bit. May be NULL, in which
     case setting it does nothing.
  */
  int (*xExecSet)(void * state, char const * zName, bool isExec);
  /**
     Sets file zName's mtime, in seconds since the Unix epoch. May be
     NULL, in which case setting it does nothing.
  */
  int (*xMtimeSet)(void * state, char const * zName, fsl_time_t mtime);
  /**
     Replaces tgt's contents with the target of symlink zName. May be
     NULL if the storage has no symlinks, in which case xSymlinkCreate
     must be NULL too.
  */
  int (*xSymlinkRead)(void * state, char const * zName, fsl_b * tgt);
  /**
     Creates symlink zName pointing to zTarget. zName does not exist,
     and its directory does. May be NULL if the storage has no
     symlinks, in which case xSymlinkRead must be NULL too.
  */
  int (*xSymlinkCreate)(void * state, char const * zTarget,
                        char const * zName);
  /**
     Copies file zFrom to zTo as fsl_file_copy() does: creating zTo's
     directory and carrying over the executable bit. May be NULL, in
     which case the library reads zFrom whole and writes it to zTo. A
     storage which can copy without holding the whole file in memory
     should provide it.
  */
  int (*xCopy)(void * state, char const * zFrom, char const * zTo);
  /**
     Replaces tgt's contents with the lower-case hex SHA3-256 hash of
     file zName's contents if sha3 is true, else its SHA1 hash. May be
     NULL, in which case the library reads the file whole and hashes
     it. A storage which can hash without holding the whole file in
     memory should provide it.
  */
  int (*xHash)(void * state, char const * zName, bool sha3, fsl_b * tgt);
  /** Opaque state passed as the first argument of every member. */
  void * state;
  /**
     Version 2. Creates or replaces file zName with the content of
     blob rid of the context's repository, as the checkout code does
     to write a file of a checked-out version (checkout, update,
     revert, merge, and the manifest file). zName's directory is
     created first by the library, via xMkdir(), as for xWrite(). The
     library sets the executable bit and mtime afterwards, as after
     xWrite(). May be NULL, in which case the library reads the blob
     (fsl_content_get()) and passes it to xWrite(). A storage which
     can record the reference instead of copying the bytes, reading
     the blob only when the file is read, should provide it. It is
     given no fsl_cx: a storage which needs the context, e.g. to read
     the blob later, keeps it in its state.
  */
  int (*xWriteBlob)(void * state, char const * zName, fsl_id_t rid);
};
typedef struct fsl_ckout_fs fsl_ckout_fs;

/**
   The current version of struct fsl_ckout_fs, for its iVersion: what
   a storage written against this header sets, and what a caller sets
   in the struct it passes to fsl_cx_ckout_fs_get() or as
   fsl_cx_ckout_fs()'s pPrev, so that the copy has every member.
*/
#define FSL_CKOUT_FS_VERSION 2

/** Initialized-with-defaults fsl_ckout_fs instance, intended for
    const-copy initialization. Its iVersion is 0, which as f's
    storage means "none installed" and as a destination of
    fsl_cx_ckout_fs_get() means version 1: set iVersion to
    FSL_CKOUT_FS_VERSION before using it as one. */
#define fsl_ckout_fs_empty_m {0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL}
/** Initialized-with-defaults fsl_ckout_fs instance, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_ckout_fs fsl_ckout_fs_empty;

/**
   The filesystem as a fsl_ckout_fs, which every context uses unless
   another storage is installed: each member calls the fs.c function
   the checkout code always used (fsl_stat(), fsl_b_fill_from_filename(),
   fsl_b_to_filename(), fsl_file_unlink(), ...). A storage which keeps
   only some files elsewhere can delegate the rest to these members.
*/
FSL_EXPORT const fsl_ckout_fs fsl_ckout_fs_os;

/**
   Installs a bitwise copy of *pNew as f's checkout file storage (see
   fsl_ckout_fs). If pNew is NULL, the storage reverts to the
   filesystem, fsl_ckout_fs_os. If pPrev is not NULL, the previous
   storage is copied to it first, as fsl_cx_ckout_fs_get() copies it,
   so that a caller can restore it later: the caller sets
   pPrev->iVersion first, or the copy lacks xWriteBlob:

   ```
   fsl_ckout_fs prev = fsl_ckout_fs_empty;
   prev.iVersion = FSL_CKOUT_FS_VERSION;
   rc = fsl_cx_ckout_fs(f, &mine, &prev);
   ... // f uses mine
   rc = fsl_cx_ckout_fs(f, &prev, NULL); // back to what it was
   ```

   Only the members of pNew->iVersion are read: those a later version
   added are NULL in f's copy.

   Returns 0 on success, FSL_RC_MISUSE if pNew->iVersion is not 1 or
   2, or a required member is NULL, or exactly one of xSymlinkRead and
   xSymlinkCreate is NULL, or if a transaction is open on f, since
   files would then be split between two storages mid-operation. On
   error f's storage is unchanged.

   @see fsl_cx_ckout_fs_get()
*/
FSL_EXPORT int fsl_cx_ckout_fs(fsl_cx * const f, fsl_ckout_fs const * pNew,
                               fsl_ckout_fs * pPrev);

/**
   Stores a bitwise copy of f's checkout file storage into *dest:
   fsl_ckout_fs_os unless another one is installed. The caller sets
   dest->iVersion first to the version of the struct dest points to,
   which may have been allocated without the members of later
   versions: if it is 0 or 1, only the version 1 members are written
   (a storage's xWriteBlob is then not copied), and dest->iVersion is
   set to 1; if it is 2 or more, the whole struct is written.
   Installing a version 1 copy gives up the storage's xWriteBlob, so
   the library then writes those files through xWrite.

   @see fsl_cx_ckout_fs()
*/
FSL_EXPORT void fsl_cx_ckout_fs_get(fsl_cx const * const f,
                                    fsl_ckout_fs * dest);


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_CHECKOUT_H_INCLUDED */
/* end of file include/fossil-scm/checkout.h */
/* start of file include/fossil-scm/stash.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_STASH_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_STASH_H_INCLUDED
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

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

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

/** @file stash.h

    stash.h declares the checkout stash: uncommitted changes saved in
    the checkout db so that they can be reverted and applied again
    later, as with (fossil stash).

    The stash uses fossil(1)'s own "stash" and "stashfile" tables, so
    stashes saved by fossil(1) can be applied with these APIs and vice
    versa. The port follows fossil(1)'s src/stash.c, with Mark
    Jamsek's stash implementation in client/fnc/fnc.c as the guide to
    the equivalent libfossil APIs.

    Not yet supported: fossil(1)'s undo of stash operations, as
    libfossil does not yet have undo.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   Change types reported by fsl_stash_apply() for each stashed
   file.
*/
enum fsl_stash_e {
/** Sentinel value. */
FSL_STASH_NONE = 0,
/** An added file was written and queued for adding. */
FSL_STASH_ADD,
/** A removed file was deleted from the checkout. */
FSL_STASH_DELETE,
/**
   A file which was unchanged since the stash's baseline was
   overwritten with the stashed version.
*/
FSL_STASH_UPDATE,
/**
   A file which was changed since the stash's baseline was merged with
   the stashed version without conflicts.
*/
FSL_STASH_MERGE,
/**
   As for FSL_STASH_MERGE, but the merge had conflicts, which are
   marked in the file.
*/
FSL_STASH_CONFLICT,
/**
   A file which was changed since the stash's baseline could not be
   merged because it is binary or a symlink. It is left unchanged.
*/
FSL_STASH_UNMERGEABLE,
/**
   The file's name is not safe to write: it is outside the checkout,
   or a part of its path which should be a directory is not one. It
   was skipped.
*/
FSL_STASH_UNSAFE
};
typedef enum fsl_stash_e fsl_stash_e;

/**
   Callback type for fsl_stash_apply(). It is called once for
   each stashed file, after that file is handled. zName is the file's
   checkout-relative name, as it will be at the next check-in. If the
   stash renamed the file, zOrigName is its original name, else it is
   the same as zName. nConflicts is the number of merge conflicts for
   FSL_STASH_CONFLICT, else 0. state is the callbackState member of
   the options object.

   If it returns non-0, applying stops and that result is returned,
   noting that files written so far stay written.
*/
typedef int (*fsl_stash_f)(char const * zName,
                                 char const * zOrigName,
                                 fsl_stash_e change,
                                 unsigned nConflicts,
                                 void * state);

/**
   Options for fsl_stash_save().
*/
struct fsl_stash_save_opt {
  /**
     The stash's comment. May be NULL.
  */
  char const * comment;
  /**
     A NULL-terminated list of file or directory names to stash. If
     this is NULL or its first entry is NULL, all changes in the
     checkout are stashed.
  */
  char const * const * filenames;
  /**
     If true, this->filenames are relative to the current working
     directory, else to the checkout root.
  */
  bool relativeToCwd;
  /**
     If false (the default), the stashed changes are reverted after
     they are saved, as with (fossil stash save). If true, they are
     kept, as with (fossil stash snapshot).
  */
  bool keepChanges;
  /**
     Optional callback for the revert which follows the save. Ignored
     if this->keepChanges is true.
  */
  fsl_ckout_revert_f revertCallback;
  /**
     State for this->revertCallback.
  */
  void * revertCallbackState;
};
typedef struct fsl_stash_save_opt fsl_stash_save_opt;

/** Initialized-with-defaults fsl_stash_save_opt instance,
    intended for use in const-copy initialization. */
#define fsl_stash_save_opt_empty_m { \
  NULL/*comment*/, NULL/*filenames*/, true/*relativeToCwd*/, \
  false/*keepChanges*/, NULL/*revertCallback*/, NULL/*revertCallbackState*/ \
}

/** Initialized-with-defaults fsl_stash_save_opt instance,
    intended for use in non-const copy initialization. */
FSL_EXPORT const fsl_stash_save_opt fsl_stash_save_opt_empty;

/**
   Saves the checkout's uncommitted changes as a new stash, then
   reverts them unless opt->keepChanges is true. See
   fsl_stash_save_opt for the options.

   The stash records, for each changed file, whether it is added or
   removed, its executable and symlink state, its original and new
   names, and its content: a delta from the checkout's version for a
   modified file, the whole content for an added file, and nothing
   for a removed one.

   If stashId is not NULL, the new stash's ID is written to it on
   success.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOOP if there were no changes to stash, or none in the
   files named by opt->filenames (in which case no stash is created),
   or any number of db or I/O errors.

   The stash is saved in its own transaction, which is committed
   before the revert, as fossil(1) does, so that a failed revert
   cannot lose changes it already reverted on disk. If the revert
   fails, the stash is still saved and *stashId is still set, but
   the revert's error is returned. If the caller has a transaction
   open, the save joins it and the caller's commit decides.
*/
FSL_EXPORT int fsl_stash_save(fsl_cx * const f,
                              fsl_stash_save_opt const * opt,
                              fsl_id_t * stashId);

/**
   Options for fsl_stash_apply().
*/
struct fsl_stash_apply_opt {
  /**
     The stash to apply, or 0 for the most recent one.
  */
  fsl_id_t stashId;
  /**
     If true, the stash is dropped after it is applied, as with
     (fossil stash pop).
  */
  bool pop;
  /**
     If true, the checkout is first updated to the stash's baseline
     version, as with (fossil stash goto).
  */
  bool gotoBaseline;
  /**
     Optional per-file callback.
  */
  fsl_stash_f callback;
  /**
     State for this->callback.
  */
  void * callbackState;
};
typedef struct fsl_stash_apply_opt fsl_stash_apply_opt;

/** Initialized-with-defaults fsl_stash_apply_opt instance,
    intended for use in const-copy initialization. */
#define fsl_stash_apply_opt_empty_m { \
  0/*stashId*/, false/*pop*/, false/*gotoBaseline*/, \
  NULL/*callback*/, NULL/*callbackState*/ \
}

/** Initialized-with-defaults fsl_stash_apply_opt instance,
    intended for use in non-const copy initialization. */
FSL_EXPORT const fsl_stash_apply_opt fsl_stash_apply_opt_empty;

/**
   Applies a stash to the current checkout. For each stashed file:

   - An added file is written and queued for adding.
   - A removed file is deleted from the disk.
   - A modified file which is unchanged on disk since the stash's
     baseline is overwritten with the stashed version.
   - A modified file which was changed on disk since then is merged
     with the stashed version, three-way, with the stash's baseline
     version as the common ancestor. Conflicts are marked in the
     file. A binary file or symlink cannot be merged and is left
     unchanged.
   - A renamed file is moved to its new name.

   If nConflicts is not NULL, the number of files which had merge
   conflicts or could not be merged is written to it, as fossil(1)
   counts them, including, for gotoBaseline, files the update left in
   conflict. The callback gets each file's own conflict count.

   Returns 0 on success, even if there were conflicts. Returns
   FSL_RC_NOT_A_CKOUT if no checkout is opened, FSL_RC_NOT_FOUND if
   the stash does not exist or there are no stashes, or any number of
   db or I/O errors.

   The db side runs in a transaction, but files written before an
   error stay written.
*/
FSL_EXPORT int fsl_stash_apply(fsl_cx * const f,
                               fsl_stash_apply_opt const * opt,
                               unsigned * nConflicts);

/**
   Deletes the given stash, or every stash if stashId is negative.
   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOT_FOUND if stashId is positive and no such stash exists,
   or a db error.
*/
FSL_EXPORT int fsl_stash_drop(fsl_cx * const f, fsl_id_t stashId);

/**
   Changes the comment of the given stash. Unlike
   fsl_stash_apply(), a stashId of 0 does not mean the most
   recent stash. Returns 0 on success, FSL_RC_NOT_A_CKOUT if no
   checkout is opened, FSL_RC_NOT_FOUND if no such stash exists, or a
   db error.
*/
FSL_EXPORT int fsl_stash_rename(fsl_cx * const f, fsl_id_t stashId,
                                char const * zComment);

/**
   Writes the ID of the most recent stash to *stashId, or 0 if there
   are no stashes. Returns 0 on success, FSL_RC_NOT_A_CKOUT if no
   checkout is opened, or a db error.
*/
FSL_EXPORT int fsl_stash_latest(fsl_cx * const f, fsl_id_t * stashId);

/**
   Reconstructs the stashed content of one file and appends it to
   tgt, which is first reset. zName is the file's name at the next
   check-in, as stored in the stash. If baseline is not NULL, the
   file's content in the stash's baseline version is written to it,
   or it is left empty for an added file.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOT_FOUND if the stash or the file is not found, FSL_RC_TYPE
   if the file was removed in the stash (it has no content), or a db
   or delta error.

   Clients can use this to show a stash, e.g. as a diff between
   baseline and tgt. The stash's file list is in the checkout db's
   stashfile table.
*/
FSL_EXPORT int fsl_stash_content(fsl_cx * const f, fsl_id_t stashId,
                                 char const * zName, fsl_b * const tgt,
                                 fsl_b * const baseline);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_STASH_H_INCLUDED */
/* end of file include/fossil-scm/stash.h */
/* start of file include/fossil-scm/undo.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_UNDO_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_UNDO_H_INCLUDED
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

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

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

/** @file undo.h

    undo.h declares one level of undo and redo for the operations
    which change a checkout's files: fsl_ckout_update(),
    fsl_ckout_merge(), fsl_ckout_revert(), fsl_stash_apply() and
    fsl_stash_drop(), as with (fossil undo) and (fossil redo).

    Unlike fossil(1), which saves each file just before an operation
    writes it, libfossil records the state before an operation as a
    stash snapshot of the local changes, plus the checkout version and
    copies of the vfile and vmerge tables (as fossil(1)'s undo_vfile
    and undo_vmerge). Undo reverts, goes back to that version, writes
    each snapshot file back exactly, and restores vfile and vmerge.
    Redo does the same in the other direction.

    The undo state lives in the checkout db's fsl_undo* tables, apart
    from fossil(1)'s own undo tables, so (fossil undo) and
    fsl_undo() do not see each other's state.

    Differences from fossil(1):

    - Undo does not restore an unmanaged file which the update or
      merge overwrote, as the snapshot holds only managed changes.
      (Redo does restore unmanaged files at paths the undo took over,
      e.g. one left behind by an update which dropped a rename.)

    - Undo refuses if the checkout is no longer on the version the
      operation left it on (e.g. after a commit), and, unless forced,
      if its local changes or merge state changed after the
      operation, because restoring the earlier state would discard
      those changes. fossil(1) restores only the files the operation
      wrote, and a commit clears its undo state.

    - Undo of only some files, (fossil undo FILE...), is not
      supported.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   What fsl_undo_state() reports is available.
*/
enum fsl_undo_e {
/** Nothing can be undone or redone. */
FSL_UNDO_NONE = 0,
/** The most recent operation can be undone. */
FSL_UNDO_UNDO,
/** The most recent undo can be redone. */
FSL_UNDO_REDO
};
typedef enum fsl_undo_e fsl_undo_e;

/**
   Reports what can be undone or redone in f's checkout. *state is
   set to one of the fsl_undo_e values. If zLabel is not NULL, it is
   set to a description of the operation, e.g. "update", which the
   caller must pass to fsl_free(), or to NULL if *state is
   FSL_UNDO_NONE.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   or a db error.
*/
FSL_EXPORT int fsl_undo_state(fsl_cx * const f, fsl_undo_e * state,
                              char ** zLabel);

/**
   Undoes the most recent undoable operation, or, if redo is true,
   redoes the most recent undo.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOT_FOUND if there is nothing to undo (or redo),
   FSL_RC_MISUSE if called while another checkout operation is
   running on f, or FSL_RC_CONFLICT if the checkout is no longer on
   the version the operation left it on (e.g. after a commit), or if
   its local changes or merge state changed after the operation and
   force is false. force does not override a version change. On
   FSL_RC_CONFLICT nothing is changed.

   It runs in a transaction, but files it has written stay written if
   it fails partway.
*/
FSL_EXPORT int fsl_undo(fsl_cx * const f, bool redo, bool force);

/**
   Forgets any undo or redo state. Returns 0 on success,
   FSL_RC_NOT_A_CKOUT if no checkout is opened, or a db error.
*/
FSL_EXPORT int fsl_undo_reset(fsl_cx * const f);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_UNDO_H_INCLUDED */
/* end of file include/fossil-scm/undo.h */
/* start of file include/fossil-scm/confdb.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_CONFDB_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_CONFDB_H_INCLUDED
/*
  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-FileType: Code

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

    fossil-confdb.h declares APIs dealing with fossil's various
    configuration option storage backends.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   A flag type for specifying which configuration backend a given API
   should be applied to. Used by most of the fsl_config_XXX() APIS,
   e.g. fsl_config_get_int32() and friends.

   This type is named fsl_confdb_e (not the "db" part) because 3 of
   the 4 fossil-supported config storage backends are databases. The
   "versioned setting" backend, which deals with non-db local files,
   was encapsulated into this API long after the db-related options
   were
*/
enum fsl_confdb_e {
/** Sentinel value. Not for use with public APIs. */
FSL_CONFDB_NONE = 0,
/**
   Signfies the global-level (per system user) configuration area.

   Note that fsl_config_... APIs which use this do not currently open
   that database on demand due to the potential for downstream
   locking-related issues when the config db is left open, as well as
   locking-related issues here when a separate client or instance is
   holding that db open. That behaviour may change in the future.
*/
FSL_CONFDB_GLOBAL = 1,
/**
   Signfies the repository-level configuration area.
*/
FSL_CONFDB_REPO = 2,
/**
   Signfies the checkout-level (a.k.a. "local") configuration area.
*/
FSL_CONFDB_CKOUT = 3,

/**
   The obligatory special case...

   Versionable settings are stored directly in SCM-controlled files,
   each of which has the same name as the setting and lives in the
   .fossil-settings directory of a checkout. Though versionable
   settings _can_ be read from a non-checked-out repository, doing so
   requires knowning which version to fetch and is horribly
   inefficient, so there are currently no APIs for doing so.

   Note that the APIs which read and write versioned settings do not
   care whether those settings are valid for fossil(1).

   Reminder to self: SQL to find the checkins in which a versioned
   settings file was added or modified (ignoring renames and branches
   and whatnot).

   ```
select strftime('%Y-%m-%d %H:%M:%S',e.mtime) mtime,
b.rid, b.uuid from mlink m, filename f, blob b, event e
where f.fnid=m.fnid
and m.mid=b.rid
and b.rid=e.objid
and f.name='.fossil-settings/ignore-glob'
order by e.mtime desc
;
   ```

*/
FSL_CONFDB_VERSIONABLE = 4
};
typedef enum fsl_confdb_e fsl_confdb_e;

/**
   Returns the name of the db table associated with the given
   mode. Results are undefined if mode is an invalid value. The
   returned bytes are static and constant.

   Returns NULL for the role FSL_CONFDB_VERSIONABLE.
*/
FSL_EXPORT char const * fsl_config_table_for_role(fsl_confdb_e mode);

/**
   Returns a handle to the db associates with the given fsl_confdb_e
   value. Returns NULL if !f or if f has no db opened for that
   configuration role. Results are undefined if mode is an invalid
   value.

   For FSL_CONFDB_VERSIONABLE it returns the results of fsl_cx_db(),
   even though there is no database-side support for versionable files
   (which live in files in a checkout).
*/
FSL_EXPORT fsl_db * fsl_config_for_role(fsl_cx * const f, fsl_confdb_e mode);

/**
   Returns the int32 value of a property from one of f's config
   dbs, as specified by the mode parameter. Returns dflt if !f, f
   does not have the requested config db opened, no entry is found,
   or on db-level errors.
*/
FSL_EXPORT int32_t fsl_config_get_int32( fsl_cx * const f, fsl_confdb_e mode,
                                         int32_t dflt, char const * key );
/**
   int64_t counterpart of fsl_config_get_int32().
*/
FSL_EXPORT int64_t fsl_config_get_int64( fsl_cx * const f, fsl_confdb_e mode,
                                         int64_t dflt, char const * key );

/**
   fsl_id_t counterpart of fsl_config_get_int32().
*/
FSL_EXPORT fsl_id_t fsl_config_get_id( fsl_cx * const f, fsl_confdb_e mode,
                                       fsl_id_t dflt, char const * key );
/**
   double counterpart of fsl_config_get_int32().
*/
FSL_EXPORT double fsl_config_get_double( fsl_cx * const f, fsl_confdb_e mode,
                                         double dflt, char const * key );


/**
   Boolean countertpart of fsl_config_get_int32().

   fsl_str_bool() is used to determine the booleanness (booleanity?)
   of a given config option.
*/
FSL_EXPORT bool fsl_config_get_bool( fsl_cx * const f, fsl_confdb_e mode,
                                     bool dflt, char const * key );

/**
   A convenience form of fsl_config_get_buffer().  If it finds a
   config entry it returns its value. If *len is not NULL then *len is
   assigned the length of the returned string, in bytes (and is set to
   0 if NULL is returned). Any errors encounters while looking for
   the entry are suppressed and NULL is returned.

   The returned memory must eventually be freed using fsl_free(). If
   len is not NULL then it is set to the length of the returned
   string. Returns NULL for any sort of error or for a NULL db value.

   If capturing error state is important for a given use case, use
   fsl_config_get_buffer() instead, which provides the same features
   as this one but propagates any error state.

   Achtung: because this is intended only for fossil config data, some
   of which supports #-style single-line comments, this function
   strips such content from its value (as of 2026-08-29, in order to
   resolve a discrepancy between libfossil and fossil(1)).
*/
FSL_EXPORT char * fsl_config_get_text( fsl_cx * const f, fsl_confdb_e mode,
                                       char const * key,
                                       fsl_size_t * len );

/**
   The fsl_b-type counterpart of fsl_config_get_int32().

   Replaces the contents of the given buffer (re-using any memory it
   might have) with a value from a config region. Returns 0 on
   success, FSL_RC_NOT_FOUND if no entry was found or the requested db
   is not opened, FSL_RC_OOM on allocation errror.

   If mode is FSL_CONFDB_VERSIONABLE, this operation requires
   a checkout and returns (if possible) the contents of the file
   named {CHECKOUT_ROOT}/.fossil-settings/{key}.

   This strips out #-style comment lines as described for
   fsl_config_get_text().

   On any sort of error, including the inability to find or open
   a versionable-settings file, non-0 is returned:

   - FSL_RC_OOM on allocation error

   - FSL_RC_NOT_FOUND if either the database referred to by mode is
   not opened or a matching setting cannot be found.

   - FSL_RC_ACCESS is a versionable setting file is found but cannot
   be opened for reading.

   - FSL_RC_NOT_A_CKOUT if mode is FSL_CONFDB_VERSIONABLE and no
   checkout is opened.

   - Potentially one of several db-related codes if reading a
   non-versioned setting fails.

   In the grand scheme of things, the inability to load a setting is
   not generally an error, so clients are not expected to treat it as
   fatal unless perhaps it returns FSL_RC_OOM, in which case it likely
   is.
*/
FSL_EXPORT int fsl_config_get_buffer( fsl_cx * const f, fsl_confdb_e mode,
                                      char const * key, fsl_b * const b );


/**
   If f has an opened checkout, this replaces b's contents (re-using
   any existing memory) with an absolute path to the filename for that
   setting: {CHECKOUT_ROOT}/.fossil-settings/{key}

   This routine neither verifies that the given key is a valid
   versionable setting name nor that the file exists: it's purely a
   string operation.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if f has no checkout
   opened, FSL_RC_MISUSE if key is NULL, empty, or if
   fsl_is_simple_pathname() returns false for the key, and FSL_RC_OOM
   if appending to the buffer fails.
 */
FSL_EXPORT int fsl_config_versionable_filename(fsl_cx *f, char const * key, fsl_b *b);

/**
   Sets a configuration variable in one of f's config databases, as
   specified by the mode parameter. Returns 0 on success.  val may
   be NULL. Returns FSL_RC_MISUSE if f does not have that database
   opened or key is NULL, FSL_RC_RANGE if key is empty, and
   FSL_RC_NOT_A_CKOUT if mode is FSL_CONFDB_VERSIONABLE and f has no
   opened checkout. On error, f's error state gives the setting name
   and the database or file it was being written to.

   If mode is FSL_CONFDB_VERSIONABLE, it attempts to write/overwrite
   the corresponding file in the current checkout.

   If mem is NULL and mode is not FSL_CONFDB_VERSIONABLE then an SQL
   NULL is bound instead of an empty blob. For FSL_CONFDB_VERSIONABLE
   an empty file will be written for that case.

   If mode is FSL_CONFDB_VERSIONABLE, this does NOT queue any
   newly-created versionable setting file for inclusion into the
   SCM. That is up to the caller. See
   fsl_config_versionable_filename() for info about an additional
   potential usage error case with FSL_CONFDB_VERSIONABLE.

   Pedantic side-note: the input text is saved as-is. No trailing
   newline is added when saving to FSL_CONFDB_VERSIONABLE because
   doing so would require making a copy of the input bytes just to add
   a newline to it. The non-text fsl_config_set_XXX() APIs add a
   newline when writing to their values out to a versionable config
   file because it costs them nothing to do so and text files "should"
   have a trailing newline.

   Potential TODO: if mode is FSL_CONFDB_VERSIONABLE and the key
   contains directory components, e,g, "app/x", we should arguably use
   fsl_mkdir_for_file() to create those components. As of this writing
   (2021-03-14), no such config keys have ever been used in fossil.

   @see fsl_config_versionable_filename()
*/
FSL_EXPORT int fsl_config_set_text( fsl_cx * const f, fsl_confdb_e mode,
                                    char const * key, char const * val );

/**
   The blob counterpart of fsl_config_set_text(). If len is
   negative then fsl_strlen(mem) is used to determine the length of
   the memory.

   If mem is NULL and mode is not FSL_CONFDB_VERSIONABLE then an SQL
   NULL is bound instead of an empty blob. For FSL_CONFDB_VERSIONABLE
   an empty file will be written for that case.
*/
FSL_EXPORT int fsl_config_set_blob( fsl_cx * const f, fsl_confdb_e mode, char const * key,
                                    void const * mem, fsl_int_t len );
/**
   int32 counterpart of fsl_config_set_text().
*/
FSL_EXPORT int fsl_config_set_int32( fsl_cx * const f, fsl_confdb_e mode,
                                     char const * key, int32_t val );
/**
   int64 counterpart of fsl_config_set_text().
*/
FSL_EXPORT int fsl_config_set_int64( fsl_cx * const f, fsl_confdb_e mode,
                                     char const * key, int64_t val );
/**
   fsl_id_t counterpart of fsl_config_set_text().
*/
FSL_EXPORT int fsl_config_set_id( fsl_cx * const f, fsl_confdb_e mode,
                                  char const * key, fsl_id_t val );
/**
   fsl_double counterpart of fsl_config_set_text().
*/
FSL_EXPORT int fsl_config_set_double( fsl_cx * const f, fsl_confdb_e mode,
                                      char const * key, double val );
/**
   Boolean counterpart of fsl_config_set_text().

   For compatibility with fossil conventions, the value will be saved
   in the string form "on" or "off". When mode is
   FSL_CONFDB_VERSIONABLE, that value will include a trailing newline.
*/
FSL_EXPORT int fsl_config_set_bool( fsl_cx * const f, fsl_confdb_e mode,
                                    char const * key, bool val );

/**
   "Unsets" (removes) the given key from the given configuration database.
   It is not considered to be an error if the config table does not
   contain that key.

   Returns FSL_RC_MISUSE if key is NULL or empty or f does not have
   the database for mode opened.

   Returns FSL_RC_UNSUPPORTED, changing no setting, if mode is
   FSL_CONFDB_VERSIONABLE. It "could" hypothetically remove a
   checked-out copy of a versioned setting, then queue the file for
   removal in the next checkin, but it does not do so. It might, in
   the future, be changed to do so, or at least to remove the local
   settings file.
*/
FSL_EXPORT int fsl_config_unset( fsl_cx * const f, fsl_confdb_e mode,
                                 char const * key );

/**
   Begins (or recurses) a transaction on the given configuration
   database.  Returns 0 on success, non-0 on error. On success,
   fsl_config_transaction_end() must eventually be called with the
   same parameters to pop the transaction stack. Returns
   FSL_RC_MISUSE if no db handle is opened for the given
   configuration mode. Assuming all arguments are valid, this
   returns the result of fsl_db_txn_begin() and propagates
   any db-side error into the f object's error state.

   This is primarily intended as an optimization when an app is
   making many changes to a config database. It is not needed when
   the app is only making one or two changes.

   @see fsl_config_transaction_end()
   @see fsl_db_txn_begin()
*/
FSL_EXPORT int fsl_config_transaction_begin(fsl_cx * const f, fsl_confdb_e mode);

/**
   Pops the transaction stack pushed by
   fsl_config_transaction_begin(). If rollback is true then the
   transaction is set roll back, otherwise it is allowed to
   continue (if recursive) or committed immediately (if not
   recursive).  Returns 0 on success, non-0 on error. Returns
   FSL_RC_MISUSE if no db handle is opened for the given
   configuration mode. Assuming all arguments are valid, this
   returns the result of fsl_db_txn_end() and propagates
   any db-side error into the f object's error state.

   @see fsl_config_transaction_begin()
   @see fsl_db_txn_end()
*/
FSL_EXPORT int fsl_config_transaction_end(fsl_cx * const f, fsl_confdb_e mode, bool rollback);

/**
   Populates li as a glob list from the given configuration key.
   Uses (versionable/repo/global) config settings, in that order.
   It is not an error if one or more of those sources is missing -
   they are simply skipped.

   Note that gets any new globs appended to it, as per
   fsl_glob_list_append(), as opposed to replacing any existing
   contents.

   Returns 0 on success, but that only means that there were no
   errors, not that any entries were necessarily added to li.

   Arguably a bug: this function does not open the global config if
   it was not already opened, but will use it if it is opened. This
   function should arbuably open and close it in that case. That said,
   there are cases which prohibit closing of the config db and this
   function cannot know if one of those cases is active.
*/
FSL_EXPORT int fsl_config_globs_load(fsl_cx * const f, fsl_list * const li, char const * key);

/**
   Fetches the preferred name of the "global" db file for the current
   user by assigning it to *zOut. Returns 0 on success, in which case
   *zOut is updated and non-0 on error, in which case *zOut is not
   modified.  On success, ownership of *zOut is transferred to the
   caller, who must eventually free it using fsl_free().

   Errors include:

   - FSL_RC_OOM on allocation error
   - FSL_RC_NOT_FOUND if no relevant environment variables are set
     from which to form the db path. On Unix-like systems that means
     none of FOSSIL_HOME, HOME, or XDG_CONFIG_HOME.
   - FSL_RC_TYPE (Unix-like systems) if neither FOSSIL_HOME nor
     XDG_CONFIG_HOME is set and $HOME is not a directory.

   This function has no fsl_cx and sets no error message;
   fsl_config_open() reports these failures in its context's error
   state.

   The locations searched for the database file are
   platform-dependent...

   Unix-like systems are searched in the following order:

   1) If the FOSSIL_HOME environment var is set, use
   $FOSSIL_HOME/.fossil.

   2) If $HOME/.fossil already exists, use that.

   3) If XDG_CONFIG_HOME environment var is set, use
   $XDG_CONFIG_HOME/fossil.db.

   4) If $HOME/.config is a directory, use $HOME/.config/fossil.db

   5) Fall back to $HOME/.fossil (historical name).

   Windows:

   1) If $FOSSIL_HOME is set, use that directory.
   2) If $LOCALAPPDATA is set, use that directory.
   3) If $APPDATA is set, use that directory.
   4) If $USERPROFILE is set, use that directory.
   5) If $HOMEDRIVE and $HOMEPATH are set, use that directory.

   If none of the above are set, FSL_RC_NOT_FOUND is returned.

   The name `_fossil` is appended to the first of the above-listed
   locations which is set in the environment.

   All platforms:

   Except where listed above, this function does not check whether the
   file already exists or is a database.
*/
FSL_EXPORT int fsl_config_global_preferred_name(char ** zOut);

/**
   A variant of fsl_config_get_int32() which can search through multiple
   config sources in an order specified by the caller.

   zCfg must be a NUL-terminated list of case-sensitive letters
   corresponding to config sources: any of (c, r, v, g) for checkout,
   repo, versionable, and global, respectively. Each source, if
   available, is searched, in the order provided, until either the
   given key is found in that source or no more sources are available,
   in which case dflt is returned. Any missing sources are silently
   skipped over (e.g. if 'c' is provided but no checkout is opened,
   that is not considered an error by this function).

   Errors are silently ignored and cause dflt to be returned.

   @see fsl_configs_get_int64()
   @see fsl_configs_get_id()
   @see fsl_configs_get_bool()
   @see fsl_configs_get_text()
*/
FSL_EXPORT int32_t fsl_configs_get_int32(fsl_cx * const f, char const * zCfg, int32_t dflt, char const * key);

/**
   The int64_t counterpart of fsl_configs_get_int32().
*/
FSL_EXPORT int64_t fsl_configs_get_int64(fsl_cx * const f, char const * zCfg, int64_t dflt, char const * key);

/**
   The fsl_id_t counterpart of fsl_configs_get_int32().
*/
FSL_EXPORT fsl_id_t fsl_configs_get_id(fsl_cx * const f, char const * zCfg, fsl_id_t dflt, char const * key);

/**
   The bool counterpart of fsl_configs_get_int32().
*/
FSL_EXPORT bool fsl_configs_get_bool(fsl_cx * const f, char const * zCfg, bool dflt, char const * key);

/**
   The double counterpart of fsl_configs_get_int32().
*/
FSL_EXPORT double fsl_configs_get_double(fsl_cx * const f, char const * zCfg, double dflt, char const * key);

/**
   The buffer counterpart of fsl_configs_get_int32(). This variant
   collects, if found, its results in the given buffer (its memory, if
   any, is reused by this routine). It returns 0 if an entry is found,
   FSL_RC_OOM on buffer allocation error, and FSL_RC_NOT_FOUND if no
   match is found in any of the listed sources (noting that missing
   sources are silently skipped). The full range of errors reported by
   fsl_config_get_buffer() is not supported here: only FSL_RC_OOM and
   FSL_RC_NOT_FOUND are reported.

   @see fsl_configs_get_text()
*/
FSL_EXPORT int fsl_configs_get_buffer( fsl_cx * const f, char const *zCfg,
                                       char const * key, fsl_b * const b );

/**
   The C-string counterpart of fsl_configs_get_int32(). If the final
   argument is not NULL then if a match is found then its length (in
   bytes) is assigned to (*len). Returns NULL if no match is found.

   If non-NULL is returned, ownership is transfered to the caller, who
   must eventually pass the value to fsl_free().

   Note that this function silently ignores any errors,
   e.g. allocation failure for the result string will be reported by
   returning NULL (which is indistinguishable from it not finding a
   match).

   @see fsl_configs_get_buffer()
*/
FSL_EXPORT char * fsl_configs_get_text(fsl_cx * const f, char const * zCfg, char const * key,
                                       fsl_size_t * len);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_CONFDB_H_INCLUDED */
/* end of file include/fossil-scm/confdb.h */
/* start of file include/fossil-scm/vpath.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_VPATH_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_VPATH_H_INCLUDED
/*
  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-FileType: Code

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

  *****************************************************************************
  This file declares public APIs relating to calculating paths via
  Fossil SCM version history.
*/

#if defined(__cplusplus)
extern "C" {
#endif

typedef struct fsl_vpath_node fsl_vpath_node;
typedef struct fsl_vpath fsl_vpath;

/**
   Holds information for a single node in a path of checkin versions.

   @see fsl_vpath
*/
struct fsl_vpath_node {
  /** ID for this node */
  fsl_id_t rid;
  /** True if pFrom is the parent of rid */
  bool fromIsParent;
  /** True if primary side of common ancestor */
  bool isPrimary;
  /* HISTORICAL: Abbreviate output in "fossil bisect ls" */
  bool isHidden;
  /** Node this one came from. */
  fsl_vpath_node *pFrom;
  union {
    /** List of nodes of the same generation */
    fsl_vpath_node *pPeer;
    /** Next on path from beginning to end */
    fsl_vpath_node *pTo;
  } u;
  /** List of all nodes */
  fsl_vpath_node *pAll;
};

/**
   A utility type for collecting "paths" between two checkin versions.
*/
struct fsl_vpath{
  /** Current generation of nodes */
  fsl_vpath_node *pCurrent;
  /** All nodes */
  fsl_vpath_node *pAll;
  /** Nodes seen before */
  fsl_id_bag seen;
  /** Number of steps from first to last. */
  int nStep;
  /** Earliest node in the path. */
  fsl_vpath_node *pStart;
  /** Common ancestor of pStart and pEnd */
  fsl_vpath_node *pPivot;
  /** Most recent node in the path. */
  fsl_vpath_node *pEnd;
};

/**
   An empty-initialize fsl_vpath object, intended for const-copy
   initialization.
*/
#define fsl_vpath_empty_m {0,0,fsl_id_bag_empty_m,0,0,0,0}

/**
   An empty-initialize fsl_vpath object, intended for copy
   initialization.
*/
FSL_EXPORT const fsl_vpath fsl_vpath_empty;


/**
   Returns the first node in p's path.

   The returned node is owned by path may be invalidated by any APIs
   which manipulate path.
*/
FSL_EXPORT fsl_vpath_node * fsl_vpath_first(fsl_vpath *p);

/**
   Returns the last node in p's path.

   The returned node is owned by path may be invalidated by any APIs
   which manipulate path.
*/
FSL_EXPORT fsl_vpath_node * fsl_vpath_last(fsl_vpath *p);

/**
   Returns the next node p's path.

   The returned node is owned by path may be invalidated by any APIs
   which manipulate path.

   Intended to be used like this:

   ```
   for( p = fsl_vpath_first(path) ;
   p ;
   p = fsl_vpath_next(p)){
   ...
   }
   ```
*/
FSL_EXPORT fsl_vpath_node * fsl_vpath_next(fsl_vpath_node *p);

/**
   Returns p's path length.
*/
FSL_EXPORT int fsl_vpath_length(fsl_vpath const * p);

/**
   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 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 ridFrom to ridTo
   (inclusive), storing the result state in path. If path has
   state before this is called, it is cleared by this call.

   ridFrom and ridTo must both be valid checkin version RIDs.

   If directOnly is true, then use only the "primary" links from
   parent to child.  In other words, ignore merges.

   On success, returns 0 and path->pStart will point to the
   beginning of the path (the ridFrom node). If pStart is 0 then no
   path could be found but 0 is still returned.

   Elements of the path can be traversed like so:

   ```
   fsl_vpath path = fsl_vpath_empty;
   fsl_vpath_node * n = 0;
   int rc = fsl_vpath_shortest(f, &path, versionFrom, versionTo, 1, 0);
   if(rc) { ... error ... }
   for( n = fsl_vpath_first(&path); n; n = fsl_vpath_next(n) ){
   ...
   }
   fsl_vpath_clear(&path);
   ```

   On error, f's error state may be updated with a description of the
   problem.
*/
FSL_EXPORT int fsl_vpath_shortest( fsl_cx * const f, fsl_vpath * const path,
                                   fsl_id_t ridFrom, fsl_id_t ridTo,
                                   bool directOnly, bool oneWayOnly );

/**
   This variant of fsl_vpath_shortest() stores the shortest direct
   path from version ridFrom to version ridTo 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:

   ```
   rid INT UNIQUE
   generation INTEGER PRIMARY KEY
   ```

   Where [rid] is a checkin version RID and [generation] is the
   1-based number of steps from ridFrom, including ridFrom (so
   ridFrom'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 ridFrom,
                                                    fsl_id_t ridTo,
                                                    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
   :/.
*/
FSL_EXPORT void fsl_vpath_reverse(fsl_vpath * path);


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_VPATH_H_INCLUDED */
/* end of file include/fossil-scm/vpath.h */
/* start of file include/fossil-scm/bisect.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_BISECT_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_BISECT_H_INCLUDED
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

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

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

/** @file bisect.h

    bisect.h declares a bisect session, as with (fossil bisect): mark
    check-ins good or bad, and step the checkout to the midpoint of the
    path between the innermost good and bad ones until one check-in is
    left.

    The session lives in the checkout db's vvar table under fossil(1)'s
    own names (bisect-good, bisect-bad, bisect-log, bisect-complete and
    the bisect-OPTION settings), so a session started with fossil(1) can
    be continued with these APIs and vice versa.

    The path between good and bad is computed as fossil(1) 2.29's
    path_shortest() does, including its priority queue's ordering of
    equally short paths and its "skip" (hidden) check-ins, so that each
    step picks the same check-in fossil(1) would. That is a separate
    implementation from fsl_vpath_shortest(), which predates those
    changes in fossil(1).
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   Verdicts for fsl_bisect_mark().
*/
enum fsl_bisect_e {
/** The check-in does not have the problem. */
FSL_BISECT_GOOD = 1,
/** The check-in has the problem. */
FSL_BISECT_BAD,
/** The check-in cannot be tested, e.g. it does not build. */
FSL_BISECT_SKIP
};
typedef enum fsl_bisect_e fsl_bisect_e;

/**
   Records a verdict for check-in rid, or the current checkout's
   version if rid is 0, in the bisect log. A good or bad verdict
   replaces the session's good or bad check-in, unless rid already is
   that check-in, in which case nothing is logged, as in fossil(1).
   Like fossil(1), a skip is logged only once the log has a good or bad
   entry.

   This does not move the checkout: call fsl_bisect_next() for that,
   as (fossil bisect) does when its auto-next option is on.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_RANGE for an invalid verdict, or a db error.
*/
FSL_EXPORT int fsl_bisect_mark(fsl_cx * const f, fsl_bisect_e verdict,
                               fsl_id_t rid);

/**
   Removes the most recent good, bad or skip entry from the bisect log
   and recomputes the good and bad check-ins from what remains, as
   (fossil bisect undo) does, except that skip entries are passed over
   (fossil(1) 2.29 takes a skip entry for a good check-in of 0).

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOT_FOUND if the log is empty, or a db error.
*/
FSL_EXPORT int fsl_bisect_undo(fsl_cx * const f);

/**
   Ends the bisect session: forgets the good and bad check-ins, the
   log and whether the session is complete. Options are kept, except
   the linear option, which fossil(1) also resets. Returns 0 on
   success, FSL_RC_NOT_A_CKOUT if no checkout is opened, or a db error.
*/
FSL_EXPORT int fsl_bisect_reset(fsl_cx * const f);

/**
   Session state, as reported by fsl_bisect_state() and
   fsl_bisect_next().
*/
struct fsl_bisect_state_t {
  /** The innermost good check-in, or 0. */
  fsl_id_t good;
  /** The innermost bad check-in, or 0. */
  fsl_id_t bad;
  /**
     For fsl_bisect_next(): the check-in the checkout was (or would be)
     updated to, or 0 if the bisect is complete.
  */
  fsl_id_t next;
  /**
     The number of steps on the path between good and bad, not
     counting skipped check-ins.
  */
  int span;
  /**
     An estimate of the steps remaining: the base-2 logarithm of span,
     rounded up, as fossil(1) reports it.
  */
  int stepsLeft;
  /**
     For fsl_bisect_state(): true if the session has finished. For
     fsl_bisect_next(): true if this step found nothing left to test.
  */
  bool complete;
};
typedef struct fsl_bisect_state_t fsl_bisect_state_t;

/** Initialized-with-defaults fsl_bisect_state_t instance. */
FSL_EXPORT const fsl_bisect_state_t fsl_bisect_state_t_empty;

/**
   Reports the session's good and bad check-ins and whether it is
   complete. The next, span and stepsLeft members are left 0.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   or a db error.
*/
FSL_EXPORT int fsl_bisect_state(fsl_cx * const f, fsl_bisect_state_t * st);

/**
   Picks the next check-in to test: the midpoint of the path between
   the good and bad check-ins, skipping skipped ones, or, with the
   linear option on, the check-in next to the good one. If uOpt is not
   NULL, the checkout is then updated to it with fsl_ckout_update(),
   using uOpt with its checkinRid member replaced. If there is no such
   check-in, the session is marked complete instead.

   On success st, if not NULL, describes the result.

   Returns 0 on success (including when the bisect is complete),
   FSL_RC_NOT_A_CKOUT if no checkout is opened, FSL_RC_MISUSE if
   neither a good nor a bad check-in has been marked, FSL_RC_NOT_FOUND
   if there is no path between them, or a db or update error.
*/
FSL_EXPORT int fsl_bisect_next(fsl_cx * const f, fsl_ckup_opt const * uOpt,
                               fsl_bisect_state_t * st);

/**
   Computes the path between the session's good and bad check-ins
   into path, from the good one to the bad one, with isHidden set on
   skipped check-ins. If only one of them is set, the path is that
   one check-in. path is cleared first and must eventually be passed
   to fsl_vpath_clear().

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_MISUSE if neither a good nor a bad check-in has been
   marked, FSL_RC_NOT_FOUND if there is no path between them, or a db
   error.
*/
FSL_EXPORT int fsl_bisect_path(fsl_cx * const f, fsl_vpath * const path);

/**
   Gets, and if zNewValue is not NULL first sets, the bisect option
   zName: "auto-next", "direct-only", "display" or "linear", which
   are kept as fossil(1) keeps them. If zValue is not NULL, *zValue
   is set to the option's value, or its default, which the caller must
   pass to fsl_free().

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOT_FOUND for an unknown option, or a db error.
*/
FSL_EXPORT int fsl_bisect_option(fsl_cx * const f, char const * zName,
                                 char const * zNewValue, char ** zValue);

/**
   Returns true if the bisect option zName, which must be one of the
   boolean ones, is on, as fossil(1) decides it: a value of "on",
   "yes" or "true" (in any case) or a non-zero number is on, "off",
   "no", "false" or "0" is off, and anything else, or no checkout,
   means the option's default.
*/
FSL_EXPORT bool fsl_bisect_option_is_on(fsl_cx * const f,
                                        char const * zName);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_BISECT_H_INCLUDED */
/* end of file include/fossil-scm/bisect.h */
/* start of file include/fossil-scm/patch.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_PATCH_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_PATCH_H_INCLUDED
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

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

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

    patch.h declares APIs for fossil(1)-compatible binary patches, as
    with (fossil patch). A patch is a single file which captures all
    of the uncommitted changes of a checkout so that they can be
    applied to another checkout of the same repository, typically on
    another machine.

    A patch file is an SQLite database with these tables, as defined
    by fossil(1)'s src/patch.c:

    - cfg(key,value): metadata. See fsl_patch_info.

    - chng(pathname,origname,hash,isexe,islink,delta): one row per
      changed file. pathname is the file's name at the next check-in
      and origname its name before a rename, else NULL. hash is the
      baseline version's hash of the file, or NULL for a new file.
      delta is NULL for a removed file, the compressed full content
      for a new file, else a compressed fossil delta from the baseline
      content, with a length of 0 if the content is unchanged.

    - patchmerge(type,mhash): optional. One row per pending merge,
      where type is one of "merge", "cherrypick", "backout" or
      "integrate".

    Patches created by these APIs can be applied by fossil(1) and vice
    versa.

    Not yet supported: undo of an applied patch.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   Options for fsl_patch_create().
*/
struct fsl_patch_create_opt {
  /**
     The file to write the patch to. If this is NULL, the patch is
     passed to this->out instead.
  */
  char const * filename;
  /**
     If true and this->filename already exists, it is overwritten,
     else fsl_patch_create() fails with FSL_RC_ALREADY_EXISTS.
  */
  bool overwrite;
  /**
     Output channel for the patch if this->filename is NULL. The
     patch is binary and is passed to it in one or more calls.
  */
  fsl_output_f out;
  /**
     State for this->out.
  */
  void * outState;
  /**
     The name of the machine the patch is created on, recorded in the
     patch for informational purposes only. May be NULL, in which
     case it is not recorded. The library does not look this up
     itself.
  */
  char const * hostname;
};
typedef struct fsl_patch_create_opt fsl_patch_create_opt;

/** Initialized-with-defaults fsl_patch_create_opt instance,
    intended for use in const-copy initialization. */
#define fsl_patch_create_opt_empty_m { \
  NULL/*filename*/, false/*overwrite*/, NULL/*out*/, \
  NULL/*outState*/, NULL/*hostname*/ \
}

/** Initialized-with-defaults fsl_patch_create_opt instance,
    intended for use in non-const copy initialization. */
FSL_EXPORT const fsl_patch_create_opt fsl_patch_create_opt_empty;

/**
   Creates a patch of all uncommitted changes in f's checkout,
   including pending merges, as with (fossil patch create). See
   fsl_patch_create_opt for the options.

   The checkout is scanned for changes first, so the caller need not
   do so.

   Unlike fossil(1), each file's executable bit and symlink state are
   taken from the file itself. fossil(1) takes them from the checkout
   db, which a changes scan does not update when only they change, so
   its patches lose such a change.

   The patch is built in memory and written only once it is complete,
   so an error does not leave a partial patch file behind. It is
   written even if there are no changes, as fossil(1) does.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_MISUSE if opt->filename and opt->out are both NULL,
   FSL_RC_ALREADY_EXISTS if opt->filename exists and opt->overwrite
   is false, FSL_RC_TYPE if opt->filename exists but is not a file,
   any result code returned by opt->out, or any number of db or I/O
   errors.
*/
FSL_EXPORT int fsl_patch_create(fsl_cx * const f,
                                fsl_patch_create_opt const * opt);

/**
   Opaque handle to an opened patch. It is created by
   fsl_patch_open_file() or fsl_patch_open_mem() and freed by
   fsl_patch_close(). It must not outlive the fsl_cx it was opened
   with.
*/
typedef struct fsl_patch fsl_patch;

/**
   Opens the patch file zFile, read-only, and assigns *pOut to a new
   handle to it, which the caller must eventually pass to
   fsl_patch_close(). Neither a repository nor a checkout need be
   opened.

   The patch is validated before it is accepted: it must be a
   well-formed SQLite database which passes SQLite's quick_check and
   has the tables and columns described in this file's docs. Note
   that a patch is untrusted input, so the database is opened in
   SQLite's defensive mode with untrusted-schema handling. The file
   names in it are not checked here but by fsl_patch_apply().

   Returns 0 on success, FSL_RC_NOT_FOUND if zFile does not exist,
   FSL_RC_SYNTAX if it is not a valid patch, FSL_RC_OOM, or a db
   error. On error *pOut is not modified.
*/
FSL_EXPORT int fsl_patch_open_file(fsl_cx * const f, char const * zFile,
                                   fsl_patch ** pOut);

/**
   Works like fsl_patch_open_file() but reads the patch from the n
   bytes of memory at src, e.g. a patch read from stdin or from a
   remote command. The memory is copied, so the caller still owns
   src and need not keep it alive.

   In addition to the errors fsl_patch_open_file() can return, this
   returns FSL_RC_SYNTAX if n is less than 512, the smallest possible
   SQLite database.
*/
FSL_EXPORT int fsl_patch_open_mem(fsl_cx * const f, void const * src,
                                  fsl_size_t n, fsl_patch ** pOut);

/**
   Frees all resources owned by p. A no-op if p is NULL.
*/
FSL_EXPORT void fsl_patch_close(fsl_patch * p);

/**
   Metadata from a patch's cfg table. Any member may be NULL if the
   patch does not have that entry. All strings are owned by the
   fsl_patch they come from and are valid until it is closed.
*/
struct fsl_patch_info {
  /** Hash of the check-in the patch's changes are relative to. */
  char const * baseline;
  /** The repository's project code. */
  char const * projectCode;
  /** The repository's project name. */
  char const * projectName;
  /** The user who created the patch. */
  char const * user;
  /** The machine the patch was created on. */
  char const * hostname;
  /** The absolute path of the checkout the patch was created in. */
  char const * ckoutDir;
  /** The absolute path of the repository it was created in. */
  char const * repoDb;
  /** When the patch was created, as a Julian day, or 0 if unknown. */
  double date;
};
typedef struct fsl_patch_info fsl_patch_info;

/**
   Returns p's metadata. It is read when p is opened, so this cannot
   fail. The result is owned by p.
*/
FSL_EXPORT fsl_patch_info const * fsl_patch_info_get(fsl_patch const * p);

/**
   One changed file in a patch, as passed to fsl_patch_each_f.
*/
struct fsl_patch_entry {
  /** The file's checkout-relative name at the next check-in. */
  char const * name;
  /** The file's name before it was renamed, or NULL if it was not
      renamed. */
  char const * origName;
  /** The file's hash in the baseline version, or NULL if the file is
      new. */
  char const * baselineHash;
  /** True if the file is new (not in the baseline). */
  bool isNew;
  /** True if the file is removed. */
  bool isDeleted;
  /** True if an existing file's content changed. Always false for a
      new or removed file, and for one which is only renamed or whose
      permissions changed. */
  bool isModified;
  /** True if the file is executable. */
  bool isExe;
  /** True if the file is a symlink. */
  bool isLink;
};
typedef struct fsl_patch_entry fsl_patch_entry;

/**
   Callback type for fsl_patch_each(). e and the memory it points to
   are valid only for the duration of the call. If it returns non-0,
   iteration stops and that result is returned from fsl_patch_each(),
   except that FSL_RC_BREAK stops iteration and fsl_patch_each()
   returns 0.
*/
typedef int (*fsl_patch_each_f)(fsl_patch_entry const * e, void * state);

/**
   Callback type for fsl_patch_each_merge(), passed the type and hash
   of one pending merge. It works as fsl_patch_each_f does.
*/
typedef int (*fsl_patch_merge_f)(fsl_merge_type_e type,
                                 char const * zHash, void * state);

/**
   Calls cb once for each changed file in p, ordered by name, passing
   it state. Returns 0 on success, the result of cb as described for
   fsl_patch_each_f, or a db error.
*/
FSL_EXPORT int fsl_patch_each(fsl_patch * const p, fsl_patch_each_f cb,
                              void * state);

/**
   Calls cb once for each pending merge recorded in p, in the order in
   which they are recorded, passing it state. Entries with an unknown
   merge type or a malformed hash are skipped, as fossil(1) does.
   Returns 0 on success, including if p has no merges, the result of
   cb as described for fsl_patch_each_f, or a db error.
*/
FSL_EXPORT int fsl_patch_each_merge(fsl_patch * const p,
                                    fsl_patch_merge_f cb, void * state);

/**
   Reconstructs one file of patch p, for example to show the patch as a
   diff, as (fossil patch diff) does. p's context must have a
   repository opened, which must hold the patch's baseline versions.
   zName is the file's name as fsl_patch_entry::name has it.

   If tgt is not NULL, it is reset, then the file's content as the
   patch leaves it is written to it: empty for a removed file, and
   the baseline content for a file which is only renamed or whose
   permissions changed.

   If baseline is not NULL, it is reset, then the file's content in
   the patch's baseline is written to it: empty for a new file. Unlike
   fossil(1), which shows a removed file as an empty diff because its
   patches record no hash for it, a removed file's baseline content
   is looked up in the baseline check-in.

   Returns 0 on success, FSL_RC_NOT_A_REPO if no repository is opened,
   FSL_RC_NOT_FOUND if p has no file named zName or a baseline version
   which is needed is not in the repository, FSL_RC_SYNTAX for a
   malformed hash or file content, FSL_RC_DELTA_INVALID_xxx for a
   malformed delta, or a db error.
*/
FSL_EXPORT int fsl_patch_content(fsl_patch * const p, char const * zName,
                                 fsl_b * const tgt, fsl_b * const baseline);

/**
   The steps reported by fsl_patch_apply()'s callback.
*/
enum fsl_patch_apply_e {
/** Sentinel value. */
FSL_PATCH_APPLY_NONE = 0,
/**
   A pre-existing local change was reverted, because
   fsl_patch_apply_opt::force was true. The name is that of the
   reverted file.
*/
FSL_PATCH_APPLY_REVERT,
/**
   The checkout was updated to the patch's baseline. The name is the
   baseline's hash.
*/
FSL_PATCH_APPLY_BASELINE,
/**
   A pending merge was re-done. The name is the merged version's
   hash.
*/
FSL_PATCH_APPLY_MERGE,
/**
   A file which a merge changed but the patch does not mention was
   reverted, as fossil(1) does.
*/
FSL_PATCH_APPLY_UNMERGE,
/** A file was removed. */
FSL_PATCH_APPLY_DELETE,
/** A file was renamed. origName is its former name. */
FSL_PATCH_APPLY_RENAME,
/** A file's content or permissions were changed. */
FSL_PATCH_APPLY_EDIT,
/** A new file was written and queued for adding. */
FSL_PATCH_APPLY_NEW
};
typedef enum fsl_patch_apply_e fsl_patch_apply_e;

/**
   Callback type for fsl_patch_apply(). It is called after each step
   is done, or in place of doing it in a dry run. zName is the
   checkout-relative file name or a hash, as documented for each
   fsl_patch_apply_e value. zOrigName is the file's former name for
   FSL_PATCH_APPLY_RENAME, else NULL.

   If it returns non-0, applying stops and that result is returned,
   noting that files written so far stay written.
*/
typedef int (*fsl_patch_apply_f)(fsl_patch_apply_e step,
                                 char const * zName,
                                 char const * zOrigName,
                                 void * state);

/**
   Options for fsl_patch_apply().
*/
struct fsl_patch_apply_opt {
  /**
     If true and the checkout has uncommitted changes, they are
     reverted, and permanently lost, before the patch is applied. If
     false, a checkout with changes is an error.
  */
  bool force;
  /**
     If true, nothing is changed, but the callback is told what
     would have been done.
  */
  bool dryRun;
  /**
     Optional per-step callback.
  */
  fsl_patch_apply_f callback;
  /**
     State for this->callback.
  */
  void * callbackState;
};
typedef struct fsl_patch_apply_opt fsl_patch_apply_opt;

/** Initialized-with-defaults fsl_patch_apply_opt instance,
    intended for use in const-copy initialization. */
#define fsl_patch_apply_opt_empty_m { \
  false/*force*/, false/*dryRun*/, NULL/*callback*/, \
  NULL/*callbackState*/ \
}

/** Initialized-with-defaults fsl_patch_apply_opt instance,
    intended for use in non-const copy initialization. */
FSL_EXPORT const fsl_patch_apply_opt fsl_patch_apply_opt_empty;

/**
   Applies patch p to f's checkout, as with (fossil patch apply), in
   this order:

   1. If the checkout has changes and opt->force is true, they are
      reverted.

   2. If the checkout is not at the patch's baseline, it is updated
      to it.

   3. The patch's pending merges, if any, are re-done, then any file
      which they changed but which the patch does not mention is
      reverted. That follows fossil(1) (2024-12-16): such changes were
      not part of the original checkout's state.

   4. Removed files are removed, renamed files are renamed, and
      changed and new files are written, with new ones queued for
      adding.

   Unlike fossil(1), a new empty file is added, and a change to only a
   file's executable or symlink state is applied. fossil(1) drops both.

   Before anything is changed, the patch is checked: a file name which
   is not a simple relative path or is a reserved name, a hash which
   is not a full artifact hash, or a baseline (of the patch or of any
   file) which is not in the repository causes the whole patch to be
   rejected. When a file is written, removed or renamed, its path is
   also checked against symlinked or non-directory parent directories
   at that time.

   In a dry run, the callback is not told which files step 3 would
   revert, as that depends on the outcome of merges which are not
   done.

   Returns 0 on success. Returns FSL_RC_NOT_A_CKOUT if no checkout is
   opened, FSL_RC_REPO_MISMATCH if the patch's project code differs
   from the repository's, FSL_RC_CONFLICT if the checkout has changes
   and opt->force is false, FSL_RC_NOT_FOUND or FSL_RC_PHANTOM if the
   baseline or a file's baseline version is not in the repository
   (it may need to be synced first), FSL_RC_RANGE for an unsafe file
   name, FSL_RC_SYNTAX for a malformed hash or file content,
   FSL_RC_DELTA_INVALID_xxx for a malformed delta, the result of
   opt->callback, or any number of db or I/O errors.

   The db side runs in a transaction, which is rolled back on error
   or in a dry run, but files written before an error stay written.
*/
FSL_EXPORT int fsl_patch_apply(fsl_cx * const f, fsl_patch * const p,
                               fsl_patch_apply_opt const * opt);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_PATCH_H_INCLUDED */
/* end of file include/fossil-scm/patch.h */
/* start of file include/fossil-scm/auth.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_AUTH_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_AUTH_H_INCLUDED
/*
  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-FileType: Code

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

  ******************************************************************************
  This file declares public APIs for handling fossil
  authentication-related tasks.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   If f has an opened repository, this function forms a hash from:

   "zProjectCode/zLoginName/zPw"

   (without the quotes)

   where zProjectCode is typically a repository-dependent series of
   random bytes. If zProjCode is 0 then fsl_repo_project_code() is
   used to fetch it. (The project code is stored in the repository's
   config table under the key 'project-code'.)

   The returned string is owned by the caller, who must eventually
   fsl_free() it.

   Returns NULL if zProjCode is 0 and fsl_repo_project_code() fails,
   in which case f's error state holds that function's result
   (FSL_RC_NOT_FOUND if the repository has no project-code), or on
   allocation error.

   All arguments except zProjCode must be non-NULL or behavior is
   undefined.

   Potential TODO:

   - in fossil(1), this function generates a different result (it
   returns a copy of zPw) if the project code is not set, under
   the assumption that this is "the first xfer request of a
   clone."  Whether or not that will apply at this level to
   libfossil remains to be seen.
*/

FSL_EXPORT char * fsl_sha1_shared_secret2( fsl_cx * const f, char const * zLoginName,
                                           char const * zPw, char const * zProjCode );

/**
   Equivalent to fsl_sha1_shared_secret2(f,zLoginName,zPw,NULL).
*/
FSL_EXPORT char * fsl_sha1_shared_secret( fsl_cx * const f, char const * zLoginName,
                                          char const * zPw );

/**
   Fetches the login group name (if any) for the given context's
   current repositorty db. If f has no opened repo, 0 is returned.

   If the repo belongs to a login group, its name is returned in the
   form of a NUL-terminated string. The returned value (which may be
   0) is owned by the caller, who must eventually fsl_free() it. The
   value (unlike in fossil(1)) is not cached because it may change
   via modification of the login group.
*/
FSL_EXPORT char * fsl_repo_login_group_name(fsl_cx * const f);

/**
   Fetches the login cookie name associated with the current repository
   db, or 0 if no repository is opened.

   The returned (NUL-terminated) string is owned by the caller, who
   must eventually fsl_free() it. The value is not cached in f because
   it may change during the lifetime of a repo (if a login group is
   set or removed).

   The login cookie name is a string in the form "fossil-XXX", where
   XXX is the first 16 hex digits of either the repo's
   'login-group-code' or 'project-code' config values (in that order).
*/
FSL_EXPORT char * fsl_repo_login_cookie_name(fsl_cx * const f);

/**
   Searches for a user ID (from the repo.user.uid DB field) for a given
   username and password. The password may be either its hashed form or
   non-hashed form (if it is not exactly 40 bytes long, that is!).

   On success, 0 is returned and *pId holds the ID of the
   user found (if any).  *pId will be set to 0 if no match for the
   name/password was found, or positive if a match was found.

   If any of the arguments are NULL, or zUsername is empty,
   FSL_RC_MISUSE is returned. f must have an opened repo, else
   FSL_RC_NOT_A_REPO is returned. If the repo has no project-code,
   FSL_RC_NOT_FOUND is returned. On a db error, that error is
   reported via f's error state.

*/
FSL_EXPORT int fsl_repo_login_search_uid(fsl_cx * const f, char const * zUsername,
                                         char const * zPasswd, fsl_id_t * pId);

/**
   Clears all login state for the given user ID. If the ID is negative
   then ALL logins are cleared. Has no effect on the built-in
   pseudo-users.

   Returns non-0 on error, and not finding a matching user ID is not
   considered an error.

   Returns FSL_RC_MISUSE if f is NULL. f must have an opened repo, or
   FSL_RC_NOT_A_REPO is returned. On a db error, that error is
   reported via f's error state.

   TODO: there are currently no APIs for _setting_ the state this
   function clears! As of mid-2026 they are managed by the sync layer.
*/
FSL_EXPORT int fsl_repo_login_clear( fsl_cx * const f, fsl_id_t userId );


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_AUTH_H_INCLUDED */
/* end of file include/fossil-scm/auth.h */
/* start of file include/fossil-scm/forum.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_FORUM_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_FORUM_H_INCLUDED
/*
  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-FileType: Code

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

  ******************************************************************************
  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.
*/
int fsl_repo_install_schema_forum(fsl_cx *f);


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_FORUM_H_INCLUDED */
/* end of file include/fossil-scm/forum.h */
/* start of file include/fossil-scm/sync.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_SYNC_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_SYNC_H_INCLUDED
/*
  Copyright 2025 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

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

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

/** @file sync.h

    sync.h declares APIs dealing with fossil repository
    synchronization.
*/


#if defined(__cplusplus)
extern "C" {
#endif

typedef struct fsl_sc fsl_sc;

/**
   Callback for xfer-layer debugging messages. TODO consolidate this
   with the fsl_msg system.
*/
typedef void (*fsl_xfer_dbg_f)(fsl_xfer *xf, char const * zMsg);

/**
   Internal part of fsl_sc, uplifted into its own struct to simplify
   proper intialization of them in downstream fsl_sc implementations.
*/
struct fsl_xfer_dbg {
  /**
     This optional method is intended to be set by client-level code,
     not the sync channel implementor.

     If not NULL, the library or fsl_sc implementations may emit
     debugging output via this function.

     For output channel legibility, zMsg should always end with a
     newline (fsl_xfer_debug() and friends will automatically add one
     if needed).

     Implementations are free to mangle or emit the message in any
     form they like.

     Design note: its return type is void, but experience with binding
     C to Java and C++ shows that such bindings may need to propagate
     unexpected exceptions (e.g. resource acquisition failure, logging
     failure, etc.) somehow through the C API, and the conventional
     generic way to do that is to have a result code.  In normal use,
     it is never expected that a debugging function fails in a way
     which impacts the non-debugging functionality, but if an
     implementation absolutely must report an error, they should call
     fsl_xfer_error(), and that will be propagated back from this
     call. Channels, however, are _not_ required to check that after
     every debug call - they may assume success when the debug
     function is called, as the debug channel should not interfere
     with the sync channel's operation. That said, most of the
     fsl_xfer APIs become no-ops when its error state is set, causing
     the error to be implicitly propagated.

     @see fsl_xfer_debug_f_FILE()
     @see fsl_xfer_debug_f_buffer()
  */
  fsl_xfer_dbg_f callback;

  /**
     Available in callback() implementations via ch->debug.state.

     This memory is not owned by this object. It's owned by whoever
     set this member to non-NULL.
  */
  void * state;

  /**
     This is a scratch buffer solely for internal use by:

     1) library APIs like fsl_xfer_debugf()

     2) fsl_sc method implementations which do not themselves call
        into (1) while using this buffer.

     Without this, fsl_xfer_debug() becomes unduly memory-costly. This
     memory is owned by the library and gets cleared by
     fsl_sc_cleanup().  fsl_sc::cleanup() implementations may clean it
     up but are not required to.
  */
  fsl_b b;
};

typedef struct fsl_xfer_dbg fsl_xfer_dbg;

/** Empty-initialized fsl_xfer_dbg instance for use in cleanly
    const-copy initializing objects. */
#define fsl_xfer_dbg_empty_m {.callback=0, .state=0, .b=fsl_b_empty_m}

/** Empty-initialized instance for use in cleanly initializing
    objects. */
extern const fsl_xfer_dbg fsl_xfer_dbg_empty;

/**
   Frees any memory which may be owned by p but does not free p (which
   is typically stack-allocated).
*/
FSL_EXPORT void fsl_xfer_dbg_cleanup( fsl_xfer_dbg * p );

/**
   Flags for use with fsl_sc::flags. The top-most 8 bits are reserved
   for use by common library-level flags which a fsl_sc implementation
   may choose to support or may be required to support.
*/
enum fsl_sc_F_lib_e {
  /**
     Tells the fsl_sc impl that it should post data using the HTTP
     Content-Type value of "application/x-fossil" instead of
     "application/x-fossil-uncompressed". The former will have a
     fossil-compressed response payload[^1] whereas the latter will
     have an uncompressed response. Compressed payloads require far
     more memory to process but can save considerable network
     bandwidth.

     fsl_sc implementations are required to honor this flag, in that
     they must set the appropriate Content-Type request header, so
     that the library can Do The Right Thing without requiring that
     each fsl_sc implementation know whether to stream or buffer the
     content.

     This is a _hint_ for the remote, but the remote may override
     that, sending uncompressed responses instead of compressed.
     The remote will never do the opposite, converting a request for
     an uncompressed response to a compressed one.

     Compression may be handled differently for certain sync response
     types. e.g., a protocol-version-3 clone request will _not_ emit a
     fully-compressed response because most of the response body is
     already compressed in that case. The fsl_sc implementations need
     not concern themselves with that, however.

     Similarly, when fossil is operated via its "test-http" facility,
     as it does for non-networked/file-level sync, it does not
     compress responses.

     When this flag is set, the sync process will read all of the
     response content from the fsl_sc instance and then take over
     reading of the response from there so that fsl_sc implementations
     do not have to deal with those details.

     Because compression support is so memory-hungry, it is opt-in
     flag instead of an opt-out. Compression will save network
     bandwidth but costs the client application and the remote fossil
     instance boatloads of RAM.

     [^1]: zlib compress() with a 4-byte big-endian header encoding
           the decompressed size.
  */
  FSL_SC_F_COMPRESSED = 0x40000000,

  /**
     For impls with this flag set, the library will populate their
     fsl_sc::requestHeaders immediately before calling the impl's
     submit() method. Some impls generate their own headers or feed
     them into a proxy application in a different way, so don't need
     this. e.g. the curl-binary-based impl passes headers to curl
     in the form of CLI flags.
  */
  FSL_SC_F_REQUEST_HEADERS = 0x20000000,

  /**
     Impls which use temp files must honor this flag by _not_ deleting
     those files, so that they can be examined for testing and
     debugging.

     Implementations are recommended to send a fsl_cx_emit()
     message with the type FSL_MSG_TMPFILE and the name of the
     file in the message at the time when they would have otherwise
     been deleted, to facilitate matching temp files to their purpose.
  */
  FSL_SC_F_LEAVE_TEMP_FILES = 0x10000000,

  /**
     Impls which might, due to shelling out, emit info to stderr are
     expected to honor this flag and redirect stderr to /dev/null (or
     equivalent) if at all possible.
  */
  FSL_SC_F_SUPPRESS_STDERR = 0x08000000,

  /**
     Impls which use TLS must honor this flag by accepting any server
     certificate, without verifying its chain or its host name. The
     connection is then open to a man-in-the-middle attack. It
     corresponds to fossil(1)'s --accept-any-cert flag.
  */
  FSL_SC_F_TLS_ACCEPT_ANY_CERT = 0x04000000,

  /**
     For channels which do not speak HTTP. The library does not parse
     HTTP headers from the reply, so submit() must not make read()
     return any. Instead, submit() sets fsl_sc::reply to describe the
     reply body, which read() then returns from its first byte. The
     flag says nothing about the request: it may be combined with
     FSL_SC_F_REQUEST_HEADERS, for a channel which speaks HTTP to its
     peer but delimits the reply itself, and the library then builds
     fsl_sc::requestHeaders as it does without this flag. Without
     FSL_SC_F_REQUEST_HEADERS the channel carries the login card
     passed to submit() in whatever way it likes.
  */
  FSL_SC_F_NO_HTTP = 0x02000000,

  /**
     The mask of FSL_SC_F_... bits which are reserved for use by
     library-level options.
  */
  FSL_SC_F_lib_mask = 0x7FFF0000,

  /**
     The mask of FSL_SC_F_... bits which are reserved for use by
     client-level options.
  */
  FSL_SC_F_client_mask = ~FSL_SC_F_lib_mask
};

/**
   Indicates that fsl_sc::read() must read exactly 1 line of
   input. Its precise value is not well-defined but it is guaranteed
   to be of the same type as fsl_sc::read()'s final parameter. It is
   not an enum entry because we cannot (in C99) portably make an enum
   be precisely of a specific integer type.
*/
#define FSL_SC_READ_LINE ((fsl_int_t)-1)

/**
   Indicates that fsl_sc::read() must transfer or copy all of its
   input into the result buffer. See FSL_SC_READ_LINE for more
   details. It does _not_ have a well-defined value beyond that it is
   guaranteed to be negative and distinct from FSL_SC_READ_LINE, but
   must not be changed willy-nilly because it gets baked into all
   client code.
*/
#define FSL_SC_READ_ALL ((fsl_int_t)-2147483648)

/**
   Initialization modes for use with fsl_sc::init() implementations.
*/
enum fsl_sc_init_e {
  /**
     Indicates that the fsl_sc instance should initialize any core
     resources but not necessarily any request/response resources.

     See fsl_sc::init() for more details.
  */
  FSL_SC_INIT_INITIAL = 0x01,

  /**
     Indicates that the object must (re)initialize any state needed
     for constructing a request. e.g. initializing a buffer or temp
     file. The xfer layer may use this to compose a follow-up response
     while it is still reading a remote's response.

     See fsl_sc::init() for more details.

     Design note: there is no FSL_SC_INIT_RESPONSE counterpart because
     that role is effectively filled by fsl_sc::submit(), which
     initiates the processing of any response.
  */
  FSL_SC_INIT_REQUEST = 0x02
};

/**
   The fsl_sc class encapsulates a streamable (as opposed to
   random-access) I/O channel intended solely for use in implementing
   fossil(1)'s sync protocol in libfossil in a synchronous,
   I/O-channel-agnostic manner.  (The name "sc" is an abbreviation of
   "sync channel".)  The idea is that we can hook up arbitrary
   streamable I/O channels via this interface, e.g. HTTP-, SSH-, and
   file-driven channels.

   Each instance must be fully populated to set up its fsl_cx, I/O
   methods, and non-NULL values for all required methods (init(),
   cleanup(), etc.). Each instance may have arbitrary state associated
   with it, but whether such state must be provided by the user, or is
   created/initialized by the open() implementation, is
   implementation-defined.

   A channel's lifecycle, in terms of its API, goes something like:

   - User populates a state object of the type required by the
     channel.

   - User cleanly initializes a fsl_sc instance by copy-initializing
     it from a known-good starting point, e.g. fsl_sc_empty or
     fsl_sc_popen. We'll call this object "sc".

   - User sets sc.state.p if necessary for the implementation.
     e.g. fsl_sc_popen requires that its state pointer refer to a
     properly-populated fsl_sc_popen_state object, e.g. a copy of
     fsl_sc_popen_state_curl.

   - User passes it off to the library for handling. A bit of vague
     hand-waving there.

   - Its init() method is called.

   - Its append() method will be called an arbitrary number of times
     to populate it with a fossil sync request payload.

   - Its submit() method is called to finalize the request payload
     and send it wherever it needs to go.

   - Its read() method is used to read the response payload. Sync
     protocol "cards" are read line-by-line and card-level payloads
     are read in their-payload-sized chunks.

   - For a multi-round-trip sync, its init() method is called once per
     round trip, starting the process over.

   - Its cleanup() method is called to clean it up.


   A client applies a channel of its own to a sync or a clone through
   fsl_xfer_config::channel. What the library requires of it:

   - init(), append(), submit() and read() must not be NULL and
     impl.p must not be NULL. A channel which lacks any of them is
     refused with FSL_RC_MISUSE and a message which names what it
     lacks. cleanup() is optional, and self() defaults to
     fsl_sc_self().

   - A method has failed if it returns non-0 or if it set the
     transfer's error state with fsl_xfer_error() or one of its
     siblings. If it set that state, the library reports that error as
     it is, whatever the method returned, so a method which fails
     should set a message and return the same code. If it returned
     non-0 without setting it, the library sets it to that code with a
     message which names the channel and the method. A read() which
     reaches the end of its input returns FSL_RC_BREAK, which is not a
     failure.

   - A read() asked for a positive number of bytes must append exactly
     that many, and a read() asked for FSL_SC_READ_LINE must append at
     least one byte. If it returns 0 having appended anything else
     the library fails the transfer with FSL_RC_MISUSE and a message
     which names the channel and says how many bytes were asked for
     and how many were appended.
*/
struct fsl_sc {
  /**
     The "transfer context" for this channel. This is set by the
     library and is needed by many related APIs.
  */
  fsl_xfer * xfer;

  /**
     A debugging-purposes name for this channel,
     e.g. "http-socket". The bytes are considered to be static, and
     must outlive any instance of this class which uses them.
  */
  char const * name;

  /**
     The remote fossil URL.

     It is up to the client to either set up the URL before passing
     this object on to the library or to ensure that the
     "last-sync-url" repository config entry (a URL string) is of a
     schema compatible with this instance.

     It is also up to the client to ensure that the URL scheme matches
     the fsl_sc implementation. How best to do that is still TBD.

     This memory is owned by this object.

     Recall that fsl_b_external() is a convenient way to wrap a (const
     char *) in this without having to allocate.
  */
  fsl_url url;

  /**
     Flags for customizing certain behaviors. See fsl_sc_F_lib_e.
  */
  fsl_flag32_t flags;

  /**
     Implementation-dependent state.
  */
  struct {
    /**
       Arbitrary state for implementations. Its ownership is
       implementation-defined, as is whether this object's init()
       method will populate this or whether the client must provide
       it. If this object owns it, its cleanup() method must free the
       memory and clear this member. If this object does not own this
       memory, whether it should clear this member is
       implementation-defined (but normally they should unless it
       points to static/global memory).
    */
    void * p;
    /**
       An optional value which uniquely identifies a specific
       type. Intended as a semi-type-safety measure for this->state.p.
       i.e. don't assume p is of the desired type unless this matches
       some well-defined value (which need not, and probably should
       not, be public).
    */
    void const * type;
  } impl;

  /**
     this->init()'s responsibility is to initialize and validate any
     resources which may be implied via this->impl.

     The second argument tells the implementation what type of
     initialization is required, as per the fsl_sc_init_e docs.

     FSL_SC_INIT_INITIAL is only ever passed one time per object and
     is guaranteed to be called before FSL_SC_INIT_REQUEST is. If the
     channel needs to perform any validation, that is the time to do
     it.

     FSL_SC_INIT_REQUEST is called each time a new request body needs
     to be generated, including the initial request. Implementations
     must discard any prior request-specific state when initialized
     with this value.

     ch->flags must be set before calling this and must not be
     modified afterwards. The library will set the ch->xfer member.

     It is up to the direct users of this API to ensure that their
     fsl_sc instances contain no randomly-initialized state before the
     initial call to this function. i.e. cleanly initialize _all_
     member state.

     This call may, depending on the impl, initialize ch->impl,
     whereas some channel implementations may require that the caller
     populate ch->impl with an implementation-defined "something".
     Those details are to be documented for each concrete
     implementation. The former strategy is of course preferred but
     some channels may require inputs which the library cannot account
     for.

     Implementations must return 0 on success. On error they must
     return a fsl_rc_e value and should ideally call fsl_xfer_error()
     on ch->xfer to report an error message and return its result.

     Regardless of success or failure, clients are required to
     eventually call the cleanup() method if they call init(). On a
     failed init() call, it is not generically knowable whether it's
     okay to call init() again, and clients should not do so.

     Whether or not this step will initialize any network and/or FILE
     and/or RPC connections is left to the implementation. It may do
     so here, if needed, or it may delay such things until submit().
  */
  int (*init)(fsl_sc *ch, enum fsl_sc_init_e mode);

  /**
     this->append() must append the first n bytes of pIn to the
     outbound sync request payload. The library calls this an
     arbitrary number of times to generate a sync body payload.

     Implementations are free to buffer, or not, the payload,
     depending on their requirements, but practical considerations may
     make buffering unavoidable. e.g. an HTTP implementation will
     require the full payload before sending, so that the Content-Size
     header can be set and the headers pushed before the payload is. A
     streaming-to-(FILE*) implementation, however, has no such
     requirements, so could avoid an extra buffering step (unless,
     perhaps, that file's contents are intended for further processing
     by, e.g., netcat(1), in which case HTTP headers would need to be
     prepended).

     Achtung: calling this API directly from client code will
     effectively corrupt the output. The library internals funnel all
     fsl_sc output traffic through a single point so that the size of
     the request and its SHA1 hash can be kept track of (both are
     needed for sending authenticated requests). Calling this API
     directly will bypass that and result in request bodies whose
     hashes do not match fossil's authentication expectations.
  */
  int (*append)(fsl_sc *ch, void const * pIn, fsl_size_t n);

  /**
     this->submit() tells the channel that the library is done
     building the request payload and it should be submitted.

     If this method buffers its response, it may close (if still
     opened) any channel opened by init() but should retain any state
     which might be needed for reestablishing that connection. If it
     does not buffer the response, it may keep the channel open for
     downstream read() calls.

     This is never called before init() is passed FSL_SC_INIT_REQUEST
     and is never called after any call to init() fails.

     If loginCard is not NULL, it contains the full content of a login
     card for the request. A channel which uses
     FSL_SC_F_REQUEST_HEADERS must not add it to the request: the
     library has put it in requestHeaders already, in the Cookie
     header shown below. Any other channel must carry these bytes to
     the remote. An HTTP channel emits them as a header in this form:

     ```
     Cookie: x-f-l-c=UrlEncodedValueOfTheCard
     ```

     Which, in C, might look something like:

     ```
     char * z = fsl_mprintf("Cookie: x-f-l-c=%t\r\n",
                             cmpp_b_cstr(loginCard));
     ...
     fsl_free(z);
     ```

     A channel which uses FSL_SC_F_NO_HTTP and does not use
     FSL_SC_F_REQUEST_HEADERS carries the card in whatever way suits
     its transport, and its peer must present it to the remote as that
     header.

     (Sidebar: that approach to authentication only works with fossil
     versions newer than 2025-07-27, so the library cannot log in
     to older fossil versions but can otherwise speak to them.)

     Implementations must return 0 on success. On error,
     implementations must return a non-FSL_RC_OK value from the
     fsl_rc_e enum, and are strongly encouraged to set an error
     message using the fsl_xfer_error() family of functions, passing
     ch->xfer to it.
  */
  int (*submit)(fsl_sc *ch, fsl_b const *loginCard);

  /**
     this->read() must read, or consume from its buffer, the requested
     amount of data and append it to tgt.  It must only append to the
     target buffer, not reset or otherwise manipulate it, as the
     buffer may already contain state when this is called.

     If howMuch is greater than zero, it's a number of bytes which are
     expected to be appended to tgt. A non-0 result code must be
     returned if exactly that many bytes cannot be consumed.

     If howMuch is FSL_SC_READ_LINE then:

     1) One newline-separated (0x0A) line must be consumed from the
        input source and be append to tgt, including the newline
        character.  Aside from interpretation of that one character,
        implementations must treat the preceeding data (if any) as
        opaque. i.e. it must not be otherwise parsed and empty lines
        must not be skipped.

     2) If no newline is found, return FSL_RC_BREAK if at EOF and no
        data precedes the EOF, else some other non-0 error code
        (e.g. FSL_RC_IO). The library will interpret FSL_RC_BREAK as a
        non-error EOF condition.

     If howMuch is FSL_SC_READ_ALL then the library must read the
     whole response into the target buffer. (This is used by the
     library to handle fossil-compressed response bodies on behalf of
     fsl_sc implementations.) If the implementation internally stores
     the response in a fsl_b, it should use fsl_b_swap() to
     transfer it to tgt, rather than copy it.  If it uses a file,
     fsl_stream() can be used to transfer it, e.g.:

     ```
     fsl_stream(fsl_input_f_FILE, responseFile,
                fsl_output_f_b, tgt);
     // or:
     fsl_stream(fsl_input_f_fd, &myFileDescriptor,
                fsl_output_f_b, tgt);
     ```

     When howMuch is FSL_SC_READ_ALL, the library will not read any
     more from the channel until/unless ch->submit() is called again,
     so the implementation may free up any related resources at that
     point if it likes.

     The library will never pass a howMuch value of 0 to this
     function, but it reserves the option of eventually using 0 as a
     way of communicating that we are done reading, if such a
     capability ever becomes useful. For future compatibility's sake,
     it's legal to simply return 0 if howMuch is 0, but it's also
     legal to assert(howMuch!=0) until that happens.

     How the end of a reply body is determined. The library never
     tells read() the length of the body and does not stop reading
     once it has read that many bytes, so read() must end the body
     itself, in HTTP mode and in FSL_SC_F_NO_HTTP mode alike. The
     length the library knows is the Content-Length header in HTTP
     mode and fsl_sc::reply.length in FSL_SC_F_NO_HTTP mode. It is
     used afterwards, to check what was read:

     - If the reply is not compressed, the library reads cards with
       FSL_SC_READ_LINE and with sized reads, and the body ends
       where a FSL_SC_READ_LINE read returns FSL_RC_BREAK. So read()
       must return FSL_RC_BREAK right after the last byte of the
       body and must not return any byte which follows it, as that
       belongs to the next reply. When the body has ended, the library
       fails the transfer with "truncated" or "longer than its
       Content-Length" if it read another number of bytes than the
       length.

     - If the reply is compressed, the library calls read() once, with
       FSL_SC_READ_ALL, which must append the whole body and no more:
       the library fails the transfer if that is not the length. It
       then decompresses the body and serves the cards from memory
       without calling read() again before the next submit().

     Must return 0 on success, non-0 on error, and should use one of
     the fsl_xfer_error() family of functions to to provide any error
     message and propagate the error through the library.
  */
  int (*read)(fsl_sc *ch, fsl_b * tgt, fsl_int_t howMuch);

  /**
     Must free up all dynamically-allocated resources owned by ch and
     ch->impl.

     Finalizing must, if appropriate, free up any resources it uses,
     but must not free the object passed to it (which might be
     stack-allocated or part of a larger struct). If this connection
     is still open, it must close it.

     It is up to the implementation to set ch->impl.p to 0 if that's
     appropriate for them - the library does not do so. Some
     implementations may use static state and not need to reset
     ch->impl.

     In the wisdom of "destructors must not throw," the library
     provides no way to report a failure to close a channel (nor does
     it really care, at that point - by then the channel will have
     either already failed or served its purpose). If, after this
     call, ch->f has error state, the library has the option, at its
     developers' discretion, of emitting a warning to the client (this
     is unspecified and currently unimplemented, but warning and/or
     debug channels may be added at some point).

     The library will never pass NULL to this function.

     This method must never be called directly from client
     code. Instead, pass the object to fsl_sc_cleanup(), as that will
     free up the common fsl_sc members, leaving clean() impls to only
     concern themselves with their own private state.
  */
  void (*cleanup)(fsl_sc *ch);

  /**
     This is internal-use tooling to support adding "shim" layers of
     fsl_sc between the library and the "real" fsl_sc. The default
     impl (fsl_sc_self()) is suitable for all non-proxying channels
     and simply returns its argument. The impl for the tracer channel
     returns the object it's tracing. This distinction is relevant for
     handling of fsl_sc internals such as ch->url and ch->flags, in
     that (A) the internals always want those values to come from the
     "real" implementation, not the shim, and (B) they don't want code
     which is using a shim to have to know it's using a shim.  Calling
     ch->self(ch)->url will return the "correct" URL object.

     Implementation code of a fsl_sc, unless that channel is itself a
     proxy for another, should not use this - it's simply not needed
     there.  It's used by library code which wants to avoid having to
     know there's a shim/proxy channel in place. Implementors of proxy
     channels must provide a self() implementation which looks
     something like the following (taken from the tracer channel):

     ```
     // Custom channel state, set in fsl_sc::impl.p of channels
     // of this subtype.
     struct my_channel_state {
       fsl_sc * proxied; // proxied channel
       ... any other necessary state ...
     };
     typedef struct my_channel_state my_channel_state;

     fsl_sc * my_self(fsl_sc *ch){
       my_channel_state * const st = ch->impl.p;
       fsl_sc * const orig = st->proxied;
       return orig->self(orig); // call self() in case orig is a proxy!
     }
     ```
  */
  fsl_sc * (*self)(fsl_sc *ch);

  /**
     If this->flags contains FSL_SC_F_REQUEST_HEADERS, the library
     will populate this with raw HTTP headers for the request,
     including a trailing `\r\n` line, immediately before calling
     submit().  Implementations' submit() methods must, unless they do
     their own header generation, emit this before the body.  See
     FSL_SC_F_REQUEST_HEADERS.
  */
  fsl_b requestHeaders;
  /**
     A general-purpose scratchpad buffer for use by the channel object
     and the library internals.
  */
  fsl_b scratch;
  /**
     For channels with FSL_SC_F_NO_HTTP: what submit() must set to
     describe the reply, in place of the Content-Length and
     Content-Type headers. A length of 0 is an error.
  */
  struct {
    /** Size of the reply body in bytes. */
    fsl_size_t length;
    /** True if the body is fossil-compressed, as for FSL_SC_F_COMPRESSED. */
    bool compressed;
  } reply;
}/*fsl_sc*/;

/**
   An implementation for fsl_xfer::debug::callback which requires
   that the associated state be a (FILE*) handle opened for output.
   Each call sends zMsg to that FILE handle via fprintf(), without
   additional decoration.
*/
FSL_EXPORT void fsl_xfer_debug_f_FILE(fsl_xfer *xf, char const * zMsg);

/**
   An implementation for fsl_xfer::debug::callback which requires
   that the associated state be a (fsl_b*). On each call zMsg is
   appended as-is to that buffer, without additional decoration.
*/
FSL_EXPORT void fsl_xfer_debug_f_buffer(fsl_xfer *xf, char const * zMsg);

/**
   The default implementation of fsl_sc::self(). Simply returns
   ch.
*/
FSL_EXPORT fsl_sc * fsl_sc_self(fsl_sc *ch);

/** Empty-initialized fsl_sc instance, intended for const-copy
    initialization. */
#define fsl_sc_empty_m {        \
    .xfer=0, .name="unnamed",   \
    .url=fsl_url_empty_m,       \
    .flags = 0,                 \
    .impl = {.p = 0,.type = 0}, \
    .init=0, .append = 0,       \
    .submit=0,                  \
    .read=0, .cleanup=0,        \
    .self=fsl_sc_self,          \
    .requestHeaders = fsl_b_empty_m, \
    .scratch = fsl_b_empty_m     \
}

/** Empty-initialized fsl_sc instance, intended for copy
    initialization. */
extern const fsl_sc fsl_sc_empty;

/**
   Flags regarding which configuration options to sync.
*/
enum fsl_config_sync_e {
  FSL_CFG_SYNC_NONE         = 0,
  FSL_CFG_SYNC_CSS          = 1<<0, /* Style sheet only */
  FSL_CFG_SYNC_SKIN         = 1<<1, /* WWW interface appearance */
  FSL_CFG_SYNC_TKT          = 1<<2, /* Ticket configuration */
  FSL_CFG_SYNC_PROJ         = 1<<3, /* Project name */
  FSL_CFG_SYNC_SHUN         = 1<<4, /* Shun settings */
  FSL_CFG_SYNC_USER         = 1<<5, /* The USER table */
  FSL_CFG_SYNC_ADDR         = 1<<6, /* The CONCEALED table */
  FSL_CFG_SYNC_XFER         = 1<<7, /* Transfer configuration */
  FSL_CFG_SYNC_ALIAS        = 1<<8, /* URL Aliases */
  FSL_CFG_SYNC_SUBSCRIBER   = 1<<9, /* Email subscribers */
  FSL_CFG_SYNC_IWIKI        = 1<<10, /* Interwiki codes */
  FSL_CFG_SYNC_ALL          = 0x0000ffff, /* Everything */
  FSL_CFG_SYNC_OVERWRITE    = 0x10000000 /* Causes overwrite instead of merge */
};

typedef struct fsl_xfer_config fsl_xfer_config;

/**
   Synchronizes the repository currently opened by f with the peer
   selected by config. config->op.pull and config->op.push select the
   transfer direction. At least one must be true and config->op.clone
   must be false.

   This function requires an opened repository.

   Each protocol round runs in its own transaction, which is committed
   before the next request goes out, as fossil(1)'s client does. That
   keeps the repository's write lock free while waiting on the network,
   so other connections can write between rounds. If the caller has a
   transaction open, the rounds are savepoints nested in it, and
   nothing reaches the disk until the caller commits.

   If a reply holds an error card, or a card or body which cannot be
   handled, then processing of that reply stops there, what was
   received before that point is kept, and further rounds follow if
   the session still has work to do, as sections 5.2 and 10.1 of the
   sync draft require, though no further batches of local artifacts
   are pushed. The session then keeps everything it received and
   returns the first such error. A second such error ends the session
   at once, likewise keeping what was received and returning the
   first error. On any other error (e.g. out of memory, a db error, a
   project code mismatch, or received content which does not match its
   hash), the session ends at once: the current round is rolled back,
   and rounds which were already committed are kept. Like fossil(1), a
   later sync picks up where it stopped.

   On success, returns 0. On error it returns a non-0 fsl_rc_e value
   and propagates error information through err (if not NULL), or
   through f when err is NULL.
*/
FSL_EXPORT int fsl_sync_client(fsl_cx * f,
                               fsl_xfer_config const * config,
                               fsl_error * err);

#if 0
/**
   Resets ch's buffers for re-use and then calls ch->submit().

   This is prefered to calling ch->submit() directly because this
   ensures that ch's buffers are accounted for.
*/
FSL_EXPORT void fsl_sc_close(fsl_sc * const ch);
#endif

/**
   Calls fsl_sc_close() then, if ch->cleanup is not NULL, it is
   called. Then it frees all of ch's buffers. Does not free ch.

   This is prefered to calling ch->cleanup() directly because this
   ensures that ch's buffers are accounted for.
*/
FSL_EXPORT void fsl_sc_cleanup(fsl_sc * ch);

/**
   If xf has a debug channel installed, the given
   fsl_appendf()-compatible arguments are posted to it in string
   form. The output may be prefixed with other information.

   If xf has no debugging channel then this function has no
   side-effects.

   This function adds a newline to the result if it does not end in
   one.

   Returns 0 on success and the only error case is a formatting buffer
   allocation error, which causes FSL_RC_OOM to be returned. Such
   results should not be propagated by client code - an OOM is
   innocuous in the context of debugging output.

   This function requires allocating memory, and re-uses a buffer
   dedicated to that purpose. In ideal cases, it won't have to
   allocate more than once during the lifetime of a given fsl_xf
   instance.

   WARNING: fsl_xfer_config::debug-bound logging functions must not
   call this, else there will be an endless loop and eventual stack
   overflow.
*/
FSL_EXPORT int fsl_xfer_debugf(fsl_xfer * xf, char const * zFmt, ...);

/** va_list variant of fsl_xfer_debugf(). */
FSL_EXPORT int fsl_xfer_debugfv(fsl_xfer * xf, char const * zFmt, va_list args);

/**
   Equivalent to fsl_xfer_debugf(ch,"%s",zMsg) but is more efficient
   than that.
*/
FSL_EXPORT void fsl_xfer_debug(fsl_xfer * xf, char const * zMsg);

/**
   Returns xf's fsl_cx context. This is used in fsl_sc callback
   implementations.
*/
FSL_EXPORT fsl_cx * fsl_xfer_cx(fsl_xfer * xf);

/**
   Returns the most bytes xf's transfer accepts in one reply body,
   compressed or uncompressed: fsl_xfer_config::maxResponseBytes if it
   is positive, else 256 MiB. The library checks a reply against it
   when it knows its length. A channel which reads a reply of unknown
   length should stop and fail when the reply gets longer.

   xf may be NULL, as for a channel used outside of a transfer, and
   then the result is the default.

   fsl_sc::xfer is set before fsl_sc::init() is first called, so
   this may be used from there.
*/
FSL_EXPORT fsl_size_t fsl_xfer_max_response(fsl_xfer const * xf);

/**
   Returns the number of seconds a channel should let a read or write
   make no progress before failing the transfer:
   fsl_xfer_config::socketTimeoutSeconds if it is positive, else 120.
   The library does not enforce this itself: it is for channels which
   do their own I/O, as the native socket channel does.

   xf may be NULL, as for fsl_xfer_max_response(), and fsl_sc::xfer is
   set before fsl_sc::init() is first called.
*/
FSL_EXPORT int fsl_xfer_socket_timeout(fsl_xfer const * xf);

/**
   Sets xf's (persistent) error state to the given information
   and propagates it through to xf's fsl_cx. After this,
   further calls to fsl_xf-taking APIs will fail.

   This is intended to only be used from fsl_sc implementations
   and this library's own internals.

   This function prefixes the message with some form of ch->name and
   the fsl_rc_cstr() value of the given result code.

   The format is fsl_appendf()'s, not the C library's. In it %z is not
   a size modifier: it prints a (char *) like %s and then frees it, as
   in SQLite, so "%zu" with a size_t crashes. Print sizes with
   FSL_SIZE_T_PFMT, e.g. "%" FSL_SIZE_T_PFMT.

   Returns the given code, or FSL_RC_ERROR if code is 0. i.e.
   it never returns 0. A code value of 0 is semantically illegal in
   this context.
*/
FSL_EXPORT int fsl_xfer_errorf(fsl_xfer *xf, int code, char const * zFmt,
                               ...);

/** va_list variant of fsl_xfer_errorf(). */
FSL_EXPORT int fsl_xfer_errorfv(fsl_xfer *xf, int code, char const * zFmt,
                              va_list args);

/**
   Equivalent to fsl_xfer_errorf(ch,code,"%s",zMsg) unless code is
   FSL_RC_OOM, in which case zMsg is disregarded.
*/
FSL_EXPORT int fsl_xfer_error(fsl_xfer *xf, int code, char const * zMsg);

/**
   Policies for use with fsl_sc_popen indicating how to fetch the
   response from invoking an external command to transport fossil sync
   requests. This is all internal experimentation, not part of the
   public API.
*/
enum fsl_sc_popen_e {
  /**
     Directs the binary's stdout to a temp file bound to
     fsl_sc_popen_state::response::fp using fopen().

     This "should" work the same as fsl_sc_popen_e_direct but this one
     works where that one doesn't, for reasons unknown.

     Measurements show, somewhat surprisingly, this to be
     significantly faster than fsl_sc_popen_e_membuf (anywhere from
     30% to twice as fast, depending on the test run), as well as far
     memory-lighter: 410kb peak RAM vs 9.4MB peak ram for the same
     clone of fossil's canonical repository.
  */
  fsl_sc_popen_e_filebuf = 1,

  /**
     Don't use this except for experimentation.

     Slurp whole response into a fsl_b at
     fsl_sc_popen_state::response. This works but can use a huge
     amount of memory.

     This is slower than fsl_sc_popen_e_filebuf and much more
     memory-hungry.  The main speed culprit seems to be
     fsl_b_stream_lines(), which takes up some 25% of the test
     run's CPU instructions (as reported by callgrind).
  */
  fsl_sc_popen_e_membuf = 2,

  /**
     Does not work!

     Don't buffer: read response from the binary's stdout, bound to
     fsl_sc_popen_state::process::fdStdOut.

     This mode is currently failing with curious read failures: for
     _some_ cards, reading the payload leaves (apparently) pieces
     which are then read by the next read-line op and of course don't
     parse as a card. The cause is as-yet unknown but it's got to be a
     bug somewhere in this code.
  */
  fsl_sc_popen_e_direct = 3,

  /**
     Does not work!

     Read the binary's stdout using an unbuffered file descriptor
     open()ed on fsl_sc_popen_state::response::fd.

     This is is known to fail with "not found" for the output file
     after fsl_popen2()'ing the command (at which point we expect the
     output to be there). This "should" fail in the same way as
     fsl_sc_popen_e_direct, as we're doing the same thing just with
     another file of indirection.
  */
  fsl_sc_popen_e_fd = 4,

  /**
     Mode used by fsl_sc_popen_state_empty.
  */
  fsl_sc_popen_e_default = fsl_sc_popen_e_filebuf
};

typedef struct fsl_sc_popen_state fsl_sc_popen_state;

/**
   State for use with the fsl_sc_popen fsl_sc impl. fsl_sc_popen
   requires that its state member point to an instance of this class.

   This type acts as a base implemtation for channels which
   "shell out" to an external binary to provide the transport
   layer. e.g. curl can be used for HTTP(S) and fossil(1)'s own
   "test-http" mechanism can be used this way.
*/
struct fsl_sc_popen_state {
  /**
     State for "subclasses". Not really subclasses, but "concrete
     implementations" gets unwieldy after a while.
  */
  struct {
    /**
       This optional method gets called as part of the
       FSL_SC_INIT_INITIAL phase of fsl_sc::init() to give subclasses
       a way to perform any validation they may need. It may also
       perform any one-time initialization it may need to do.

       If it returns non-0, channel initialization fails.
    */
    int (*init)(fsl_sc *ch);

    /**
       Command arguments initializer. Must be set by concrete
       implementations and it gets invoked via
       fsl_sc::submit(). Implementations must populate b using
       ((fsl_sc_popen_state*)ch->impl.p)'s state, namely the
       request.filename and response.filename members, which are names
       of temporary files which will eventually contain the request
       payload and response payloads.

       Implementations must use fsl_b_escape_arg() and friends to
       append a complete command line to b. They must return 0 on
       success.

       When this is called (early on in the fsl_sc::submit() process):

       - this->bin.location will be set to the command to invoke. It
         must be prepended to the command line (or may it may be
         proxied via a separate command known only to the concrete
         implementation).

       - this->url will be set to the remote fossil URL.

       - this->request.filename is a file which the
         command is expected to read the fossil sync request body
         payload from.

       - If this->response.filename is not NULL then it is a file
         which the command is expected to write the fossil sync
         response to, minus any transport-layer metadata like HTTP
         headers. If it is NULL, the process is expected to write to
         stdout.

       - None of the other this->request and this->response members
         will be set up.

       - If bLoginCard is not NULL then it will hold the content for a
         fossil sync login card. Implementations must emit an HTTP
         header in the form "Cookie: x-f-x-l=XYZ" where XYZ is the
         URL-encoded content of bLoginCard.  For fsl_sc impls which
         use the FSL_SC_F_REQUEST_HEADERS flag, the library will have
         populated ch->requestHeaders before this is called, including
         the login card.
    */
    int (*buildCommandLine)(fsl_sc * ch, fsl_b * b,
                            fsl_b const * bLoginCard);

    /**
       May be set for subclasses in order to clean up any dynamic
       state owned by this object in this->impl.state. It will be
       called early in the fsl_sc::cleanup() step, before st's base
       class state are cleaned.

       Whether or not it must free st is implementation-defined.
    */
    void (*cleanup)( fsl_sc_popen_state * st );

    /**
       Subclass-specific state. Owned by this object's cleanup()
       method.
    */
    void * state;
  } impl;

  /** Info about the binary. */
  struct {
    /**
       The name of the program binary, e.g. "curl". It is expected to
       be findable via the $PATH.
    */
    char const * name;
    /**
       Location where the binary was found. If NULL, it defaults to a
       $PATH search of this->bin.name. Clients may set this before
       use, but (A) it must be allocated using a libfossil API,
       e.g. fsl_mprintf(), and (B) this memory is owned by this
       object.

       If the client does not set this, the library will search in the
       $PATH for this->name and assign that value here.
    */
    char * location;
  } bin;
  /** State for/around fsl__popen2(). */
  struct {
    /** The external process's stdin, i.e. a write-only stream. */
    FILE *fStdIn;
    /** The external process's stdout, i.e. a read-only stream. */
    int fdStdOut;
    /** The external process's PID. */
    int pid;
  } process;

  /**
     State for the sync request payload.
  */
  struct {
    /** Filename of this->fp. */
    char *filename;
    /** Request payload temp file. */
    FILE *fp;
    /** Number of initiated requests. */
    unsigned count;
  } request;

  /**
     State for the sync response payload.
  */
  struct {
    /**
       How to read the response. This should never be set by clients.
       It's for library-internal experimentation. If it must be set as
       part of a struct initialization, set it to
       fsl_sc_popen_e_default.
    */
    enum fsl_sc_popen_e mode;
    /**
       Response temp file when this->response.mode is
       fsl_sc_popen_e_filebuf or fsl_sc_popen_e_fd.
    */
    char *filename;
    /**
       Response source file when this->mode is fsl_sc_popen_e_filebuf.
       This file is opened in "w+b" mode.
    */
    FILE * fp;
    /**
       Response input source when this->mode is fsl_sc_popen_e_fd.
    */
    int fd;
    /** Number of initiated response-reads. */
    unsigned count;
    /**
       Response body when this->mode is fsl_sc_popen_e_membuf.
    */
    fsl_b b;
  } response;

  /**
     Flag(s).
  */
  struct {
    /**
       Internal implementation detail. Tells fsl_sc_popen's
       cleanup() impl whether or not to free() this object.
    */
    void * allocStamp;

    /**
       A random prefix for temp file names. Memory is owned by this
       object. All request and response temp files are prefixed with
       this and get a predictable suffix. We generate a random prefix,
       rather than a new random name on each call, to simplify
       grouping of the files for development and debugging purposes.
    */
    char * tmpfilePrefix;
  } misc;

  /**
     The command line to invoke. This is intended to be set up by
     this->impl.buildCommandLine.
  */
  fsl_b cmd;
};

/**
   Initializer for a fsl_sc_popen_state object which sets
   obj.bin.name=BinName, obj.impl.buildCommandLine=XCmdInit, and
   obj.impl.cleanup=XCleanup.

   The object is intended only for use as the fsl_sc::state pointer of
   a copy of fsl_sc_popen.
*/
#define fsl_sc_popen_state_init(BinName,xInit,XCmdInit,XCleanup) {  \
  .impl = {                                                  \
    .init=xInit,                                             \
    .buildCommandLine=XCmdInit,                              \
    .cleanup=XCleanup, .state = 0                            \
  },                                                         \
  .bin = { .name = BinName, .location = 0 },                 \
  .process = {                                               \
    .fStdIn = 0, .fdStdOut = -1, .pid = 0                    \
  },                                                         \
  .request = {                                               \
    .filename = 0, .fp = 0, .count=0                         \
  },                                                         \
  .response = {                                              \
    .mode = fsl_sc_popen_e_default,                          \
    .filename = 0, .fp = 0, .fd = -1,                        \
    .count=0, .b = fsl_b_empty_m                        \
  },                                                         \
  .misc = {                                                  \
    .allocStamp = 0,                                         \
    .tmpfilePrefix = 0                                       \
  },                                                         \
  .cmd = fsl_b_empty_m                                  \
}

//#define fsl_sc_popen_state_empty_m fsl_sc_popen_state_init("unnamed",0,0)

/**
   An empty base fsl_sc_popen_state instance intended to be
   copied to intialize fsl_sc_popen_state implementations.
   Implementations must set the bin.name and
   impl.buildCommandLine members to whatever is appropriate for the
   object's external binary.
*/
extern const fsl_sc_popen_state fsl_sc_popen_state_empty;

/**
   An empty base fsl_sc instance for use with fsl_sc_popen_state
   implementations.

   To use it:

   1. Bitwise-copy it over a fsl_sc instance.

   2. Set its state.p member to point to a valid fsl_sc_popen_state
      instance.

   3. Do not modify its state.type member.

   Nuances of this implementation:

   - Its state.p _must_ be a (fsl_sc_popen_state*) and state.type must
     be &fsl_sc_popen. This initializer does that latter part.

   - If state->flag.allocStamp is not 0, it must point to state->p.
     This indicates that this object owns its state pointer and will
     free it via this object's cleanup() method.
*/
extern const fsl_sc fsl_sc_popen;

/**
   An empty state object of the type expected by fsl_sc_popen,
   configured to use the system's "curl" binary as the fossil sync
   communication channel.

   This class is not needed if libfossil is built with libssl, in
   which case it can talk HTTP(s) via that.
*/
extern const fsl_sc_popen_state fsl_sc_popen_state_curl;

/**
   Like fsl_sc_popen but may include different fsl_sc::flags defaults.
   The state.p member _must_ point to a fsl_sc_popen_state instance
   initialized by bitwise copying from fsl_sc_popen_state_curl.

   Example usage:

   ```
   fsl_sc_popen_state pst = fsl_sc_popen_state_curl;
   fsl_sc st = fsl_sc_popen_curl;
   st.state.p = &pst;
   ```
*/
extern const fsl_sc fsl_sc_popen_curl;

/**
   Works like fsl_sc_popen_curl but uses "fossil test-http" for the
   transport layer. The fsl_sc::state::p pointer of these objects MUST be a
   pointer to an fsl_sc_popen_state object which was initialized by
   copying it from fsl_sc_popen_state_fth. Example:

   ```
   fsl_sc sc = fsl_sc_popen_fth;
   fsl_sc_popen_state st = fsl_sc_popen_state_fth;
   sc.state.p = &sc;
   ```
*/
extern const fsl_sc fsl_sc_popen_fth;
/**
   State type for use with fsl_sc_popen_fth.
*/
extern const fsl_sc_popen_state fsl_sc_popen_state_fth;

/**
   Works like fsl_sc_popen_curl but uses "ssh ... fossil test-http" for the
   transport layer. The fsl_sc::state::p pointer of these objects MUST be a
   pointer to an fsl_sc_popen_state object which was initialized by
   copying it from fsl_sc_popen_state_ssh. Example:

   ```
   fsl_sc sc = fsl_sc_popen_ssh;
   fsl_sc_popen_state st = fsl_sc_popen_state_ssh;
   sc.state.p = &sc;
   ```

   By default it assumes that fossil(1) is in the remote's $PATH, but
   it can be explicitly told the path by providing a query argument to
   the URL: fossil=/path/to/remote/fossil (URL-encoded if it contains
   anything which needs to be).

   Peculiarities of this implementation:

   - The user in the URL is the ssh login, and ssh does the
     authentication. We copy fossil(1): no fossil login card is sent,
     and any password supplied in the URL is ignored.
*/
extern const fsl_sc fsl_sc_popen_ssh;

/**
   State type for use with fsl_sc_popen_ssh.
*/
extern const fsl_sc_popen_state fsl_sc_popen_state_ssh;

/**
   A native socket-based sync channel for http:// and https:// URLs. It
   is a drop-in peer of fsl_sc_popen_curl which removes the dependency
   on an external curl binary by speaking HTTP over a TCP socket
   directly (and, when built with FSL_NATIVE_TLS_OPENSSL, TLS for
   https://). It uses the library-generated HTTP headers
   (FSL_SC_F_REQUEST_HEADERS), as the "fossil test-http" channel does.

   A client copy-initializes an fsl_sc from this value, calls
   fsl_sc_socket_state_init() on it to allocate per-channel private
   state, then hands it to the sync machinery, e.g.:

   ```
   fsl_sc ch = fsl_sc_socket;
   fsl_url_parse(&ch.url, zUrl);
   fsl_sc_socket_state_init(&ch);
   ```

   See doc/sync-native-channel.md.
*/
extern const fsl_sc fsl_sc_socket;

/**
   Allocates and installs the private state for an fsl_sc_socket
   instance. Call after copy-initializing an fsl_sc from fsl_sc_socket
   and before its init(). Returns 0 on success, FSL_RC_OOM on
   allocation failure. The state is freed by the channel's cleanup().
*/
FSL_EXPORT int fsl_sc_socket_state_init(fsl_sc *ch);

/**
   What read() returns when no byte arrived within
   fsl_xfer_socket_timeout() seconds. See fsl_sc_stream_ops.
*/
#define FSL_SC_STREAM_TIMEOUT ((fsl_int_t)-2)

/**
   What read() returns at the end of a stream which was not closed
   cleanly, as when a TLS peer closes the connection without a
   close_notify alert. See fsl_sc_stream_ops.
*/
#define FSL_SC_STREAM_UNCLEAN ((fsl_int_t)-3)

/**
   The callbacks of a stream channel, which gives a caller who has
   only a byte stream (a TCP or TLS connection, a Unix socket, a
   tunnel) the library's HTTP handling, so that the caller writes none
   of it: the request line and headers, the HTTP/1.1 upgrade with
   "Connection: close", replies with a Content-Length, close-delimited
   replies, chunked replies, the reply size limit and the timeout.
   The library's own http: and https: channel is this same channel
   with sockets and OpenSSL as its callbacks.

   The channel makes one request per connection. For each round
   trip it calls connect(), then write() until the request is sent,
   then read() until it returns 0 and then close(). It also calls
   close() when the transfer ends with the connection open, as after
   a failed write(). The calls all come from the thread which runs the
   transfer.

   Every callback which can fail receives the transfer, xf, to report
   the failure to. A failing callback sets the error state with
   fsl_xfer_errorf() or one of its siblings, naming what failed, and
   returns as described below. The channel then fails the transfer
   with that error, as for the methods of fsl_sc. If a callback fails
   without setting one, the channel sets a message which names the
   channel and the callback.

   The callbacks must make progress or fail: the library cannot
   interrupt a blocked callback.
*/
struct fsl_sc_stream_ops {
  /**
     Opens the connection to the host in url: url->host, url->port
     (0 if the URL has none), url->scheme and url->path. The library
     does not interpret the scheme, so a caller may use any. If it
     does TLS, it also does all of its certificate handling. Returns
     0 on success. The callback should not let a later read() or
     write() wait longer than fsl_xfer_socket_timeout(xf) seconds
     for progress.
  */
  int (*connect)(void * state, fsl_url const * url, fsl_xfer * xf);

  /**
     Reads up to n bytes into dest and returns how many it read. It
     returns at least one byte, waiting for it if need be, unless the
     stream has ended, when it returns 0 if the peer closed the
     connection cleanly, with a TCP FIN or a TLS close_notify, and
     FSL_SC_STREAM_UNCLEAN if it did not, as a TLS peer which just
     closes the connection. Both end the reply, and the library
     checks it against its Content-Length. A reply which has neither a
     Content-Length nor chunks ends where the connection does, and is
     accepted only after a clean close, as it could otherwise be cut
     short. If no byte arrives within
     fsl_xfer_socket_timeout(xf) seconds it returns
     FSL_SC_STREAM_TIMEOUT. The library treats that as the end of the
     reply if the peer had already sent some of it, and otherwise
     fails with "No response from HOST within N seconds". Any other
     negative result is a failure.
  */
  fsl_int_t (*read)(void * state, void * dest, fsl_size_t n,
                    fsl_xfer * xf);

  /**
     Writes up to n bytes from src and returns how many it wrote,
     which is at least one, or a value less than 1 on failure.
     The library calls it again for the rest.
  */
  fsl_int_t (*write)(void * state, void const * src, fsl_size_t n,
                     fsl_xfer * xf);

  /**
     Closes the connection and releases whatever connect() acquired.
     It is optional.
  */
  void (*close)(void * state);

  /**
     The first argument of all of the callbacks. It is the caller's.
  */
  void * state;
};
typedef struct fsl_sc_stream_ops fsl_sc_stream_ops;

/**
   Initializes ch as a stream channel which calls ops, ready to be
   assigned to fsl_xfer_config::channel. ops must have its connect(),
   read() and write() set, and it and what its state points to must
   outlive every transfer which uses ch, because ch points to ops
   until a transfer starts and copies it. Each transfer takes its own
   copy of ch, which allocates and frees the buffers it needs, so
   nothing has to be cleaned up afterwards and ch may serve any number
   of transfers one after another.

   The URL of the transfer is parsed into the channel's copy and
   passed to ops->connect(). Its scheme, such as https, has no
   meaning to the channel.

   ch->name is "stream", which prefixes the channel's error
   messages. A caller may change it after this returns.

   Returns 0 on success and FSL_RC_MISUSE if ch or ops is NULL or ops
   lacks a required callback.
*/
FSL_EXPORT int fsl_sc_stream_init(fsl_sc * ch, fsl_sc_stream_ops const * ops);

/**
   Expands to a mapping of all fsl_sc_tracer_e types by invoking
   E(NAME,VALUE) for each one. NAME is the suffix part of the name,
   e.g. init instead of FSL_SC_TRACER_init. VALUE is its integer
   value.
*/
#define fsl_sc_tracer_map(E)              \
  E(none,0)                               \
  E(init,1) E(read, 1<<1) E(append, 1<<2) \
  E(cleanup, 1<<3) E(submit, 1<<4) E(self, 1<<5) \
  E(debug, 1<<6)

/**
   Flags for use with fsl_sc_tracer_init().
*/
enum fsl_sc_tracer_e {
#define E(NAME,FLAG) FSL_SC_TRACER_ ## NAME = FLAG,
  fsl_sc_tracer_map(E)
#undef E

  FSL_SC_TRACER_all = 0
#define E(NAME,FLAG) | FSL_SC_TRACER_ ## NAME
  fsl_sc_tracer_map(E),
#undef E

  FSL_SC_TRACER_default = FSL_SC_TRACER_init
  | FSL_SC_TRACER_cleanup
  | FSL_SC_TRACER_submit
  | FSL_SC_TRACER_self
};

/**
   An fsl_sc implementation which proxies another, which must be
   set as its state member.

   This proxy calls fsl_sc_debug() with the name of each called fsl_sc
   method before passing the method on to the proxied changed.

   The exception is: the fsl_sc::debug.callback method is passed that
   through directly because calling fsl_sc_debug() on itself leads to
   an endless loop.

   The out argument is where debug output should be written
   to. Neither out nor out->out may be NULL.

   Example:

   ```
   fsl_outputer out = ...;
   fsl_sc orig = ...another sc...;
   fsl_sc tracer = fsl_sc_tracer_empty;
   fsl_sc * const sc = fsl_sc_tracer_init(
       &tracer, &orig, FSL_SC_TRACER_all, &out
   );
   assert( !sc || sc==&tracer );
   ```

   Then use tracer in place of orig with the downstream APIs.  Calling
   tracer.cleanup(&tracer) will also cleanup orig.
*/
extern const fsl_sc fsl_sc_tracer_empty;

/**
   Initializes chTrace as a copy of fsl_sc_tracer_empty then directs
   chTrace's state to point to ch. Returns chTrace on success.  On
   error it returns NULL.
*/
FSL_EXPORT fsl_sc * fsl_sc_tracer_init(fsl_sc *chTrace, fsl_sc *ch,
                                       fsl_flag32_t traceFlags,
                                       fsl_outputer * out);

/** @internal

   Pass the name of a macro which takes 2 arguments to this
   macro. Macro E will be called with (NAME,LENGTH) of each sync card
   type. NAME is the unquoted name. LENGTH is strlen(#NAME) (which we
   need in a compile-time form).

   !!! Keep these sorted by name and edit code which uses these to
   !!! match. Internals require them to be sorted by name. Actually...
   !!! maybe not anymore.
*/
#define fsl_xfcard_map(E) \
  /* KEEP */   E(cfile,5) E(clone,5) E(clone_seqno,11) E(config,6)   \
  /* THESE */  E(cookie,6) E(error,5) E(file,4) E(gimme,5) E(igot,4) \
  /* SORTED */ E(login,5) E(uvfile,6) E(message,7) E(pragma,6)       \
  /* BY */     E(private,7) E(pull,4) E(push,4) E(reqconfig,9)       \
  /* NAME */   E(uvgimme,7) E(uvigot,6)

/** @internal

   Ids for fossil sync protocol card types.

   This is only exposed in the public API for use with
   fsl_xfer_metrics. It is otherwise an internal type.
*/
enum fsl_xfcard_e {
  /* MUST BE FIRST. Reminder to self: this has to be outside of
     fsl_xfcard_map() because of how fsl__xfcard_search() is set up. */
  fsl_xfcard_e_unknown,

#define E(T,LEN) fsl_xfcard_e_ ## T,
  fsl_xfcard_map(E)
#undef E

  /* Sentinel entry */
  fsl_xfcard_e_COUNT
};
typedef enum fsl_xfcard_e fsl_xfcard_e;
/**
   A comma-separated list of zeroes: one for each entry in
   fsl_xfcard_e.
*/
#define fsl_xfcard_zeroes \
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

/**
   Metrics for use with the library's "xfer" (sync) subsystem.
*/
struct fsl_xfer_metrics {
  /** Number of connections made to the remote. */
  fsl_size_t trips;
  /** Number of "igot" cards sent */
  fsl_size_t iGotSent;
  /** Number of private "igot" cards */
  fsl_size_t privIGot;
  /** Number of gimme cards sent */
  fsl_size_t gimmeSent;
  /** Number of files sent */
  fsl_size_t fileSent;
  /** Number of deltas sent */
  fsl_size_t deltaSent;
  /** Number of files received */
  fsl_size_t fileRcvd;
  /** Number of deltas received */
  fsl_size_t deltaRcvd;
  /** Number of dangling deltas received */
  fsl_size_t danglingFile;
  /** Total received artifacts */
  fsl_size_t rcvdArtifacts;
  /** Largest card payload size */
  fsl_size_t largestCardPayload;
  /**
     Buffer capacity allocated for the latest single
     fossil-compressed response.
  */
  fsl_size_t largestDecompressedResponse;
  /**
     Number of compressed response bytes via fsl__xfer_submit().
     This counts only compressed response bodies, not the compressed
     content of cfile cards.
  */
  fsl_size_t bytesReadCompressed;
  /** Number of uncompressed response bytes via fsl__xfer_read() and
      fsl_xfer_readln(). */
  fsl_size_t bytesReadUncompressed;
  /**
     Number of response body bytes as received from the peer,
     before any decompression.
  */
  fsl_size_t bytesReadWire;
  /** Number of bytes via fsl__xfer_append() and friends. */
  fsl_size_t bytesWritten;
  /** Counts of each card type seen in the response(s). */
  fsl_size_t cardsRx[fsl_xfcard_e_COUNT];
  /**
     Counts of each card type sent in request(s).

     TODO: replace most of the card-specific members with this.  We
     first need to change how fsl__xfer_appendln() works.
  */
  fsl_size_t cardsTx[fsl_xfcard_e_COUNT];

  /** Various timing metrics. */
  struct {
    /** Time spent waiting on fsl_sc::read(), but only via
        fsl__xfer_read(), fsl__xfer_readln(), and (when reading
        compressed responses) fsl__xfer_submit(). */
    fsl_timer read;
    /** Time spent waiting on fsl_sc::submit(). */
    fsl_timer submit;
    /**
       Time taken to decompress cfile card payloads.
    */
    fsl_timer uncompress;
    /**
       Time taken to decompress cfile card payloads.
    */
    fsl_timer process;
  } timer;
};

typedef struct fsl_xfer_metrics fsl_xfer_metrics;

/**
   Payload type for FSL_MSG_XFER messages, sent after each round trip
   of a sync or clone and once more when it completes.
*/
struct fsl_msg_xfer {
  /** The running metrics. */
  fsl_xfer_metrics const * metrics;
  /** Number of completed round trips. */
  fsl_size_t trips;
  /** NULL until the final message, then "Pull", "Push", "Sync" or
      "Clone" (fossil(1)'s labels). */
  char const * zDone;
  /** The remote's host name, or NULL if it has none (e.g. file:). */
  char const * zRemote;
};
typedef struct fsl_msg_xfer fsl_msg_xfer;

/**
   Empty-initialized fsl_xfer_metrics instance intended for
   const-copy initialization.
*/
#define fsl_xfer_metrics_empty_m { \
    .trips = 0, \
    .iGotSent = 0, \
    .privIGot = 0, \
    .gimmeSent = 0, \
    .fileSent = 0, \
    .deltaSent = 0, \
    .fileRcvd = 0, \
    .deltaRcvd = 0, \
    .danglingFile = 0, \
    .rcvdArtifacts = 0, \
    .largestCardPayload = 0, \
    .largestDecompressedResponse = 0, \
    .bytesReadCompressed = 0, \
    .bytesReadUncompressed = 0, \
    .bytesReadWire = 0, \
    .bytesWritten = 0, \
    .cardsRx = {fsl_xfcard_zeroes},  \
    .cardsTx = {fsl_xfcard_zeroes},  \
    .timer = {                       \
      .read = fsl_timer_empty_m, \
      .submit = fsl_timer_empty_m, \
      .uncompress = fsl_timer_empty_m,    \
      .process = fsl_timer_empty_m \
    } \
  }

/**
   Empty-initialized fsl_xfer_metrics instance intended for
   non-const copy initialization.
*/
extern const fsl_xfer_metrics fsl_xfer_metrics_empty;

/**
   A callback for use with the libfossil sync transfer subsystem.
   Implementations are passed the sync-related metrics, their state
   object, and the result code of the sync (so that they can choose
   whether or not to skip any display on error).
*/
typedef void (*fsl_xfer_metrics_f)(fsl_xfer_metrics const *, void*,
                                   int theRc);

/**
   A fsl_xfer_metrics_f implementation which requires that its second
   argument be a (fsl_xfer_metrics*). It copies the first argument
   bitwise over the second. The final argument is ignored.
*/
void fsl_xfer_metrics_f_dup(fsl_xfer_metrics const *, void*, int theRc);

/**
   A fsl_xfer_metrics_f implementation which requires its second
   argument to be a (fsl_outputer*). It sends all output to that
   channel. If theRc is non-0 then this is a no-op.
*/
void fsl_xfer_metrics_f_outputer(fsl_xfer_metrics const * m,
                                 void *state, int theRc);

/**
   This typedef describes a callback used by the library for fetching
   passwords when needed for remote synchronization.

   Its first two arguments are current fsl_cx and the URL the password
   is being requested for. The final argument is
   implementation-dependent state.

   Implementations must somehow collect a password for the given URL,
   append a copy of it to bOut, and return 0 on success. On error
   they must return non-0, preferably the result of passing f to
   fsl_cx_err_set(). If appending the result to the buffer fails, it's
   caused (barring invalid arguments) by an OOM, in which case that
   code can be returned directly.

   It is legal for implementations to use bOut for construct their
   input prompt, so long as they pass it to fsl_b_reuse() before
   appending the password to it.

   To indicate a non-error when no password is available, return 0 and
   do not modify bOut (or pass it to fsl_b_reuse() before
   returning). In such cases the library will continue as if no
   credentials are available, which might trigger an error later on if
   credentials are required.

   bOut is owned by the library. The state argument is owned by
   whoever put it there.

   Design notes:

   Sync passwords are stored, if at all, in f's global config
   database.  Each has a key of "libfossil-sync-pw:" + the URL shorn
   of any password part. Thus saving a password for
   "http://foo:bar@baz/bar" will leave a config entry named
   "libfossil-sync-pw:http://foo@baz/bar". The passwords are stored as
   conventionally-fossil-hashed passwords.

   Passwords are specific to a given repository "project-code", so
   attempting to sync to the same URL for multiple project codes will
   leave the sync unable to log in to any but the most recent one for
   which the password was saved.

   This password storage is different from fossil(1)'s. The thinking
   is "separate apps, separate passwords", though the passwords all go
   in the same database. That's subject to change, though.
*/
typedef int (*fsl_pw_f)(fsl_cx * f, char const * zUrl,
                        fsl_b * bOut, void * state);

#if 0
/**
   A fsl_pw_f() implementation which uses unistd.h's
   obsolete/deprecated getpass(2). This implementation exists
   primarily for testing.

   Warning: getpass(2) uses static state, so this function must not be
   used if multiple threads might need to use getpass(2).

   This function works only for terminal applications, not GUI apps or
   those which cannot read from stdin.

   This implementation ignores the final argument.


   TODO: implement a getpass()-free alternative like the one
   demonstrated at:

   https://www.gnu.org/software/libc/manual/html_node/getpass.html

   Ah, fossil(1) has one in its user.c as well.
*/
int fsl_pw_f_getpass(fsl_cx * f, char const * zUrl,
                     fsl_b * bOut, void * state);
#endif

/**
   Various configuration pieces for libfossil sync transfer subsystem.

   Instances of this class are invariably stack-allocated but may own
   memory and must be cleaned up using fsl_xfer_config_cleanup().

   As of 2026-11-03: do not bitwise-copy these!
*/
struct fsl_xfer_config {
  /**
     The URL or filename to sync with. If this is empty then the
     library will try to determine it from the currently-opened
     repository. Its memory is owned by this object.
  */
  fsl_b url;

  /**
     Reserved for a response time limit. fsl_sync_client() returns
     FSL_RC_NYI if this is set to a non-negative value.
  */
  int8_t maxResponseSeconds;

  /**
     For fsl_sync_client() and fsl_clone(), the hard maximum
     compressed and uncompressed response size, in bytes. Values less
     than 1 mean 256 MiB. A fossil(1) server stops adding artifacts to
     a reply once the reply reaches its max-download setting (default
     5000000 bytes), so a reply can be max-download + 1 artifact.
     Replies from a fossil(1) server should be smaller than FSL_BLOB_MAX_SIZE.

     The native socket channel and the popen channels stop reading a
     reply once the reply is longer than:

        maxResponseBytes + (the formula in src/sc.c:fsl__sc_reply_max)

     It is also the approximate maximum outbound request payload size,
     which may also be exceeded by one artifact. Values less than 1 apply a
     built-in default to the outbound payload size.

     A channel supplied through channel reads the effective value with
     fsl_xfer_max_response().
  */
  int32_t maxResponseBytes;

  /**
     Seconds the HTTP socket channel waits for each read of a reply (or
     write of a request) to make progress before failing the
     transfer. Values less than 1 mean the default of 120. A channel
     supplied through channel reads the effective value with
     fsl_xfer_socket_timeout() and must apply it itself.
  */
  int32_t socketTimeoutSeconds;

  /**
     Verbosity level (higher is more verbose).
  */
  short verbosity;

  /**
     A hint for fsl_sc channels which support it. See
     FSL_SC_F_LEAVE_TEMP_FILES.
  */
  bool leaveTempFiles;

  /**
     If true, request zlib-compressed responses using the
     application/x-fossil Content-Type. Otherwise use
     application/x-fossil-uncompressed. This is a hint to the server,
     which may respond as it likes.
  */
  bool compressTraffic;

  /**
     If true, set FSL_SC_F_TLS_ACCEPT_ANY_CERT on the channel, so that
     an https connection accepts any server certificate.
  */
  bool acceptAnyCert;

  /**
     TODO (2026-08-30): add dryRun flag now that we can sync in a
     transaction.  That was historically not possible because we
     shelled out to fossil(1) and our transaction locked the db.
  */

  /**
     Receives messages emitted by this transfer. If its callback is
     NULL, fsl_sync_client() inherits the listener configured on its
     fsl_cx.
  */
  fsl_msg_listener listener;

  /** Optional debug message callback. */
  fsl_xfer_dbg debug;

  /**
     fsl_sc API tracing hook.
  */
  struct {
    /**
       If non-zero, a tracing channel is installed with the given mask
       of fsl_sc_tracer_e flags. If it is zero, no tracer is
       installed.
    */
    fsl_flag32_t mask;
    /**
       The tracing output sink.
    */
    fsl_outputer outputer;
  } trace;

  /**
     Members which are set to true will activate specific aspects of
     sync.
  */
  struct {
    /* Clone with protocol version 1, 2, or 3. 0 = do not clone. */
    short clone;
    /* Push content. */
    bool push;
    /* Pull content. */
    bool pull;
    /* Transfer private content, subject to peer authorization. */
    bool privateContent;
    /* Reserved. fsl_sync_client() returns FSL_RC_NYI when true. */
    bool autosync;
    /* Request all igot cards from the server. */
    bool verily;
  } op;

  struct {
    /**
       If not NULL, fsl_xfer's cleanup routine will call this,
       passing it the metrics, this->state, and the final result code
       of the sync process.
    */
    fsl_xfer_metrics_f callback;
    /**
       Optional state for the 2nd argument to this->callback(). It is
       owned by whoever assigns it to non-NULL.
    */
    void * state;
  } metrics;

  struct {
    /**
       Callback to use to fetch passwords.
    */
    fsl_pw_f callback;
    /**
       State for the password callback. It must match that
       implementation's expectations. It is owned by whoever set this
       property.
    */
    void * state;
    /**
       If true:

       - If the URL contains a password, then on successful sync
         the hashed password is saved for future use with that same
         URL (excluding the password part).

       This does not govern whether a saved password is used: see
       ignoreSaved.
    */
    bool save;
    /**
       If true and the URL has no password, saved passwords are not
       looked up: the password comes from this->callback, which may
       then be saved as governed by this->save. Without a callback,
       a sync which needs a password fails.
    */
    bool ignoreSaved;
  } password;

  /**
     If not NULL, a copy of this channel is used for the transfer,
     instead of one chosen from the URL scheme. The caller initializes
     it from fsl_sc_empty and sets its methods, flags and impl state
     (see fsl_sc for what it must provide; the library refuses a
     channel which lacks a required member). The library sets the
     copy's xfer member and parses the URL, which is still required,
     into the copy's url, so that the channel can read its host and
     path. The caller keeps ownership of what impl.p points to, which
     must outlive the transfer, and of the original, which the library
     does not clean up.
  */
  fsl_sc const * channel;
};


/**
   Empty-initialized fsl_xfer_config instance intended for const-copy
   initialization.
*/
#define fsl_xfer_config_empty_m {    \
  .url = fsl_b_empty_m,              \
  .maxResponseSeconds = -1,          \
  .maxResponseBytes = 0,             \
  .socketTimeoutSeconds = 0,         \
  .verbosity = 0,                    \
  .compressTraffic=true,             \
  .acceptAnyCert=false,              \
  .listener = fsl_msg_listener_empty_m, \
  .debug = fsl_xfer_dbg_empty_m,     \
  .trace = {                         \
    .mask = 0,                       \
    .outputer = fsl_outputer_FILE_m  \
  },                                 \
  .op = {                            \
    .clone = 0,                      \
    .push = false,                   \
    .pull = false,                   \
    .privateContent  = false,        \
    .autosync = false                \
  },                                 \
  .metrics = {                       \
    .callback = NULL, .state = NULL  \
  },                                 \
  .password = {                      \
    .callback = NULL,                \
    .state = NULL,                   \
    .save = false,                   \
    .ignoreSaved = false             \
  },                                 \
  .channel = NULL                    \
}

/**
   Flags for use with fsl_xfer_config_from_flags(). This is a bit of a
   holdover from fcli rather than an integral part of the sync
   interface.
*/
enum fsl_sync_flags_e {
  /**
     Only perform one of the request operations if the fossil config
     setting "fcli.autosync" or "autosync" is set, preferring the
     former. "autosync" is fossil(1) standard flag for this, but clients
     may use "fcli.autosync" to trump that without changing fossil's
     behavior.
  */
  FSL_SYNC_AUTO     =     0x01,
  /** Perform a pull (read-only) sync. */
  FSL_SYNC_PULL     =     0x02,
  /** Perform a push (write-only) sync. */
  FSL_SYNC_PUSH     =     0x04,
  /** Perform a full (read/write) sync. */
  FSL_SYNC_FULL     =     FSL_SYNC_PULL | FSL_SYNC_PUSH,
  /** Perform a full sync, but only if autosync is enabled. */
  FSL_SYNC_FULLAUTO =     FSL_SYNC_AUTO | FSL_SYNC_FULL,
  /** Legacy flag - no longer used (we don't shell out anymore). */
  FSL_SYNC_NO_STDOUT =    0x10,
  /**
     Elide all sync-related messages, including metrics.
  */
  FSL_SYNC_NO_OUTPUT =    0x20,

  /**
     Do not save a password. By default it will be saved.
  */
  FSL_SYNC_NO_PW_SAVE =   0x80,
  /**
     Do not use a saved password. A password from the URL or the
     password callback may still be saved, as governed by
     FSL_SYNC_NO_PW_SAVE.
  */
  FSL_SYNC_NO_SAVED_PASSWORD = 0x100
};
typedef enum fsl_sync_flags_e fsl_sync_flags_e;

/**
   Given flags from the fsl_sync_flags_e enum, this function derives
   options to set on xc and sets them.

   It returns flags, possibly modified for autosync-related flags.

   If f does not have an opened repository, or on any error involving
   fetching state from f, -1 is returned and f's error state is
   updated.

   It may modify:

   - xc->op.pull, xc->op.push: depending on both the flags and, if
   applicable, autosync settings.

   - xc->listener.callback is set to a dummy no-op impl if the
   FSL_SYNC_NO_OUTPUT flag is used.

   - xc->password.save = false if FSL_SYNC_NO_PW_SAVE is used,
   else true.

   - xc->password.ignoreSaved = true if FSL_SYNC_NO_SAVED_PASSWORD is
   used, else false.

   - IFF xc->url is empty then it may be populated from the
     most recent sync-url for the current repo.
*/
fsl_flag32_t fsl_xfer_config_from_flags(fsl_cx * f,
                                        fsl_xfer_config *xc,
                                        fsl_flag32_t flags);

/**
   Empty-initialized fsl_xfer_config instance intended for
   non-const-copy initialization.
*/
extern const fsl_xfer_config fsl_xfer_config_empty;

/**
   Frees any memory which may be owned by p but does not
   free p.
*/
FSL_EXPORT void fsl_xfer_config_cleanup( fsl_xfer_config * p );

/**
   Tries to find a saved password for xf's URL. If found, it's
   assigned to xf->user.passwordToFree and xf->user.password, else
   xf->user.passwordToFree will be 0 and xf->user.password will be
   unmodified. It ignores db-level and search errors, except that
   failure to open the global config db is reported via xf's error
   state. A saved password which is empty is treated as not found.

   If no saved password is found and xf's config->password.callback is
   not 0, the callback is used to collect the password.

   If usePrompt is true then:

   a) If xf's config->password.callback is not 0 then it is used to collect
   the password, else

   b) xf's error state is set to FSL_RC_ACCESS, with a message which
   includes the user and the URL.

   Not finding a password is not an error here. When the sync itself
   finds no password for a URL whose user is not "anonymous" or
   "nobody", and has no callback, it fails with FSL_RC_ACCESS.
*/
FSL_EXPORT void fsl_xfer_pw_lookup(fsl_xfer * xf, bool usePrompt);

/**
   Options for use with fsl_clone(). Because its children
   may own memory, these must be cleaned up using
   fsl_clone_config_cleanup().
*/
struct fsl_clone_config {
  /** Options for fsl_repo_create(). */
  fsl_repo_create_opt repo;
  /**
     Options related to the transfer subsystem.
  */
  /**
     Core sync subsystem options.
  */
  fsl_xfer_config xfer;
};

typedef struct fsl_clone_config fsl_clone_config;

/**
   Empty-initialized fsl_clone_config instance intended for const-copy
   initialization.
*/
#define fsl_clone_config_empty_m {      \
  .repo = fsl_repo_create_opt_empty_m,  \
  .xfer = fsl_xfer_config_empty_m       \
}

/**
   Empty-initialized fsl_clone_config instance intended for
   non-const-copy initialization.
*/
extern const fsl_clone_config fsl_clone_config_empty;

/**
   Cleans up any memory owned by c and its members, but does
   not free c.
*/
void fsl_clone_config_cleanup(fsl_clone_config *c);

/**
   Clones a fossil repository using the given configuration
   and optional error object. The configuration bits are
   documented in the fsl_clone_config struct.

   This function uses a call-local savepoint so that all repository
   changes made by every protocol round are committed atomically. On
   any error, including a later round, the repository is restored to
   its pre-sync state. In the first reply, though, an error card is
   ignored, and a card or body which cannot be handled only ends
   processing of that reply; either way the clone goes on to its
   second round, as sections 8.3 and 10.1 of the sync draft require.
   A bad clone_seqno card, a project code mismatch, or content which
   does not match its hash is always an error.

   On success it will have created a new clone at the file specified
   by cc->repo.filename.

   On error non-0 is returned and, if `err` is not NULL, it will be
   populated with any available error information.
*/
FSL_EXPORT int fsl_clone( fsl_clone_config const * cc, fsl_error * err );

#if 0
/**
   Untested, incomplete, and it open design question remain regarding
   handling of the channel's state object's memory.

   Attempts to find a fsl_sc class capable of handling the given
   fossil URL.

   Currently handled:

   - http and https: uses fsl_sc_popen

   On success, returns a new instance, which the caller must
   eventually pass to fsl_sc_cleanup() and then to fsl_free().
*/
int fsl_sc_for_url( char const * zUrl, fsl_sc **pOut,  );
#endif

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_SYNC_H_INCLUDED */
/* end of file include/fossil-scm/sync.h */
/* start of file include/fossil-scm/pages.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_PAGES_H_INCLUDED)
#define ORG_FOSSIL_SCM_PAGES_H_INCLUDED
/*
  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-FileType: Code

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

  *****************************************************************************
  This file contains only Doxygen-format documentation, split up into
  Doxygen "pages", each covering some topic at a high level.  This is
  not the place for general code examples - those belong with their
  APIs.
*/

/** @mainpage libfossil

    Forewarning: this API assumes one is familiar with the Fossil SCM,
    ideally in detail. The Fossil SCM can be found at:

    https://fossil-scm.org

    libfossil is an experimental/prototype library API for the Fossil
    SCM. This API concerns itself only with the components of fossil
    which do not need user interaction or the display of UI components
    (including HTML and CLI output). It is intended only to model the
    core internals of fossil, off of which user-level applications
    could be built.

    The project's repository and additional information can be found at:

    https://fossil.wanderinghorse.net/r/libfossil/

    This code is 100% hypothetical/potential, and does not represent
    any Official effort of the Fossil project. It is up for any amount
    of change at any time and does not yet have a stable API.

    All Fossil users are encouraged to participate in its development,
    but if you are reading this then you probably already knew that
    :).

    This effort does not represent "Fossil Version 2", but provides an
    alternate method of accessing and manipulating fossil(1)
    repositories. Whereas fossil(1) is a monolithic binary, this API
    provides library-level access to (some level of) the fossil(1)
    feature set (that level of support grows approximately linearly
    with each new commit).

    Current status: alpha. Some bits are basically finished but there
    is a lot of work left to do. The scope is pretty much all
    Fossil-related functionality which does not require a user
    interface or direct user interaction, plus some range of utilities
    to support those which require a UI/user.
*/

/** @page page_terminology Fossil Terminology

    See also: https://fossil-scm.org/home/doc/trunk/www/concepts.wiki

    The libfossil API docs normally assume one is familiar with
    Fossil-internal terminology, which is of course a silly assumption
    to make. Indeed, one of libfossil's goals is to make Fossil more
    accessible, partly be demystifying it. To that end, here is a
    collection of terms one may come across in the API, along with
    their meanings in the context of Fossil...


    - REPOSITORY (a.k.a. "repo) is an sqlite database file which
    contains all content for a given "source tree." (We will use the
    term "source tree" to mean any tree of "source" (documents,
    whatever) a client has put under Fossil's supervision.)

    - CHECKOUT (a.k.a. "local source tree" or "working copy") refers
    to (A) the action of pulling a specific version of a repository's
    state from that repo into the local filesystem, and (B) a local
    copy "checked out" of a repo. e.g. "he checked out the repo," and
    "the changes are in his [local] checkout."

    - ARTIFACT is the generic term for anything stored in a repo. More
    specifically, ARTIFACT refers to "control structures" Fossil uses
    to internally track changes. These artifacts are stored as blobs
    in the database, just like any other content. For complete details
    and examples, see:
    https://fossil-scm.org/home/doc/tip/www/fileformat.wiki

    - A MANIFEST is a specific type of ARTIFACT - the type which
    records all metadata for a COMMIT operation (which files, which
    user, the timestamp, checkin comment, lineage, etc.). For
    historical reasons, MANIFEST is sometimes used as a generic term
    for ARTIFACT because what the fossil(1)-internal APIs originally
    called a Manifest eventually grew into other types of artifacts
    but kept the Manifest naming convention. In Fossil developer
    discussion, "manifest" most often means what this page calls
    ARTIFACT (probably because that how the C code is modelled).  The
    libfossil API calls uses the term "deck" instead of "manifest" to
    avoid ambiguity/confusion (or to move the confusion somewhere
    else, at least).

    - CHECKIN is the term libfossil prefers to use for COMMIT
    MANIFESTS. It is also the action of "checking in"
    (a.k.a. "committing") file changes to a repository.  A CHECKIN
    ARTIFACT can be one of two types: a BASELINE MANIFEST (or BASELINE
    CHECKIN) contains a list of all files in that version of the
    repository, including their file permissions and the UUIDs of
    their content. A DELTA MANFIEST is a checkin record which derives
    from a BASELINE MANIFEST and it lists only the file-level changes
    which happened between the baseline and the delta, recording any
    changes in content, permisions, or name, and recording
    deletions. Note that this inheritance of deltas from baselines is
    an internal optimization which has nothing to do with checkin
    version inheritance - the baseline of any given delta is normally
    _not_ its direct checkin version parent.

    - BRANCH, FORK, and TAG are all closely related in Fossil and are
    explained in detail (with pictures!) at:
    https://fossil-scm.org/home/doc/trunk/www/concepts.wiki
    In short: BRANCHes and FORKs are two names for the same thing, and
    both are just a special-case usage of TAGs.

    - MERGE or MERGING: the process of integrating one version of
    source code into another version of that source code, using a
    common parent version as the basis for comparison. This is
    normally fully automated, but occasionally human (and sometimes
    Divine) intervention is required to resolve so-called "merge
    conflicts," where two versions of a file change the same parts of
    a common parent version.

    - RID (Record ID) is a reference to the blob.rid field in a
    repository DB. RIDs are used extensively throughout the API for
    referencing content records, but they are transient values local
    to a given copy of a given repository at a given point in
    time. They _can_ change, even for the same content, (e.g. a
    rebuild can hypothetically change them, though it might not, and
    re-cloning a repo may very well change some RIDs). Clients must
    never rely on them for long-term reference to SCM'd data - always use
    the full UUID of such data. Even though they normally appear to be
    static, they are most explicitly NOT guaranteed to be. Nor are
    their values guaranteed to imply any meaning, e.g. "higher is
    newer" is not necessarily true because synchronization can import
    new remote content in an arbitrary order and a rebuild might
    import it in random order. The API uses RIDs basically as handles
    to arbitrary blob content and, like most C-side handles, must be
    considered transient in nature. That said, within the db, records
    are linked to each other exclusively using RIDs, so they do have
    some persistence guarantees for a given db instance.
*/


/** @page page_APIs High-level API Overview

    The primary end goals of this project are to eventually cover the
    following feature areas:

    - Provide embeddable SCM to local apps using sqlite storage.
    - Provide a network layer on top of that for synchronization.
    - Provide apps on top of those to allow administration of repos.

    To those ends, the fossil APIs cover the following categories of
    features:

    Filesystem:

    - Conversions of strings from OS-native encodings to UTF.
    fsl_utf8_to_unicode(), fsl_filename_to_utf8(), etc. These are
    primarily used internally but may also be useful for applications
    working with files (as most clients will). Actually... most of
    these bits are only needed for portability across Windows
    platforms.

    - Locating a user's home directory: fsl_find_home_dir()

    - Normalizing filenames/paths. fsl_file_canonical_name() and friends.

    - Checking for existence, size, and type (file vs directory) with
    fsl_is_file() and fsl_dir_check(), or the more general-purpose
    fsl_stat().


    Databases (sqlite):

    - Opening/closing sqlite databases and running queries on them,
    independent of version control features. See fsl_db_open() and
    friends. The actual sqlite-level DB handle type is abstracted out
    of the public API, largely to simplify an eventual port from
    sqlite3 to sqlite4 or (hypothetically) to other storage back-ends
    (not gonna happen - too much work).

    - There are lots of utility functions for oft-used operations,
    e.g. fsl_config_get_int32() and friends to fetch settings from one
    of several different configuration areas (global, repository,
    checkout, and "versionable" settings).

    - Pseudo-recusive transactions: fsl_db_txn_begin() and
    fsl_db_txn_end(). sqlite does not support truly nested
    transactions, but they can be simulated quite effectively so long
    as certain conventions are adhered to.

    - Cached statements (an optimization for oft-used queries):
    fsl_db_prepare_cached() and friends.


    The DB API is (as Brad Harder put so well) "very present" in the
    public API. While the core API provides access to the underlying
    repository data, it cannot begin to cover even a small portion of
    potential use cases. To that end, it exposes the DB API so that
    clients who want to custruct their own data can do so. It does
    require research into the underlying schemas, but gives
    applications the ability to do _anything_ with their repositories
    which the core API does not account for. Historically, the ability
    to create ad-hoc data structures as needed, in the form of SQL
    queries, has accounted for much of Fossil's feature flexibility.


    Deltas:

    - Creation and application of raw deltas, using Fossil's delta
    format, independent of version control features. See
    fsl_delta_create() and friends. These are normally used only at
    the deepest internal levels of fossil, but the APIs are exposed so
    that clients can, if they wish, use them to deltify their own
    content independently of fossil's internally-applied
    deltification. Doing so is remarkably easy, but completely
    unnecessary for content which will be stored in a repo, as Fossil
    creates deltas as needed.


    SCM:

    - A "context" type (fsl_cx) which manages a repository db and,
    optionally, a checkout db. Read-only operations on the DB are
    working and write functionality (adding repo content) is
    ongoing. See fsl_cx, fsl_cx_init(), and friends.

    - The fsl_deck class assists in parsing, creating, and outputing
    "artifacts" (manifests, control (tags), events, etc.). It gets its
    name from it being container for "a collection of cards" (which is
    what a Fossil artifact is).

    - fsl_content_get() expands a (possibly) deltified blob into its
    full form, and fsl_content_blob() can be used to fetch a raw blob
    (possibly a raw delta).

    - A number of routines exist for converting symbol names to RIDs
    (fsl_sym_to_rid()), UUIDs to RIDs (fsl_uuid_to_rid(),
    and similar commonly-needed lookups.


    Input/Output:

    - The API defines several abstractions for i/o interfaces, e.g.
    fsl_input_f() and fsl_output_f(), which allow us to accept/emit
    data from/to arbitrary streamable (as opposed to random-access)
    sources/destinations. A fsl_cx instance is configured with an
    output channel, the intention being that all clients of that
    context should generate any output through that channel, so that
    all compatible apps can cooperate more easily in terms of i/o. For
    example, the s2 script binding for libfossil routes fsl_output()
    through the script engine's i/o channels, so that any output
    generated by libfossil-using code it links to can take advantage
    of the script-side output features (such as output buffering,
    which is needed for any non-trivial CGI output). That said: the
    library-level code does not actually generate output to that
    channel, but higher-level code like fcli does, and clients are
    encouraged to in order to enable their app's output to be
    redirected to an arbitrary UI element, be it a console or UI
    widget.


    Utilities:

    - fsl_b, a generic buffer class, is used heavily by the
    library.  See fsl_b and friends.

    - fsl_appendf() provides printf()-like functionality, but sends
    its output to a callback function (optionally stateful), making it
    the one-stop-shop for string formatting within the library.

    - The fsl_error class is used to propagate error information
    between the libraries various levels and the client.

    - The fsl_list class acts as a generic container-of-pointers, and
    the API provides several convenience routines for managing them,
    traversing them, and cleaning them up.

    - Hashing: there are a number of routines for calculating SHA1,
    SHA3, and MD5 hashes. See fsl_sha1_cx, fsl_sha3_cx, fsl_md5_cx,
    and friends.

    - zlib compression is used for storing artifacts. See
    fsl_data_is_compressed(), fsl_b_compress(), and friends.
    These are never needed at the client level, but are exposed "just
    in case" a given client should want them.
*/

/** @page page_is_isnot Fossil is/is not...

    Through porting the main fossil application into library form,
    the following things have become very clear (or been reinforced)...

    Fossil is...

    - _Exceedingly_ robust. Not only is sqlite literally the single
    most robust application-agnostic container file format on the
    planet, but Fossil goes way out of its way to ensure that what
    gets put in is what gets pulled out. It cuts zero corners on data
    integrity, even adding in checks which seem superfluous but
    provide another layer of data integrity (i'm primarily talking
    about the R-card here, but there are other validation checks). It
    does this at the cost of memory and performance (that said, it's
    still easily fast enough for its intended uses). "Robust" doesn't
    mean that it never crashes nor fails, but that it does so with
    (insofar as is technically possible) essentially zero chance of
    data loss/corruption.

    - Long-lived: the underlying data format is independent of its
    storage format. It is, in principal, usable by systems as yet
    unconceived by the next generation of programmers. This
    implementation is based on sqlite, but the model can work with
    arbitrary underlying storage.

    - Amazingly space-efficient. The size of a repository database
    necessarily grows as content is modified. However, Fossil's use of
    zlib-compressed deltas, using a very space-efficient delta format,
    leads to tremendous compression ratios. As of this writing (March,
    2021), the main Fossil repo contains approximately 5.36GB of
    content, were we to check out every single version in its
    history. Its repository database is only 64MB, however, equating
    to a 83:1 compression ration. Ratios in the range of 20:1 to 40:1
    are common, and more active repositories tend to have higher
    ratios. The TCL core repository, with just over 15 years of code
    history (imported, of course, as Fossil was introduced in 2007),
    is (as of September 2013) only 187MB, with 6.2GB of content and a
    33:1 compression ratio.

    Fossil is not...

    - Memory-light. Even very small uses can easily suck up 1MB of RAM
    and many operations (verification of the R card, for example) can
    quickly allocate and free up hundreds of MB because they have to
    compose various versions of content on their way to a specific
    version. To be clear, that is total RAM usage, not _peak_ RAM
    usage. Peak usage is normally a function of the content it works
    with at a given time, often in direct relation to (but
    significantly more than) the largest single file processed in a
    given session. For any given delta application operation, Fossil
    needs the original content, the new content, and the delta all in
    memory at once, and may go through several such iterations while
    resolving deltified content. Verification of its 'R-card' alone
    can require a thousand or more underlying DB operations and
    hundreds of delta applications. The internals use caching where it
    would save us a significant amount of db work relative to the
    operation in question, but relatively high memory costs are
    unavoidable. That's not to say we can't optimize a bit, but first
    make it work, then optimize it. The library takes care to re-use
    memory buffers where it is feasible (and not too intrusive) to do
    so, but there is yet more RAM to be optimized away in this regard.
*/

/** @page page_threading Threads and Fossil

    It is strictly illegal to use a given fsl_cx instance from more
    than one thread. Period.

    It is legal for multiple contexts to be running in multiple
    threads, but only if those contexts use different
    repository/checkout databases. Though access to the storage is,
    through sqlite, protected via a mutex/lock, this library does not
    have a higher-level mutex to protect multiple contexts from
    colliding during operations. So... don't do that. One context, one
    repo/checkout.

    Multiple application instances may each use one fsl_cx instance to
    share repo/checkout db files, but must be prepared to handle
    locking-related errors in such cases. e.g. db operations which
    normally "always work" may suddenly pause for a few seconds before
    giving up while waiting on a lock when multiple applications use
    the same database files. sqlite's locking behaviours are
    documented in great detail at https://sqlite.org.
 */

/** @page page_artifacts Creating Artifacts

    A brief overview of artifact creating using this API. This is targeted
    at those who are familiar with how artifacts are modelled and generated
    in fossil(1).

    Primary artifact reference:

    https://fossil-scm.org/home/doc/trunk/www/fileformat.wiki

    In fossil(1), artifacts are generated via the careful crafting of
    a memory buffer (large string) in the format described in the
    document above. While it's relatively straightforward to do, there
    are lots of potential gotchas, and a bug can potentially inject
    "bad data" into the repo (though the verify-before-commit process
    will likely catch any problems before the commit is allowed to go
    through). The libfossil API uses a higher-level (OO) approach,
    where the user describes a "deck" of cards and then tells the
    library to save it in the repo (fsl_deck_save()) or output it to
    some other channel (fsl_deck_output()). The API ensures that the
    deck's cards get output in the proper order and that any cards
    which require special treatment get that treatment (e.g. the
    "fossilize" encoding of certain text fields). The "deck" concept
    is equivalent to Artifact in fossil(1), but we use the word deck
    because (A) Artifact is highly ambiguous in this context and (B)
    deck is arguably the most obvious choice for the name of a type
    which acts as a "container of cards."

    Ideally, client-level code will never have to create an artifact
    via the fsl_deck API (because doing so requires a fairly good
    understanding of what the deck is for in the first place,
    including the individual Cards). The public API strives to hide
    those levels of details, where feasible, or at least provide
    simpler/safer alternatives for basic operations. Some operations
    may require some level of direct work with a fsl_deck
    instance. Likewise, much read-only functionality directly exposes
    fsl_deck to clients, so some familiarity with the type and its
    APIs will be necessary for most clients.

    The process of creating an artifact looks a lot like the following
    code example. We have elided error checking for readability
    purposes, but in fact this code has undefined behaviour if error
    codes are not checked and appropriately reacted to.

    ```
    fsl_deck deck = fsl_deck_empty;
    fsl_deck * d = &deck ; // for typing convenience.
    // Doxygen bug ^^^^^^^ requires space before semicolon!
    fsl_deck_init( fslCtx, d, FSL_SATYPE_CONTROL ); // must come first
    fsl_deck_D_set( d, fsl_julian_now() );
    fsl_deck_U_set( d, "your-fossil-name", -1 );
    fsl_deck_T_add( d, FSL_TAGTYPE_ADD, "...uuid being tagged...",
                   "tag-name", "optional tag value");
    ...
    // Now output it to stdout:
    fsl_deck_output( f, d, fsl_output_f_FILE, stdout );
    // See also: fsl_deck_save(), which stores it in the db and
    // "crosslinks" it.
    fsl_deck_finalize(d);
    ```

    The order the cards are added to the deck is irrelevant - they
    will be output in the order specified by the Fossil specs
    regardless of their insertion order. Each setter/adder function
    knows, based on the deck's type (set via fsl_deck_init()), whether
    the given card type is legal, and will return an error (probably
    FSL_RC_TYPE) if an attempt is made to add a card which is illegal
    for that deck type. Likewise, fsl_deck_output() and
    fsl_deck_save() confirm that the decks they are given contain (A)
    only allowed cards and (B) have all required
    cards. fsl_deck_output() will "unshuffle" the cards, making sure
    they're in the correct order.

    Sidebar: normally outputing a structure can use a const form of
    that structure, but the traversal of F-cards in a deck requires
    (for the sake of delta manifests) using a non-const cursor. Thus
    outputing a deck requires a non-const instance. If it weren't for
    delta manifests, we could be "const-correct" here.
*/

/** @page page_transactions DB Transactions

    The fsl_db_txn_begin() and fsl_db_txn_end()
    functions implement a basic form of recursive transaction,
    allowing the library to start and end transactions at any level
    without having to know whether a transaction is already in
    progress (sqlite3 does not natively support nested
    transactions). A rollback triggered in a lower-level transaction
    will propagate the error back through the transaction stack and
    roll back the whole transaction, providing us with excellent error
    recovery capabilities (meaning we can always leave the db in a
    well-defined state).

    It is STRICTLY ILLEGAL to EVER begin a transaction using "BEGIN"
    or end a transaction by executing "COMMIT" or "ROLLBACK" directly
    on a fsl_db instance. Doing so bypasses internal state which needs
    to be kept abreast of things and will cause Grief and Suffering
    (on the client's part, not mine).

    Begin a transaction which will write the repository or checkout db
    with fsl_cx_txn_begin_write(), which takes those dbs' write locks
    before the transaction reads them. A transaction begun with
    fsl_cx_txn_begin() or fsl_db_txn_begin() takes a write lock at its
    first write. If it has read that db by then and another connection
    holds the lock, SQLite reports the db as locked at once, without
    waiting for the busy timeout.

    Tip: implementing a "dry-run" mode for most fossil operations is
    trivial by starting a transaction before performing the
    operations. Many operations run in a transaction, but if the
    client starts one of his own they can "dry-run" any op by simply
    rolling back the transaction he started. Abstractly, that looks
    like this pseudocode:

    ```
    db.begin();
    fsl.something();
    fsl.somethingElse();
    if( dryRun ) db.rollback();
    else db.commit();
    ```
*/

/** @page page_code_conventions Code Conventions

    Project and Code Conventions...

    Foreword: all of this more or less evolved organically or was
    inherited from fossil(1) (where it evolved organically, or was
    inherited from sqilte (where it evol...)), and is written up here
    more or less as a formality. Historically i've not been a fan of
    coding conventions, but as someone else put it to me, "the code
    should look like it comes from a single source," and the purpose
    of this section is to help orient those looking to hack in the
    sources. Note that most of what is said below becomes obvious
    within a few minutes of looking at the sources - there's nothing
    earth-shatteringly new nor terribly controversial here.

    The Rules/Suggestions/Guidelines/etc. are as follows...


    - C99 is the basis. It was C89 until 2021-02-12.

    - The canonical build environment uses the most restrictive set of
    warning/error levels possible. It is highly recommended that
    non-canonical build environments do the same. Adding -Wall -Werror
    -pedantic does _not_ guaranty that all C compliance/portability
    problems can be caught by the compiler, but it goes a long way in
    helping us to write clean code. The clang compiler is particularly
    good at catching subtle foo-foo's such as uninitialized variables.

    - API docs (as you may have already noticed), does not (any
    longer) follow Fossil's comment style, but instead uses
    Doxygen-friendly formatting. Each comment block MUST start with
    two or more asterisks, or '*!', or doxygen apparently doesn't
    understand it
    (https://www.stack.nl/~dimitri/doxygen/manual/docblocks.html). When
    adding code snippets and whatnot to docs, please use doxygen
    conventions if it is not too much of an inconvenience. All public
    APIs must be documented with a useful amount of detail. If you
    hate documenting, let me know and i'll document it (it's what i do
    for fun).

    - Public API members have a fsl_ or FSL_ prefix (fossil_ seems too
    long). For private/static members, anything goes. Optional or
    "add-on" APIs (e.g. ::fcli) may use other prefixes, but are
    encouraged use an "f-word" (as it were), simply out of deference
    to long-standing software naming conventions.

    - Internal APIs, especially non-static ones, start with `fsl__` or
    `FSL__`, with two underscores. Such APIs must never be used in
    client-side code.

    - Public-API structs and functions use lower_underscore_style().
    Static/internal APIs may use different styles. It's not uncommon
    to see UpperCamelCase for file-scope structs.

    - Function parameters and function-scope vars have no set
    conventions - implementors are free to name those however they
    like.

    - Overall style, especially scope blocks and indentation, should
    follow Fossil's.  We are _not at all_ picky about whether or not
    there is a space after/before parens in if( foo ), and similar
    small details, just the overall code pattern and two-space
    indentation. Hard tabs are verboten.

    - Structs and enums all get the optional typedef so that they do
    not need to be qualified with 'struct' resp. 'enum' when
    used. Because of how doxygen tracks those, the typedef should be
    separate from the struct declaration, rather than combinding
    those into a single declaration.

    - Function typedefs are named fsl_XXX_f. Implementations of such
    typedefs/interfaces are typically named fsl_XXX_f_SUFFIX(), where
    SUFFIX describes the implementation's
    specialization. e.g. fsl_output_f() is a callback
    typedef/interface and fsl_output_f_FILE() is a concrete
    implementation for FILE handles.

    - Enums tend to be named fsl_XXX_e.

    - Functions follow the naming pattern prefix_NOUN_VERB(), rather
    than the more C-conventional prefix_VERB_NOUN(),
    e.g. fsl_foo_get() and fsl_foo_set() rather than fsl_get_foo() and
    fsl_get_foo(). The primary reasons are (A) sortability for
    document processors and (B) they more naturally match with OO API
    conventions, e.g. `noun.verb()`. A few cases knowingly violate
    this convention for the sake of readability or sorting of several
    related functions (e.g. fsl_db_get_TYPE() instead of
    fsl_db_TYPE_get()).

    - Structs intended to be creatable on the stack are accompanied by
    a const instance named fsl_STRUCT_NAME_empty, and possibly by a
    macro named fsl_STRUCT_NAME_empty_m, both of which are
    "default-initialized" instances of that struct. This is superiour
    to using `memset()` for struct initialization because we can
    define (and document) arbitrary default values and all clients who
    copy-construct them are unaffected by many types of changes to the
    struct's signature (though they may need a recompile). The
    intention of the fsl_STRUCT_NAME_empty_m macro is to provide a
    struct-embeddable form for use in other structs or
    copy-initialization of const structs, and the `_m` macro is always
    used to initialize its const struct counterpart. e.g. the library
    guarantees that fsl_cx_empty_m (a macro representing an empty
    fsl_cx instance) holds the same default values as fsl_cx_empty (a
    const fsl_cx value).

    - Returning int vs fsl_int_t vs fsl_size_t: int is used as a
    conventional result code. fsl_int_t is often used as a signed
    length-style result code (e.g. printf() semantics). Unsigned
    ranges use fsl_size_t. Ints are (also) used as a "triplean" (3
    potential values, e.g. <0, 0, >0). fsl_int_t also guarantees that
    it will be 64-bit if available, so can be used for places where
    large values are needed but a negative value is legal (or handy),
    e.g. the final arguments for fsl_strndup() and
    fsl_b_append(). The use of the fsl_xxx_t typedefs, rather
    than (unsigned) int, is primarily for readability/documentation,
    e.g. so that readers can know immediately that the function uses a
    given argument or return value following certain API-wide
    semantics. It also allows us to better define platform-portable
    printf/scanf-style format modifiers for them (analog to C99's
    PRIi32 and friends), which often come in handy.

    - Signed vs. unsigned types for size/length arguments: use the
    fsl_int_t (signed) argument type when the client may legally pass
    in a negative value as a hint that the API should use fsl_strlen()
    (or similar) to determine a byte array's length. Use fsl_size_t
    when no automatic length determination is possible (or desired),
    to "force" the client to pass the proper length. Internally
    fsl_int_t is used in some places where fsl_size_t "should" be used
    because some ported-in logic relies on loop control vars being
    able to go negative. Additionally, fossil internally uses negative
    blob lengths to mark phantom blobs, and care must be taken when
    using fsl_size_t with those.

    - Functions taking elipses (...) are accompanied by a va_list
    counterpart named the same as the (...) form plus a trailing
    'v'. e.g. fsl_appendf() and fsl_appendfv(). We do not use the
    printf()/vprintf() convention because that hoses sorting of the
    functions in generated/filtered API documentation.

    - Error handling/reporting: please keep in mind that the core code
    is a library, not an application.  The main implication is that
    all lib-level code needs to check for errors whereever they can
    happen (e.g. on every single memory allocation, of which there are
    many) and propagate errors to the caller, to be handled at his
    discretion. The app-level code (::fcli) is not particularly strict
    in this regard, and installs its own allocator which abort()s on
    allocation error, which simplifies app-side code somewhat
    vis-a-vis lib-level code. When reporting an error can be improved
    by the inclusion of an error string, functions like
    fsl_cx_err_set() can be used to report the error. Several of the
    high-level types in the API have fsl_error object member which
    contains such error state. The APIs which use that state take care
    to use-use the error string memory whenever possible, so setting
    an error string is often a non-allocating operation.
*/


/** @page page_fossil_arch Fossil Architecture Overview

    An introduction to the Fossil architecture. These docs
    are basically just a reformulation of other, more detailed,
    docs which can be found via the main Fossil site, e.g.:

    - https://fossil-scm.org/home/doc/trunk/www/concepts.wiki

    - https://fossil-scm.org/home/doc/trunk/www/fileformat.wiki

    Fossil's internals are fundamentally broken down into two basic
    parts. The first is a "collection of blobs."  The simplest way to
    think of this (and it's not far from the full truth) is a
    directory containing lots of files, each one named after a hash of
    its contents. This pool contains ALL content required for a
    repository - all other data can be generated from data contained
    here. Included in the blob pool are so-called Artifacts. Artifacts
    are simple text files with a very strict format, which hold
    information regarding the idententies of, relationships involving,
    and other metadata for each type of blob in the pool. The most
    fundamental Artifact type is called a Manifest, and a Manifest
    tells us, amongst other things, which of the hash-based file names
    has which "real" file name, which version the parent (or parents!)
    is (or are), and other data required for a "commit" operation.

    The blob pool and the Manifests are all a Fossil repository really
    needs in order to function. On top of that basis, other forms of
    Artifacts provide features such as tagging (which is the basis of
    branching and merging), wiki pages, and tickets. From those
    Artifacts, Fossil can create/calculate all sorts of
    information. For example, as new Artifacts are inserted it
    transforms the Artifact's metadata into a relational model which
    sqlite can work with. That leads us to what is conceptually the
    next-higher-up level, but is in practice a core-most component...

    Storage. Fossil's core model is agnostic about how its blobs are
    stored, but libfossil and fossil(1) both make heavy use of sqlite
    to implement many of their features. These include:

    - Transaction-capable storage. It's almost impossible to corrupt a
    Fossil db in normal use. sqlite3 offers literally the most robust
    general-purpose file format on the planet.

    - The storage of the raw blobs.

    - Artifact metadata is transformed into various DB structures
    which allow libfossil to traverse historical data much more
    efficiently than would be possible without a db-like
    infrastructure (and everything that implies). These structures are
    kept up to date as new Artifacts are stored in a repository,
    either via local edits or synching in remote content. These data
    are incrementally updated as changes are made to a repo.

    - A tremendous amount of the "leg-work" in processing the
    repository state is handled by SQL queries, without which the
    library would easily require 5-10x more code in the form of
    equivalent hard-coded data structures and corresponding
    functionality. The db approach allows us to ad-hoc structures as
    we need them, providing us a great deal of flexibility.

    All content in a Fossil repository is in fact stored in a single
    database file. Fossil additionally uses another database (a
    "checkout" db) to keep track of local changes, but the repo
    contains all "fossilized" content. Each copy of a repo is a
    full-fledged repo, each capable of acting as a central copy for
    any number of clones or checkouts.

    That's really all there is to understand about Fossil. How it does
    its magic, keeping everything aligned properly, merging in
    content, how it stores content, etc., is all internal details
    which most clients will not need to know anything about in order
    to make use of fossil(1). Using libfossil effectively, though,
    does require learning _some_ amount of how Fossil works. That will
    require taking some time with _other_ docs, however: see the
    links at the top of this section for some starting points.


    Sidebar:

    - The only file-level permission Fossil tracks is the "executable"
    (a.k.a. "+x") bit. It internally marks symlinks as a permission
    attribute, but that is applied much differently than the
    executable bit and only does anything useful on platforms which
    support symlinks.

*/

#endif
/* ORG_FOSSIL_SCM_PAGES_H_INCLUDED */
/* end of file include/fossil-scm/pages.h */
/* start of file include/fossil-scm/cli.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(_ORG_FOSSIL_SCM_FCLI_H_INCLUDED_)
#define _ORG_FOSSIL_SCM_FCLI_H_INCLUDED_
/*
  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-FileType: Code

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

  *****************************************************************************
  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.
*/

#include <stdlib.h> /* EXIT_SUCCESS and friends */
#include <assert.h>

/** @page page_fcli fcli (formerly FossilApp)

    ::fcli (formerly FossilApp) provides a small framework for
    bootstrapping simple libfossil applications which only need a
    single fsl_cx instance managing a single checkout and/or
    repository. It is primarily intended for use with CLI apps
    implementing features similar to those in fossil(1), but can also
    be used with GUI apps. It provides the following basic services to
    applications:

    - The global ::fcli struct holds global state.

    - fcli_setup_v2() bootstraps the environment. This must be the
    first call made into the API, as this replaces the libfossil
    memory allocator with a fail-fast variant to simplify app-level
    code a bit (by removing the need to check for OOM errors). This
    also registers an atexit(3) handler to clean up fcli-owned
    resources at app shutdown.

    - Automatically tries to open a checkout (and its associated
    repository) under the current directory, but not finding one
    is not an error (the app needs to check for this if it should
    be an error: use fsl_cx_db_repo() and fsl_cx_db_ckout()).

    - fcli_flag(), fcli_next_arg(), and friends provide uniform access
    to CLI arguments.

    - A (very) basic help subsystem, triggered by the --help or -? CLI
    flags, or if the first non-flag argument is "help".  Applications
    may optionally assign fcli.appHelp to a function which outputs
    app-specific help.

    - Basic error reporting mechanism. See fcli_err_report().

    The source tree contains several examples of using fcli
    in the files named f-apps/f-*.c.
*/

/**
   Outputs the given fsl_appendf()-compatible formatting expression
   (2nd arg) to fcli_printf() if fcli.verbose>=N, else it does
   nothing.

   Reminder: this uses a while(0) loop so that the macro can end
   with a semicolon without triggering a warning.
*/
#define FCLI_VN(N,pfexp)                        \
  if(fcli.config.verbose>=(N)) do {        \
      fcli_printf("VERBOSE %d: ", (int)(N));    \
      fcli_printf pfexp;                        \
  } while(0)

/**
   Convenience form of FCLI_VN for level-2 verbosity.
*/
#define FCLI_V2(pfexp) FCLI_VN(2,pfexp)

/**
   Convenience form of FCLI_VN for level-1 verbosity. Levels 1 and 2
   are intended for application-level use. Levels 3+ are intended for
   fcli use.
*/
#define FCLI_V(pfexp) FCLI_VN(1,pfexp)

#if defined(__cplusplus)
extern "C" {
#endif

/**
   Result codes specific to the fcli API.
*/
enum fcli_rc_e {
/**
   For use with fcli_flag_callback_f() implementations to indicate
   that the flag processor should check for that flag again.
*/
FCLI_RC_FLAG_AGAIN = FSL_RC_end + 1,
/**
   Returned from fcli_dispatch_commands() when the string returned
   from fcli_next_arg() does not match any fcli_command in the list.
*/
FCLI_RC_NO_CMD,
/**
   Returned from fcli_setup() if flag processing invokes the help
   system. This is an indication that the app should exit immediately
   with a 0 result code.
*/
FCLI_RC_HELP
};
/**
   Types for use with the fcli_cliflag::flagType field.  The value of
   that field determines how the CLI flag handling interprets the
   fcli_cliflag::flagValue void pointer.
*/
enum fcli_cliflag_type_e {
/** Sentinel placeholder. */
FCLI_FLAG_TYPE_INVALID = 0,
/** Represents bool. */
FCLI_FLAG_TYPE_BOOL,
/** Represents bool, but gets set to false if the flag is set. */
FCLI_FLAG_TYPE_BOOL_INVERT,
/** Works like FCLI_FLAG_TYPE_BOOL but toggles the target
    boolean each time it's seen. */
FCLI_FLAG_TYPE_BOOL_TOGGLE,
/** Represents int32_t. */
FCLI_FLAG_TYPE_INT32,
/** Represents int64_t. */
FCLI_FLAG_TYPE_INT64,
/** Represents fsl_id_t, which might be either int32_t or int64_t. */
FCLI_FLAG_TYPE_ID,
/** Represents double. */
FCLI_FLAG_TYPE_DOUBLE,
/** Represents (char const *). */
FCLI_FLAG_TYPE_CSTR
};

typedef struct fcli_cliflag fcli_cliflag;
/**
   Callback handler for CLI flag handling. It is passed the flag in
   question, containing its state after fcli has processed its
   flagValue part.

   If the callback returns FCLI_RC_FLAG_AGAIN, the flag handler will
   check for that flag again (for as long as the handler keeps
   returning that value and as long as the flag repeats in the
   argument list). This can be used to implement repeatable flags.

   If it returns any other non-0 value, fcli_setup()
   resp. fcli_process_flags() will fail with that result code.

   Achtung: during fcli_setup(), at the time these are processed, fcli
   will not yet have opened up a repository or checkout, so the
   callback will not have access to things like symbolic-name-to-UUID
   conversion at this level. Apps which need to do such work on their
   arguments must first queue up the input and process it after
   fcli_setup() returns. Apps which process the flags using
   fcli_process_flags() after setup is complete will have access to
   such features.
*/
typedef int (*fcli_flag_callback_f)(fcli_cliflag const *);

/**
   Models a single CLI flag. Its relative complexity is largely to
   support generation of help text.

   @see fcli_process_flags()
*/
struct fcli_cliflag {
  /**
     "Short-form" for this flag, noting that there's no restriction on
     its length. Either of flagShort and flagLong, but not both, may be
     NULL.
  */
  const char * flagShort;
  /**
     "Long-form" for this flag, noting that there's no restriction on
     its length.
  */
  const char * flagLong;

  /**
     Specifies how to interpret the data pointed to by
     this->flagValue. See that member for details.
  */
  enum fcli_cliflag_type_e flagType;

  /**
     If not NULL, the member is the target of the flag's value.
     Its exact interpretation depends on the value of this->flagType:

     - FCLI_FLAG_TYPE_BOOL: a pointer to a bool. Existence
     of the flag causes it to be set to true.

     - FCLI_FLAG_TYPE_BOOL_INVERT: a pointer to a bool, but
     existence of the flag causes it to be set to false.

     - FCLI_FLAG_TYPE_BOOL_TOGGLE: works like the other BOOL
     varants and it toggles that value on each invocation.

     - FCLI_FLAG_TYPE_INT32: a pointer to an int32_t. The flag's
     value must be an optionally signed base-10 integer in the range
     of int32_t.

     - FCLI_FLAG_TYPE_INT64: a pointer to an int64_t. The flag's
     value must be an optionally signed base-10 integer in the range
     of int64_t.

     - FCLI_FLAG_TYPE_ID: a pointer to a fsl_id_t, which
     can be either int32_t or int64_t. The flag's value must be a
     non-negative base-10 integer in the range of fsl_id_t.

     - FCLI_FLAG_TYPE_DOUBLE: a pointer to a double. The flag's
     value is converted using strtod() and must contain nothing
     after the number.

     A numeric value which does not meet those rules causes
     fcli_process_flags() to fail with FSL_RC_RANGE and an error
     message naming the flag and the value.

     - FCLI_FLAG_TYPE_CSTR: a pointer to a (const char *). The flag's
     value will be assigned on without further interpretation.

     If this member is not NULL: If the flag is set, this value will
     be assigned to. If the flag is not set in the CLI args, this
     value is not written to.

     If this member is NULL then fcli_process_flags() will simply skip
     over it, but the help-text generator will process it. This can be
     used to set up flags which will appear in the --help text but
     which are processed separately (or outright ignored) by the app.

     The underlying flag value's string memory is owned by fcli and is
     valid until the app exits.
  */
  void * flagValue;

  /**
     Optional descriptive label to be used when rendering help text:

     -x|--x-flag=ABCD

     If it is NULL, the --help text generator will choose a value of
     the ABCD part which depends on this->flagType.

     This is only used if this->flagType is not one of
     (FCLI_FLAG_TYPE_BOOL, FCLI_FLAG_TYPE_BOOL_INVERT,
     FCLI_FLAG_TYPE_BOOL_TOGGLE). For those types (which have no
     client-given values), this member is ignored when generating help
     text.
  */
  const char * flagValueLabel;

  /**
     Optional callback which gets passed the flag, if it is set, after
     fcli has assigned the flagValue entry (if it is not NULL).
     See this data type's docs for more details.
  */
  fcli_flag_callback_f callback;

  /**
     Help text for the flag. Intended to be displayed in the context
     of a --help listing of flags.
  */
  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*/}
/** 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
   array. Example usage:

   ```
   bool flag1 = true, flag2 = false;
   int32_t flag3 = 0;
   const char * flag4 = 0;
   const fcli_cliflag cliFlags[] = {
     FCLI_FLAG_BOOL("x","xyz",&flag1,"Flag 1."),
     FCLI_FLAG_BOOL_INVERT(NULL,"yzx",&flag2,"Flag 2."),
     FCLI_FLAG_INT32("z",NULL,"value",&flag3,"Flag 3"),
     FCLI_FLAG("f","file","filename",&flag4,
               "Input file. May optionally be passed as the first "
               "non-flag argument."),
     fcli_cliflag_empty_m // list MUST end with this (or equivalent)
   };
   fcli_help_info const appHelp = {...};

   int rc = fcli_setup_v2(argc, argv, cliFlags, &appHelp);
   ```

   BE CAREFUL with the data types, as we're using (void*) to access
   data of an arbitrary type, the type being defined by a separate
   field in the fcli_cliflag object.
*/
#define FCLI_FLAG_xxx /* for doc purposes only */
//Members:
//{short, long, type, tgt, valueDescr., callback, help}
/** Bool-type flag. */
#define FCLI_FLAG_BOOL(S,L,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_BOOL,TGT,NULL,NULL,HELP}
/** Bool-type flag, but set to false if flag is set. */
#define FCLI_FLAG_BOOL_INVERT(S,L,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_BOOL_INVERT,TGT,NULL,NULL,HELP}
/** Bool-type flag toggled for each flag instance. */
#define FCLI_FLAG_BOOL_TOGGLE(S,L,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_BOOL_TOGGLE,TGT,NULL,NULL,HELP}
/** Bool-type flag with a callback. */
#define FCLI_FLAG_BOOL_X(S,L,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_BOOL,TGT,NULL,CALLBACK,HELP}
/** Bool-type flag with a callback, but set to false if the flag is set. */
#define FCLI_FLAG_BOOL_INVERT_X(S,L,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_BOOL_INVERT,TGT,NULL,CALLBACK,HELP}
/** String-type flag. */
#define FCLI_FLAG_CSTR(S,L,LBL,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_CSTR,TGT,LBL,NULL,HELP}
#define FCLI_FLAG FCLI_FLAG_CSTR
/** String-type flag with a callback. */
#define FCLI_FLAG_CSTR_X(S,L,LBL,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_CSTR,TGT,LBL,CALLBACK,HELP}
#define FCLI_FLAG_X FCLI_FLAG_CSTR_X
/** int32-type flag. */
#define FCLI_FLAG_I32(S,L,LBL,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_INT32,TGT,LBL,NULL,HELP}
/** int32-type flag with a callback. */
#define FCLI_FLAG_I32_X(S,L,LBL,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_INT32,TGT,LBL,CALLBACK,HELP}
/** int64-type flag. */
#define FCLI_FLAG_I64(S,L,LBL,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_INT64,TGT,LBL,NULL,HELP}
/** int64-type flag with a callback. */
#define FCLI_FLAG_I64_X(S,L,LBL,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_INT64,TGT,LBL,CALLBACK,HELP}
/** fsl_id_t-type flag. */
#define FCLI_FLAG_ID(S,L,LBL,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_ID,TGT,LBL,NULL,HELP}
/** fsl_id_t-type flag with a callback. */
#define FCLI_FLAG_ID_X(S,L,LBL,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_ID,TGT,LBL,CALLBACK,HELP}
/** double-type flag. */
#define FCLI_FLAG_DBL(S,L,LBL,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_DOUBLE,TGT,LBL,NULL,HELP}
/** double-type flag with a callback. */
#define FCLI_FLAG_DBL_X(S,L,LBL,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_DOUBLE,TGT,LBL,CALLBACK,HELP}

/**
   Structure for holding app-level --help info.
*/
struct fcli_help_info {
  /** Brief description of what the app does. */
  char const * briefDescription;
  /** Brief usage text. It will be prefixed by the app's name and
      "[options]". e.g. "file1 ... fileN".
  */
  char const * briefUsage;
  /**
     If not 0 then this is called after outputing any flags' help.
     It should output any additional help text using f_out().
  */
  void (*callback)(void);
};
typedef struct fcli_help_info fcli_help_info;

/**
   The fcli_t type, accessed by clients via the ::fcli
   global instance, contains various data for managing a basic
   Fossil SCM application build using libfossil.

   Usage notes:

   - All non-const pointer members are owned and managed by the
   fcli API. Clients may reference them but must be aware of
   lifetimes if they plan to hold the reference for long.

*/
struct fcli_t {
  /**
     The shared fsl_cx instance. It gets initialized by
     fcli_setup() and cleaned up post-main().

     this->f is owned by this object and will be cleaned up at app
     shutdown (post-main).
  */
  fsl_cx * f;
  /**
     The current list of CLI arguments. This list gets modified by
     fcli_flag() and friends. Its memory is owned by fcli.
  */
  char ** argv;
  /**
     Current number of items in this->argv.
  */
  int argc;
  /**
     Application's name. Currently argv[0] but needs to be adjusted
     for Windows platforms. Gets set by fcli_setup_v2() and may
     optionally be set by the client before calling that.
  */
  char const * appName;
  /**
     The flags in this struct are "public," meaning that client
     applications may query and safely manipulate them directly if
     they know what they're doing.

     However, some of this state is only be legally modified
     _before_ calling fcli_setup() (or equivalent).
  */
  struct {
    /**
       If not NULL, it must be a pointer to fcli_help_info holding help
       info for the app.  It will be formated and output when --help
       is triggered.

       Should be set by client applications BEFORE calling fcli_setup()
       so that the ::fcli help subsystem can integrate the
       app. fcli.appName will be set by the time this is used.
    */
    fcli_help_info const * appHelp;

    /**
       May be set to an array of CLI flag objects, which fcli_setup()
       will use for parsing the CLI flags. The array MUST end with an
       entry which has NULL values for its (flagShort, flagLong)
       members. When creating the array it is simplest to use
       fcli_cliflag_empty_m as the initializer for that sentinel entry.

       The elements in this array are traversed in the order they are
       provided, and any which have a callback which returns
       FCLI_RC_FLAG_AGAIN will be traversed repeatedly before moving on
       to the next flag. This ordering may have side-effects on how the
       app sets up its flag handling. In particular, this arrangement
       makes the common cases easy to implement but makes certain more
       complicated situations effectively impossible to implement. For
       example:

       ```
       -x=1 -y=2 -x=3 -y=4
       ```

       Assuming the definition of the -y flag is first in this array and
       has a callback which returns FCLI_RC_FLAG_AGAIN, the two -x flags
       will be processed before either of the -y flags. Thus it is
       impossible (using this method of traversal) to change the
       behavior of the -y flags based on the left-closest -x value.

       We "could," but probably never will, instead walk the input argv
       looking for things which look like flags, then looking back into
       this list for a match, rather than the other way around. That
       would require a new args processing implementation, though, for
       relatively little benefit.
    */
    const fcli_cliflag * cliFlags;

    /**
       If not NULL then fcli_setup() will attempt to open the
       checkout for the given dir, including its associated repo
       db. By default this is "." (the current directory).

       Applications can set this to NULL _before_ calling
       fcli_setup() in order to disable the automatic attemp to
       open a checkout under the current directory.  Doing so is
       equivalent to using the --no-checkout flag. The global
       --checkout-dir flag will trump that setting, though.
    */
    char const * checkoutDir;

    /**
       A verbosity level counter. Starts at 0 (no verbosity) and goes
       up for higher verbosity levels. Currently levels 1 and 2 are
       intended for app-level use and level 3 for library-level use.
    */
    unsigned short verbose;

    /**
       Whether or not to enable fossil's SQL tracing.  This should
       start with a negative value, which helps fcli_setup() process
       it. Setting this after initialization has no effect.
    */
    int traceSql;
    /**
       This output channel is used when initializing the context
       object. The default implementation uses fsl_outputer_FILE to
       output to stdout.
    */
    fsl_outputer outputer;

    /**
       Listener for fsl_msg-published messages. The default listener
       sends all of its output via this->outputer.
    */
    fsl_msg_listener listener;
  } config;

  /**
     Transient settings and flags set in response to global/shared CLI
     flags. These are bits which are used during (or very shortly
     after) fcli_setup() but generally have no effect if modified
     after that (and should not be modified, in any case).

     TODO (2026-07-30): move this into static state in cli.c.

     TOOD (2026-10-16): see previous TODO.
  */
  struct {
    /**
       repo db name string from -R/--repo CLI flag.
    */
    const char * repoDbArg;
    /**
       User name from the --user CLI flag.
    */
    const char * userArg;
    /**
       Incremented if fcli_setup() detects -? or --help in the
       argument list, or if the first non-flag argument is "help".
       This is an int, rather than a bool, to support multiple levels
       of help verbosity via multiple --help flags.
    */
    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;

    /**
       If true then fcli_sync() will emit verbose sync metrics. If it's
       false, it won't.

       CLI flag: -SM|--sync-metrics sets this to the opposite of
       whatever the build-time default is. i.e. it turns it off if
       it's on by default and on if it's off by default.
    */
    bool reportSyncMetrics;

    /**
       If true then fcli will dump various cache metrics

       CLI flag: -CU|--cache-metrics.
    */
    bool reportCacheMetrics;

    /**
       If true (the default) then fcli installs the
       fcli.config.listener in its fsl_cx instance, which means that
       it will provide progress of, e.g., clone or rebuild via its
       output channel. If false then it does not do so.

       CLI flag: --no-lib-events
    */
    bool libEvents;
  } globalFlags;
  /**
     For holding pre-this->f-init error state. Once this->f is
     initialized, all errors reported via fcli_err_set() are stored in
     that object's error state.
  */
  fsl_error err;
};
typedef struct fcli_t fcli_t;

/** @var fcli

    This fcli_t instance is intended to act as a singleton.  It holds
    all fcli-related global state.  It gets initialized with
    default/empty state at app startup and gets fully initialized via
    fcli_setup(). See that routine for an example of how it is
    typically initialized.

    fcli_cx() returns the API's fsl_cx instance. It will be non-NULL
    (but might not have an opened checkout/repository) if fsl_setup()
    succeeds.
*/
FSL_EXPORT fcli_t fcli;

/**
   Initializes fcli's state and CLI flags processing.

   MUST BE CALLED BEFORE fsl_malloc() and friends are used, as this
   swaps out the allocator with one which aborts on OOM. (But see
   fcli_pre_setup() for a workaround for that.)

   Should be called early on in main(), passed the arguments passed to
   main(). Returns 0 on success. This sets up the ::fcli instance and
   opens any checkout found in/above the current dir by default. To
   disable the automatic search for a checkout, assign
   `fcli.config.checkoutDir` to `NULL` before calling this.

   If the 3rd argument is not NULL, this sets `fcli.config.cliFlags` to its
   value. If the 4th argument is not NULL, this sets `fcli.config.appHelp` to
   that value.

   If argument processing finds either of the (`--help`, `-?`) flags,
   or the first non-flag argument is "help", it calls fcli_help(), and
   returns FCLI_RC_HELP, in which case the application should
   exit/return from main with code 0 immediately (see example
   below). It behaves similar when it finds the `--lib-version` flag.

   This function behaves significantly differently if its 3rd argument
   is not NULL or if fcli.config.cliFlags has been set before it is
   called. In that case, it parses the CLI flags using that type's
   rules and sets up fcli_help() to use those flags for generating the
   help. It parses the global flags first, then the app-specific flags
   (this means that global flags will be consumed from the argv array
   before app-specific flags with the same names).

   Returns 0 on success. Results other than FCLI_RC_HELP should be
   treated as fatal to the app, and fcli.f's error state _might_
   contain info about the error. If this function returns non-0, the
   convention is that the app immediately returns the result of
   fcli_end_of_main(THE_RESULT_CODE) from main(). That function will
   treat FCLI_RC_HELP as a non-error and will report any error state
   pending in the fcli_cx() object.

   Example of intended basic usage:

   ```
   int main(int argc, char const * const * argv){
     ...
     // Optional fcli_cliflag setup:
     fcli_cliflag const cliFlags[] = {
       ...,
       fcli_cliflag_empty_m // empty trailing entry required
     };
     // Optional fcli_help_info setup:
     fcli_help_info const help = {
       "Fnoobs the borts and rustles the feathers.",
       "file1 [... fileN]",
       NULL // optional callback to display extra help
     };
     // Initialize...
     int rc = fcli_setup_v2(argc, argv, cliFlags, &help);
     if(rc) goto end; // might be from --help

     ... app logic ...

     end:
     return fcli_end_of_main(rc);
   }
   ```

   @see fcli_pre_setup()
   @see fcli_setup()
   @see fcli_end_of_main()
*/
FSL_EXPORT int fcli_setup_v2(int argc, char const * const * argv,
                             fcli_cliflag const * const cliFlags,
                             fcli_help_info const * const helpInfo );

/**
   The first time this is called, it swaps out libfossil's default
   allocator with a fail-fast one which abort()s on allocation
   error. This is normally called by fcli_setup(), but that also means
   that it's illegal to use fsl_malloc() and friends before calling
   that routine. If an application really needs to use fsl_malloc()
   before calling fcli_setup(), it must call this first in order to
   get the allocator initialization out of the way.

   Calls after the first are no-ops, but the check for that is not
   thread-safe. Neither is fcli, though, so that's okay.
*/
FSL_EXPORT void fcli_pre_setup(void);

/**
   Returns the libfossil context associated with the fcli API.
   This will be NULL until fcli_setup() is called.
*/
FSL_EXPORT fsl_cx * fcli_cx(void);

/**
   Works like printf() but sends its output to fsl_outputf() using
   the fcli.f fossil conext (if set) or fsl_fprintf() (to
   stdout).
*/
FSL_EXPORT void fcli_printf(char const * fmt, ...)
#if 0
/* Would be nice, but complains about our custom format options: */
  __attribute__ ((__format__ (__printf__, 1, 2)))
#endif
  ;

/**
   f_out() is a shorthand for fcli_printf().
*/
#define f_out fcli_printf

/**
   Returns the verbosity level set via CLI args. 0 is no verbosity,
   and one level is added each time the --verbose/-V CLI flag is
   encountered by fcli_setup().
*/
FSL_EXPORT unsigned short fcli_is_verbose(void);

/**
   Searches fcli.argv for the given flag (pass it without leading
   dashes). If found, this function returns true, else it returns
   false. If value is not NULL then the flag, if found, is assumed to
   have a value, otherwise the flag is assumed to be a boolean. A flag
   with a value may take either one of these forms:

   -flag=value
   -flag value

   *value gets assigned to a COPY OF the value part of the first form
   or a COPY OF the subsequent argument for the second form (copies
   are required in order to avoid trickier memory management
   here). That copy is owned by fcli and will be cleaned up at app
   exit. On success it removes the flag (and its value, if any) from
   fcli.argv.  Thus by removing all flags early on, the CLI arguments
   are left only with non-flag arguments to sift through.

   Flags may start with either one or two dashes - they are
   equivalent.

   This function may update the fcli error state. Specifically, if
   passed a non-NULL 2nd argument and the flag is found at the end of
   the argument list or the value immediately after the flag starts
   with '-' then the error state will be updated and false will be
   returned. Apps don't normally need to be quite that picky with
   their error checking after looking for a flag, but the state is
   there if needed. It may get reset by any future calls into the API,
   though. fcli_process_flags() does check this state and will fail if
   such an error is triggered.
*/
FSL_EXPORT bool fcli_flag(char const * opt, const char ** value);

/**
   Works like fcli_flag() but tries two argument forms, in order. It
   is intended to be passed short and long forms, but can be passed
   two aliases or similar. It accepts NULL for either form.

   ```
   const char * v = NULL;
   fcli_flag2("n", "limit", &v);
   if(v) { ... }
   ```
*/
FSL_EXPORT bool fcli_flag2(char const * opt1, char const * opt2,
                           const char ** value);

/**
   Works similarly to fcli_flag2(), but if no flag is found and
   value is not NULL then *value is assigned to the return value of
   fcli_next_arg(true). In that case:

   - The return value will specify whether or not fcli_next_arg()
   returned a value or not.

   - If it returns true then *value is owned by fcli and will be
   cleaned up at app exit.

   - If it returns false, *value is not modified.

   The opt2 parameter may be NULL, but op1 may not.
*/
FSL_EXPORT bool fcli_flag_or_arg(char const * opt1, char const * opt2,
                                 const char ** value);


/**
   Clears any error state in fcli.f.
*/
FSL_EXPORT void fcli_err_reset(void);

/**
   Sets fcli.f's error state, analog to fsl_cx_err_set().
   Returns the code argument on success, some other non-0 value on
   a more serious error (e.g. FSL_RC_OOM when formatting the
   string).
*/
FSL_EXPORT int fcli_err_set(int code, char const * fmt, ...);

/**
   Returns the internally-used fsl_error instance which is used for
   propagating errors.  The object is owned by ::fcli and MUST NOT
   be freed or otherwise abused by clients. It may, however, be
   passed to routines which take a fsl_error parameter to report
   errors (e.g. fsl_deck_output().

   Returns NULL if fcli_setup() has not yet been called or after
   fcli has been cleaned up (post-main()).

*/
FSL_EXPORT fsl_error * fcli_error(void);

/**
   If ::fcli has any error state, this outputs it and returns the
   error code, else returns 0. If clear is true the error state is
   cleared/reset, otherwise it is left in place. Returns 0 if
   ::fcli has not been initialized. The 2nd and 3rd arguments are
   assumed to be the __FILE__ and __LINE__ macro values of the call
   point. See fcli_err_report() for a convenience form of this
   function.

   If fcli_cx() has no error state but fsl_cx_db(fcli_cx()) does,
   then that error state is moved into the fsl_cx object and
   reported here.

   The format of the output depends partially on fcli_is_verbose(). In
   verbose mode, the file/line info is included, otherwise it is
   elided.

   @see fcli_err_report()
*/
FSL_EXPORT int fcli_err_report2(bool clear, char const * file, int line);

/**
   Convenience macro for using fcli_err_report2().
*/
#define fcli_err_report(CLEAR) fcli_err_report2((CLEAR), __FILE__, __LINE__)

/**
   Peeks at or takes the next argument from the CLI args. If the
   argument is true, it is removed from the args list. It is owned by
   fcli and will be freed when the app exits.

   Returns NULL if the args list is empty.
*/
FSL_EXPORT const char * fcli_next_arg(bool remove);

/**
   If fcli.argv contains what looks like any flag arguments, this
   updates the fossil error state and returns FSL_RC_MISUSE, else
   returns 0. A "-" by itself is not considered to be a flag, as it
   conventionally names stdin or stdout. If outputError is true and an
   unused flag is found then
   the error state is immediately output (but not cleared).  If
   outputError is false then the next call to fcli_err_report2() will
   emit it the error, typically indirectly via fcli_end_of_main().
*/
FSL_EXPORT int fcli_has_unused_flags(bool outputError);
/**
   If fcli.argv contains any entries, returns FSL_RC_MISUSE and
   updates the error state with a message about unusued extra
   arguments, else returns 0. outputError is interpreted as for
   fcli_has_unused_flags().
*/
FSL_EXPORT int fcli_has_unused_args(bool outputError);

typedef struct fcli_command fcli_command;
/**
   Typedef for general-purpose fcli call-by-name commands.

   It gets passed its own command definition, primarily for each of
   access to the flags member for CLI flags processing.

   @see fcli_dispatch_commands()
*/
typedef int (*fcli_command_f)(fcli_command const *);

/**
   Describes a named callback command.

   @see fcli_dispatch_commands()
*/
struct fcli_command {
  /** The name of the command. */
  char const * name;
  /**
     NUL-delimited string containing optional aliases of the above command
     name. This string _must_ be double-NUL terminated (e.g., "alias\0\al\0").
  */
  char const * aliases;
  /** Brief description, for use in generating help text. */
  char const * briefDescription;
  /** The callback for this command. */
  fcli_command_f f;
  /** Optional usage callback for this command. */
  void (*usage)(void);
  /**
     Must be NULL or an array compatible with fcli_process_flags().
     Can be used from within this->f for command-specific flag
     dispatching, as well as help text generation.
  */
  fcli_cliflag const * flags;
};

/**
   Expects an array of fcli_commands which contain a trailing
   sentry entry with a NULL name and callback. It searches the list
   for a command matching fcli_next_arg(). If found, it
   removes that argument from the list, calls the callback, and
   returns its result. If no command is found FCLI_RC_NO_CMD is
   returned, the argument list is not modified, and the error state
   is updated with a description of the problem and a list of all
   command names in cmdList.

   The distinct FCLI return code aims to help clients distinguish
   between fcli_dispatch_commands() failure and failures propagated
   by successfully dispatched fcli_command fcli_command_f callbacks.

   If reportErrors is true then on error this function outputs
   the error result but it keeps the error state in place
   for the downstream use.

   As a special case: when a command matches the first argument and
   that object has a non-NULL flags member, this function checks the
   _next_ argument, and if it is "help" then this function passes
   that flags member to fcli_command_help() to output help, then
   returns 0.
*/
FSL_EXPORT int fcli_dispatch_commands( fcli_command const * cmdList,
                                       bool reportErrors);

/**
   Parse cmd->aliases for an alias (i.e., NUL-terminated string semantically
   equivalent to cmd->name) matching arg. Return 0 if a match is found, else 1.
   Note that cmd->aliases _must_ be double-NUL terminated.
*/
FSL_EXPORT int fcli_cmd_aliascmp( fcli_command const * cmd, char const * arg );

/**
   A minor helper function intended to be passed the pending result
   code of the main() routine. This function outputs any pending
   error state in fcli. Returns one of EXIT_SUCCESS if mainRc is 0
   and fcli had no pending error report, otherwise it returns
   EXIT_FAILURE. This function does not clean up fcli - that is
   handled via an atexit() handler.

   It is intended to be called once at the very end of main:

   ```
   int main(){
   int rc;

   ...set up fcli...assign rc...

   return fcli_end_of_main(rc);
   }
   ```

   As a special case, if mainRc is FCLI_RC_HELP, it is assumed to
   be the result of the fcli --help flag handling, and is treated as
   if it were 0.

   If mainRc is non-0 but fcli has no error state, the report names
   mainRc and lists any arguments the app left unconsumed (see
   fcli_next_arg()), since an unconsumed argument often shows which
   argument the app misread.

   @see fcli_error()
   @see fcli_err_set()
   @see fcli_err_report()
   @see fcli_err_reset()
*/
FSL_EXPORT int fcli_end_of_main(int mainRc);

/**
   If mem is not NULL, this routine appends mem to a list of pointers
   which will be passed to fsl_free() during the atexit() shutdown
   phase of the app. Because fcli uses a fail-fast allocator, failure
   to append the entry will itself cause a crash. This is only useful
   for values for which fsl_free() suffices to clean them up, not
   complex values like multi-dimensional arrays.

   "fax" is short for "free at exit."

   Results are undefined if the same address or overlapping addresses
   are queued more than once. Once an entry is in this queue, there is
   no way to remove it.

   Returns its argument so that it can be used like:

   ```
   char * x = fcli_fax( fsl_strdup("...") );
   ```
*/
FSL_EXPORT void * fcli_fax(void * mem);

/**
   Requires an array of fcli_cliflag objects terminated with an
   instance with NULL values for the (flagShort, flagLong) members
   (fcli_cliflag_empty_m is an easy way to get that).

   If fcli.config.cliFlags is set before fcli_setup() is called, this routine
   is called and passed those flags. Thus most apps can simply assign
   their flags there and let setup() do the work. Apps which have
   multiple dispatch paths, each with differing flags, may find it
   easier to use this.

   As a special case, if a given entry has NULL values for both of its
   (flagValue, callback) members, it is assumed to exist purely for
   use with the help-generating mechanisms and the flag is NOT
   processed or consumed by fcli_process_flags(). That can be used
   when the client needs to process the flag in ways beyond what is
   capable via this routine. In such cases, add an appropriate entry
   to the fcli_cliflag array for --help purposes and then process the
   flag using fcli_flag() (or similar) either before or after calling
   this.

   Returns 0 on success. On error it sets the fcli error state
   (fcli_error()) and returns non-0:

   - FSL_RC_MISUSE if a flag which requires a value has none.

   - FSL_RC_RANGE if a numeric flag's value is not a valid number
     of that flag's type.

   - FSL_RC_MISUSE if an entry has an unknown flagType.

   - The result of a callback() member which returns a value other
     than 0 or FCLI_RC_FLAG_AGAIN. The callback is responsible for
     setting the error message.
*/
FSL_EXPORT int fcli_process_flags( fcli_cliflag const * defs );

/**
   Requires an array of fcli_cliflag objects as described for
   fcli_process_flags(). This routine outputs their flags
   and help text in a framework-conventional manner.

   If fcli.config.cliFlags is set before fcli_setup() is called, this
   routine is called and passed those flags. Thus most apps can simply
   assign their flags there and let fcli_setup() do the work. Apps
   which have multiple dispatch paths, each with differing flags, may
   find it easier to use this.

   Such apps, in order to get the full help listing for all dispatch
   paths, may need to assign fcli.config.appHelp to a helper which
   dispatches to an app-local help routine which, in turn, passes each
   of their separate fcli_cliflag lists to this routine.
*/
FSL_EXPORT void fcli_cliflag_help(fcli_cliflag const *defs);

/**
   Requires that cmd be an array of fcli_command objects with a
   trailing entry which has a NULL name. This function iterates over
   them and outputs help text based on each one's (name,
   briefDescription, flags) members.

   If the 2nd argument is true AND the cmd->usage() callback has been
   set, it will be called for each object in the cmd array after
   outputting the cmd->flags help text.

   If the 3rd argument is true, only the help for the single given
   object is output, not any adjacent array members (if any).
*/
FSL_EXPORT void fcli_command_help(fcli_command const * cmd, bool showUsage, bool onlyOne);

/**
   Pretty print fcli_command->aliases like: " (aliases: cmd, com)".
*/
FSL_EXPORT void fcli_help_show_aliases(char const * aliases);

/**
   If fcli has a checkout opened, this dumps various info about it
   to its output channel. Returns 0 on success, FSL_RC_NOT_A_CKOUT
   if no checkout is opened, or some other non-0 code on error.

   If the useUtc argument is true, it uses UTC timestamps, else
   localtime. (Potential TODO: add an fcli-level CLI flag for that
   instead?)
*/
FSL_EXPORT int fcli_ckout_show_info(bool useUtc);

/**
   Given a hash prefix, lists (via f_out()) all blob table entries
   which have this prefix. This is intended to be used by apps which
   accept a from a user and fsl_sym_to_rid() returns FSL_RC_AMBIGUOUS.

   The first argument is an optional output label/header to output.
   If it is NULL, a default is used. If it is "" then no header is
   output.
*/
FSL_EXPORT void fcli_list_ambiguous_artifacts(char const * label, char const *prefix);

/**
   If fcli has an opened checkout, that db handle is returned, else NULL
   is returned.
*/
FSL_EXPORT fsl_db * fcli_db_ckout(void);

/**
   If fcli has an opened repository, that db handle is returned, else
   NULL is returned.
*/
FSL_EXPORT fsl_db * fcli_db_repo(void);

/**
   If fcli has an opened checkout, that db handle is returned, else NULL
   is returned and fcli's error state is updated with a description
   of the problem.
*/
FSL_EXPORT fsl_db * fcli_needs_ckout(void);

/**
   If fcli has an opened repository, that db handle is returned, else NULL
   is returned and fcli's error state is updated with a description
   of the problem.
*/
FSL_EXPORT fsl_db * fcli_needs_repo(void);

/**
   Processes all remaining CLI arguments as potential file or directory
   names, collects their vfile.id values, and stores them in the given
   target bag. It requires an opened checkout.

   vid is the vfile.vid value to filter on. If vid<=0 then the current
   checkout version is used. (Unless the app has explicitly loaded
   another version, that will be the only option available.)

   If relativeToCwd is true then each argument is resolved as if
   referenced from the current working directory, else each is assumed
   to be relative to the top of the checkout directory. (For CLI apps,
   a value of true is almost always the right choice.)

   If changedFilesOnly is true then only files which are "changed",
   according to the vfile table (as opposed to a filesystem check) are
   considered for addition. For that to work, vfile must be up to
   date, so fsl_vfile_changes_scan() must have been recently called to
   update that state. This function does not call it automatically
   because it's relatively slow and many apps already have to call it
   on their own.

   This function matches only vfile.pathname, not vfile.origname,
   because it is possible for a given name to be in both fields (in
   different records) at the same time.

   Returns 0 on success. If there are no more CLI arguments when it is
   called then it returns FSL_RC_MISUSE and updates the fcli error
   state with a description of the problem. It may return any number
   of non-0 codes from the underlying operations.

   Sidebar: fsl_filename_to_vfile_ids() requires that directory names
   passed to it have no trailing slashes, and this routine strips
   trailing slashes from its arguments before passing them on to that
   routine, so they may be entered with slashes without ill effect.

   @see fsl_filename_to_vfile_ids()
*/
FSL_EXPORT int fcli_args_to_vfile_ids(fsl_id_bag * const tgt,
                                      fsl_id_t vid,
                                      bool relativeToCwd,
                                      bool changedFilesOnly);

/**
   Performs a "fingerprint check" on the current checkout/repo
   combination, as per fsl_ckout_fingerprint_check(). If the check
   fails and reportImmediately is true then an error report is
   immediately output. Returns 0 if the fingerprint check is okay,
   else a non-0 value as per fsl_ckout_fingerprint_check().

   Passing true here may output more information than the underlying
   fsl_cx-level error state provides. e.g. it may provide a hint about
   how to recover.
*/
FSL_EXPORT int fcli_fingerprint_check(bool reportImmediately);

/**
   Returns the "tail" part of the argv[0] string which was passed to
   fcli_setup(), 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(void);

/**
   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_dibu_opt::ansiColors state with values
   dependend on the second argument.
*/
FSL_EXPORT void fcli_diff_colors(fsl_dibu_opt * const tgt,
                                 fcli_diff_colors_e theme);

/**
   Uses the library's sync API to run a sync operation, optionally
   either or both of push and pull operations. 

   Its argument may be a mask of any values from the fsl_sync_flags_e
   enum.

   Returns 0 if it does not sync.  Returns FSL_RC_NOT_A_REPO if no
   repo is opened. If the repo is opened but has no "syncwith:"
   entries in its config table, no sync is attempted and 0 is
   returned.

   If fossil cannot be found, returns FSL_RC_NOT_FOUND, else returns
   as documented for fsl_system().

   TODO (2026-09-30): consolidate fcli_sync_e with lib-level code
   (where is TBD).
*/
FSL_EXPORT int fcli_sync( int ops );


/** @internal

   This function is intented for use in development of libfossil. It
   dumps the current state of cached SQL statements to fcli_printf().

   Normally its output detail level is determined by
   fcli_is_verbose(), but if forceVerbose is true then it cranks the
   detail all the way up.
 */
FSL_EXPORT void fcli_dump_stmt_cache(bool forceVerbose);

/** @internal

    This pseudo-internal function causes fcli to dump any
    library-level caching metrics it knows about. This function exists
    primarily to keep fcli client code from having to access the
    related internal members directly. This is a no-op if fcli has
    not been initialized.
*/
FSL_EXPORT void fcli_dump_cache_metrics(void);

/**
   A fsl_msg_f() implementation intended for use with CLI apps.  It
   emits all output via fcli_printf(). This is the default message
   listener. Clients may replace the default by setting up
   fcli.config.listener before calling fcli_setup_v2(), and simple
   client apps may use this for other fsl_cx instances. This
   implementation ignores its state argument.
*/
FSL_EXPORT int fsl_msg_f_fcli(fsl_msg const *msg, void *state);

#if defined(__cplusplus)
} /*extern "C"*/
#endif

#endif
/* _ORG_FOSSIL_SCM_FCLI_H_INCLUDED_ */
/* end of file include/fossil-scm/cli.h */
/* start of file include/fossil-scm/deprecated.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(FSL_OMIT_DEPRECATED)
#if !defined(ORG_FOSSIL_SCM_LIBFOSSIL_DEPRECATED_H_INCLUDED)
#define ORG_FOSSIL_SCM_LIBFOSSIL_DEPRECATED_H_INCLUDED
/*
  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-FileType: Code

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

/** @file deprecated.h

  This file holds APIs which are deprecated or otherwise "on the chopping
  block." The libfossil public API has gathered a good deal of cruft
  over the years.
*/

/**
   @deprecated fsl_db_role_name() is easier to deal with.

   Similar to fsl_cx_db_file_ckout() and friends except that it
   applies to DB name (as opposed to DB _file_ name) implied by the
   specified role (2nd parameter). If no such role is opened, or the
   role is invalid, NULL is returned.

   If the 3rd argument is not NULL, it is set to the length, in bytes,
   of the returned string. The returned strings are NUL-terminated and
   are either static or owned by the db handle they correspond to.

   If the client does not care whether the db in question is
   actually opened, the name for the corresponding role can be
   fetched via fsl_db_role_name().

   This is the "easiest" way to figure out the DB name of the given
   role, independent of what order f's databases were opened
   (because the first-opened DB is always called "main").

   The Fossil-standard names of its primary databases are: "localdb"
   (checkout), "repository", and "configdb" (global config DB), but
   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, and which one is the
   "main" db is dependent on the order the DBs are opened, 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.
*/
char const * fsl_cx_db_name_for_role(fsl_cx const * const f,
                                     fsl_dbrole_e r,
                                     fsl_size_t * len);

/**
   Equivalent to `fcli_setup_v2(argc,argv,fcli.cliFlags,fcli.appHelp)`.

   @see fcli_pre_setup()
   @see fcli_setup_v2()
   @see fcli_end_of_main()
   @deprecated Its signature will change to fcli_setup_v2()'s at some point.
*/
int fcli_setup(int argc, char const * const * argv );

/** @deprecated fsl_close_scm_dbs()

   As of 2021-01-01, this functions identically to
   fsl_close_scm_dbs(). Prior to that...

   If fsl_repo_open_xxx() has been used to open a respository db,
   perhaps indirectly via opening of a checkout, this call closes that
   db and any corresponding checkout db.

   Returns 0 on success or if no repo/checkout db is opened. It may
   propagate an error from the db layer if closing/detaching the db
   fails.

   @see fsl_repo_open()
   @see fsl_repo_create()
*/
int fsl_repo_close( fsl_cx * const f );


/** @deprecated use fsl_close_scm_dbs() instead

   As of 2021-01-01, this functions identically to
   fsl_close_scm_dbs(). Prior to that...

   If fsl_ckout_open_dir() (or similar) has been used to open a
   checkout db, this call closes that db, as well as any
   corresponding repository db.

   Returns 0 on success or if no checkout db is opened. It may
   propagate an error from the db layer if closing/detaching the db
   fails. Returns FSL_RC_MISUSE if f has any transactions pending.

   This also closes the repository which was implicitly opened for the
   checkout.
*/
int fsl_ckout_close( fsl_cx * const f );

#endif /* ORG_FOSSIL_SCM_LIBFOSSIL_DEPRECATED_H_INCLUDED */
#endif /* FSL_OMIT_DEPRECATED */
/* end of file include/fossil-scm/deprecated.h */
#if defined(FSL_EXPOSE_INTERNAL_APIS)
/* FSL_EXPOSE_INTERNAL_APIS is a compatibility crutch for fnc! */
/* Do not use FSL_EXPOSE_INTERNAL_APIS unless you know you need it! */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_INTERNAL_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_INTERNAL_H_INCLUDED
/*
  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-FileType: Code

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

  *****************************************************************************
  This file declares library-level internal APIs which are shared
  across the library.
*/


#if defined(_WIN32) && !defined(WIN32_LEAN_AND_MEAN)
/* Keep <windows.h> from including the old <winsock.h>, which
   conflicts with the <winsock2.h> the native sync channel uses. */
#  define WIN32_LEAN_AND_MEAN
#endif

/**
   Determine whether fsl__mutex_enter() and friends are no-ops.  If
   we'd require C11 then we could use C11's mutexes instead of
   sqlite3's, but we have those handy so we might as well use them.
*/
#if !defined(FSL_ENABLE_MUTEX)
#  if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
#    define FSL_ENABLE_MUTEX 1
#  else
#    define FSL_ENABLE_MUTEX 0
#  endif
#endif

/**
   A few places lock SQLite's own mutexes even when FSL_ENABLE_MUTEX
   is 0. A SQLite built with SQLITE_THREADSAFE=0 (e.g. its wasm
   builds) omits sqlite3_mutex_xxx() altogether, so in that build
   these are no-ops. fsl__sq3_mutex_alloc() then returns a non-NULL
   dummy because fsl__libinit() treats a NULL result as OOM.
*/
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
#  define fsl__sq3_mutex_alloc(ID) ((sqlite3_mutex*)8)
#  define fsl__sq3_mutex_enter(M) (void)(M)
#  define fsl__sq3_mutex_leave(M) (void)(M)
#else
#  define fsl__sq3_mutex_alloc(ID) sqlite3_mutex_alloc(ID)
#  define fsl__sq3_mutex_enter(M) sqlite3_mutex_enter(M)
#  define fsl__sq3_mutex_leave(M) sqlite3_mutex_leave(M)
#endif

#if defined(__cplusplus)
extern "C" {
#endif

typedef struct fsl__bccache fsl__bccache;
typedef struct fsl__bccache_line fsl__bccache_line;
typedef struct fsl__pq fsl__pq;
typedef struct fsl__pq_entry fsl__pq_entry;

/** @internal

    Queue entry type for the fsl__pq class.

    Potential TODO: we don't currently use the (data) member. We can
    probably remove it.
*/
struct fsl__pq_entry {
  /** RID of the entry. */
  fsl_id_t id;
  /** Raw data associated with this entry. */
  void * data;
  /** Priority of this element. */
  double priority;
};
/** @internal
    Empty-initialized fsl__pq_entry structure.
*/
#define fsl__pq_entry_empty_m {0,NULL,0.0}

/** @internal

    A simple priority queue class. Instances _must_ be initialized
    by copying fsl__pq_empty or fsl__pq_empty_m (depending on where
    the instance lives).
*/
struct fsl__pq {
  /** Number of items allocated in this->list. */
  fsl_size_t capacity;
  /** Number of items used in this->list. */
  fsl_size_t used;
  /** The queue. It is kept sorted by entry->priority. */
  fsl__pq_entry * list;
};

/** @internal
    Empty-initialized fsl__pq struct, intended for const-copy initialization.
*/
#define fsl__pq_empty_m {0,0,NULL}

/** @internal
    Empty-initialized fsl__pq struct, intended for copy initialization.
*/
extern  const fsl__pq fsl__pq_empty;

/** @internal

    Clears the contents of p, freeing any memory it owns, but not
    freeing p. Results are undefined if !p.
*/
void fsl__pq_clear(fsl__pq * p);

/** @internal

    Insert element e into the queue. Returns 0 on success, FSL_RC_OOM
    on error. Results are undefined if !p. pData may be NULL.
*/
int fsl__pq_insert(fsl__pq *p, fsl_id_t e,
                  double v, void *pData);

/** @internal

    Extracts (removes) the first element from the queue (the element
    with the smallest value) and return its ID.  Return 0 if the queue
    is empty. If pp is not NULL then *pp is (on success) assigned to
    opaquedata pointer mapped to the entry.
*/
fsl_id_t fsl__pq_extract(fsl__pq *p, void **pp);

/** @internal

    Holds one "line" of a fsl__bccache cache.
*/
struct fsl__bccache_line {
  /**
     RID of the cached record.
  */
  fsl_id_t rid;
  /**
     Age. Newer is larger.
  */
  fsl_uint_t age;
  /**
     Content of the artifact.
  */
  fsl_b content;
};
/** @internal

    Empty-initialized fsl__bccache_line structure.
*/
#define fsl__bccache_line_empty_m { 0,0,fsl_b_empty_m }


/** @internal

    A cache for tracking the existence of blobs while the internal
    goings-on of fsl_content_get() and friends are going on.

    "bc" ==> blob cache.

    Historically fossil caches artifacts as their blob content, but
    libfossil will likely (at some point) to instead cache fsl_deck
    instances, which contain all of the same data in pre-parsed form.
    It cost more memory, though. That approach also precludes caching
    non-structural artifacts (i.e. opaque client blobs).

    Potential TODO: the limits of the cache size are currently
    hard-coded and changing them "by hand" won't have much effect.
    We should possibly have an API to tweak these limits.
*/
struct fsl__bccache {
  /**
     Total amount of buffer memory (in bytes) used by cached content.
     This does not account for memory held by this->list.
  */
  unsigned szTotal;
  /**
     Limit on the (approx.) amount of memory (in bytes) which can be
     taken up by the cached buffers at one time. Fossil's historical
     value is 50M.
  */
  unsigned szLimit;
  /**
     Number of entries "used" in this->list.
  */
  uint16_t used;
  /**
     Approximate upper limit on the number of entries in this->list.
     This limit may be violated slightly.

     This list gets searched linearly so this number should ideally be
     relatively small: 3 digits or less. Fossil's historical value is
     500.
  */
  uint16_t usedLimit;
  /**
     Number of allocated slots in this->list.
  */
  uint16_t capacity;
  /**
     Next cache counter age. Higher is newer.
  */
  fsl_uint_t nextAge;

  /**
     Gets incremented on each insert for purposes of invalidating
     this cache. See the notes for fsl__ptl::changeMarker. It's okay
     if this overflows.
  */
  unsigned changeMarker;

  /**
     List of cached content, ordered by age.
  */
  fsl__bccache_line * list;
  /**
     RIDs of all artifacts currently in the this->list
     cache.
  */
  fsl_id_bag inCache;

  /**
     Metrics solely for internal use in looking for
     optimizations. These are only updated by fsl_content_get().
  */
  struct {
    unsigned hits;
    unsigned misses;
  } metrics;
};
/** @internal

    Empty-initialized fsl__bccache structure, intended
    for const-copy initialization.
*/
#define fsl__bccache_empty_m {     \
  .szTotal = 0U,                   \
  .szLimit = 100000000U/*was 20M; sync/dephantomize needs a deeper working set*/, \
  .used = 0U, .usedLimit = 5000U/*was 400; delta chains can be long*/,\
  .capacity = 0,                   \
  .nextAge = 0,                    \
  .changeMarker = 0,               \
  .list = NULL,                    \
  .inCache = fsl_id_bag_empty_m,   \
  .metrics = {.hits = 0U, .misses = 0U}  \
}

/** @internal

   The "PRAGMA cache_size" value which a fsl_cx applies to each
   database it opens or attaches. As for the pragma, a negative value
   is in KiB and a positive value is in pages.
*/
#ifndef FSL__DB_CACHE_SIZE
#  define FSL__DB_CACHE_SIZE -32000
#endif

/**
   Milliseconds a connection libfossil opens waits for another
   connection's write lock before reporting SQLITE_BUSY. fossil(1)
   uses the same value in its db_open().
*/
#ifndef FSL__DB_BUSY_TIMEOUT_MS
#  define FSL__DB_BUSY_TIMEOUT_MS 15000
#endif
#if FSL__DB_CACHE_SIZE < -2000000 || FSL__DB_CACHE_SIZE > 500000
#  error "FSL__DB_CACHE_SIZE is outside -2000000 (about 2 GB) to 500000 pages"
#endif

/** @internal

   Very internal.

   "Manifest cache" for fsl_deck entries encountered during
   crosslinking. This type is intended only to be embedded in fsl_cx.

   The routines for managing this cache are static in deck.c:
   fsl__cx_mcache_insert() and fsl__cx_mcache_search().

   The array members in this struct MUST have the same length
   or results are undefined.
*/
struct fsl__mcache {
  /** Next age value. No clue how the cache will react once this
      overflows. */
  fsl_uint_t nextAge;
  /** Counts the number of cache hits. */
  unsigned hits;
  /** Counts the number of cache misses. */
  unsigned misses;
  /** The virtual age of each deck in the cache. They get evicted
      oldest first. */
  fsl_uint_t aAge[4];
  /**
     Stores bitwise copies of decks. Storing a fsl_deck_malloc() deck
     into the cache requires bitwise-copying is contents, wiping out
     its contents via assignment from fsl_deck_empty, then
     fsl_free()'ing it (as opposed to fsl_deck_finalize(), which would
     attempt to clean up memory which now belongs to the cache's
     copy).

     Array sizes of 6 and 10 do not appreciably change the hit rate
     compared to 4, at least not for current (2021-11-18) uses.
  */
  fsl_deck decks[4];
};

/** @internal
  Convenience typedef. */
typedef struct fsl__mcache fsl__mcache;

/** @internal
    Initialized-with-defaults fsl__mcache structure, intended for
    const-copy initialization. */
#define fsl__mcache_empty_m {                    \
    .nextAge=0, .hits=0, .misses=0,              \
    .aAge = {0,0,0,0},                           \
    .decks = {fsl_deck_empty_m,fsl_deck_empty_m, \
              fsl_deck_empty_m, fsl_deck_empty_m}\
}

/**@internal
  Initialized-with-defaults fsl__mcache structure, intended for
  non-const copy initialization. */
extern const fsl__mcache fsl__mcache_empty;

/**
   This will fail to compile if the arrays fsl__mcache::aAge and
   fsl__mcache::decks have different sizes. They must have the same
   size.
*/
typedef int fsl__mcache_StaticAssertArraySizes[
 ((sizeof(fsl__mcache_empty.aAge)
  /sizeof(fsl__mcache_empty.aAge[0]))
 == (sizeof(fsl__mcache_empty.decks)
     /sizeof(fsl__mcache_empty.decks[0])))
 ? 1 : -1
];

/**
   Expands to a list of the names of all fsl_id_bag members of the
   fsl__ptl_line struct by invoking macro E(NAME) once for each name.
*/
#define fsl__ptl_line_map(E)                        \
  E(toVerify/*RIDs of blobs added at this level*/)  \
  E(leafCheck/*Used during the processing of manifests to keep track
               of "leaf checks" which need to be done downstream.*/) \
  E(available/*RIDs of known-available content*/)   \
  E(missing/*RIDs of known-missing content*/) \
  E(dephantomize/*An experiment in queueing up dephantomization work*/)

/**
   A cache of fsl_cx state which applies per transaction level.  We
   need one of these per level in the transaction stack.
*/
struct fsl__ptl_line {
#define E(X) fsl_id_bag X;
  fsl__ptl_line_map(E)
#undef E
  /**
     A poor-man's approach to recognizing when to clear
     fsl_cx::cache::blobContent when a fsl__ptl stack level is popped.
     The problem is that fsl__bccache is global to a given fsl_cx
     instance but may hold RIDs which are invalidated when a
     transaction level pops. fsl__bccache is not structured such that
     removing individual entries by RID is easy or cheap, so we
     invalidate the whole cache if a given transaction level added
     anything to fsl_cx::cache::blobContent. When pushing a PTL level,
     we record fsl__bccache::changeMarker here and compare it when the
     transaction pops. If they differ, the blob content cache is
     cleared. An improvement to this would be to extend fsl__bccache
     to be able to remove entries by RID, but that's not on today's
     proverbial menu.
  */
  unsigned changeMarker;
};

typedef struct fsl__ptl_line fsl__ptl_line;

/**
   Enum entries corresponding to fsl__ptl_line members.
*/
enum fsl__ptl_e {
  /** Sentinel value needed in slot 0. */
  fsl__ptl_e_dummy = 0,
#define E(X) fsl__ptl_e_ ## X,
  fsl__ptl_line_map(E)
#undef E
};
typedef enum fsl__ptl_e fsl__ptl_e;

/**
   This object manages a stack of fsl__ptl_line objects for a
   fsl_cx.

   ptl = per transaction level
*/
struct fsl__ptl {
  /** Persistent error code. */
  int rc;
  /** Number of levels currently allocated. */
  uint16_t allocated;
  /** 0-based level. 0 is for work done without an explicit
      transaction on the stack. */
  uint16_t level;
  /**
     The transaction level in which the first RIDs (in this
     transaction stack) were added. This is used for determining when
     to run certain checks. A negative value means no RIDs have been
     added.
   */
  int validateRidLevel;
  /** Memory living in this->mem. */
  fsl__ptl_line * stack;
  /** Current line in this->stack. */
  fsl__ptl_line * line;
  /** Memory for this->stack. */
  fsl_b mem;
};

typedef struct fsl__ptl fsl__ptl;

/** Empty-initialized fsl__ptl struct. */
#define fsl__ptl_empty_m {               \
    .rc = 0, .allocated = 0, .level = 0, \
    .validateRidLevel = -1,              \
    .stack = NULL, .line = NULL,         \
    .mem = fsl_b_empty_m            \
  }


/**
   Generic array-of-T list memory-reservation routine.

   *list is the input array-of-T. nDesired is the number of entries to
   reserve (list entry count, not byte length). *nAlloc is the number
   of entries allocated in the list. sizeOfEntry is the sizeof(T) for
   each entry in *list. T may be either a value type or a pointer
   type and sizeofEntry must match, i.e. it must be sizeof(T*) for a
   list-of-pointers and sizeof(T) for a list-of-objects.

   If e is not NULL then this function updates e's error state on
   error, else it simply returns FSL_RC_OOM on error. If e is not
   NULL then this function is a no-op if called when e's error state
   is set, returning that code without other side-effects.

   If nDesired > *nAlloc then *list is reallocated to contain at least
   nDesired entries, else this function returns without side effects.
   If it allocates, it is free to allocate for more than nDesired
   entries.

   On success *list is re-assigned to the reallocated list memory, all
   newly-(re)allocated memory is zeroed out, and *nAlloc is updated to
   the new allocation size of *list (the number of list entries, not
   the number of bytes).

   On failure neither *list nor *nAlloc are modified.

   Returns 0 on success or FSL_RC_OOM on error.  Errors generated by
   this routine are, at least in principle, recoverable, not that the
   app can necessarily otherwise recover from an OOM.

   License note: this code and the fsl__b_list pieces it was
   added for were ported into libfossil by the same person who wrote
   the original it was ported from.
*/
int fsl__array_reserve(fsl_error *e, void **list, fsl_size_t nDesired,
                       fsl_size_t * nAlloc, unsigned sizeOfEntry);

#define fsl__cx_array_reserve(CX,LI,MIN) fsl__array_reserve(&(CX)->error, (LI), (MIN))

/**
   fsl__b_list sorting policies. NULL entries must
   always sort last.
*/
enum fsl__b_list_e {
  fsl__b_list_e_UNSORTED,
  /* Smallest buffers first. */
  fsl__b_list_e_ASC,
  /* Largest buffers first. */
  fsl__b_list_e_DESC
};

/**
   Declares struct T as a container for a list-of-MT.  MT may be
   pointer-qualified. fsl__ListType_impl() with the same arguments
   implements T_reserve() for basic list allocation. Cleanup, alas, is
   MT-dependent.
*/
#define fsl__ListType_decl(T,MT) \
  struct T {                     \
    MT * list;                   \
    fsl_size_t used;             \
    fsl_size_t capacity;         \
  };                             \
  typedef struct T T;            \
  int T ## _reserve(fsl_error *e, T *li, fsl_size_t min)

#define fsl__ListType_impl(T,MT)                                 \
  int T ## _reserve(fsl_error *e,struct T *li, fsl_size_t min) { \
    void * p = li->list;                                         \
    int const rc = fsl__array_reserve(e, &p, min,                \
                                      &li->capacity, sizeof(MT));\
    li->list = p;                                                \
    return rc;                                                   \
  }

#define fsl__ListType__reserve1_size(li,nInitial) \
  (li->used ? (li->used==li->capacity ? li->capacity * 2 : li->used+1) : nInitial)

#define fsl__LIST_T_empty_m {.list=0,.used=0,.capacity=0}

fsl__ListType_decl(fsl__b_list,fsl_b*);
#define fsl__b_list_empty_m fsl__LIST_T_empty_m
extern const fsl__b_list fsl__b_list_empty;
void fsl__b_list_cleanup(fsl__b_list *li);
//void fsl__b_list_reuse(fsl__b_list *li);

/**
   A collection of buffers for use with fsl_cx_b_borrow().
*/
struct fsl__b_library {
  fsl__b_list list;
  /**
     How/whether this->list is sorted.  This is a bit of a historical
     hanger-on from a time in this code's history when it made sense
     to sort buffers. We currently dole out buffers in FIFO order so
     do not really need this but return it in case we want to extend
     borrowing to provide a hint as to whether the caller wants a
     "small" buffer or a "large" one, in which case we would sort by
     size pull from the start resp. end of the list.
  */
  enum fsl__b_list_e sort;
  /**
     Max number of buffers to cache. 0 disables borrowing, always
     allocating. When this limit is reached, fsl_cx_b_borrow()
     will still hand out buffers but fsl_cx_b_return() will
     start freeing them immediately so long as it's over the
     limit.
  */
  uint32_t limitCount;
  /**
     Largest capacity of single buffer to keep.  If exceeded, we keep
     the fsl_b instance but toss its buffered memory. A value of
     0 disables this limit.
  */
  uint32_t limitSingleCapacity;
  /**
     Max total of fsl_b::capacity in the buffers.  0 means no
     limit.  Limit enforcement is as per this->limitSingleCapacity.
  */
  uint64_t limitCapacity;
  /**
     Current fsl_b::capacity in the buffers.
  */
  uint64_t currentCapacity;
  /** Running total of buffers borrowed. Incremented on each borrow. */
  uint64_t nBorrowed;
  /** Running total of buffers returned. Incremented on each borrow. */
  uint64_t nReturned;
  /** Running total of bytes borrowed. Incremented by b->capacity on
      each borrow. */
  int64_t nBytesBorrowed;
  /** Running total of bytes returned. Incremented by b->capacity on
      each return. */
  uint64_t nBytesReturned;
  /** Max number of buffers concurrently borrowed.
      Incremented on each borrow. */
  uint64_t peakBorrowed;
  /** Max concurrent capacity. Incremented on each return. */
  uint64_t peakCapacity;
};
typedef struct fsl__b_library fsl__b_library;
#define fsl__b_library_empty_m {     \
    .list=fsl__b_list_empty_m,       \
    .sort=fsl__b_list_e_UNSORTED,    \
    .limitCount=30,                       \
    .limitSingleCapacity=1024 * 1024 * 12,\
    .limitCapacity=1024 * 1024 * 32,      \
    .currentCapacity=0,                   \
    .nBorrowed=0, .nReturned=0,           \
    .nBytesBorrowed=0, .nBytesReturned=0, \
    .peakBorrowed=0, .peakCapacity=0      \
}

//fsl_b * fsl__b_borrow(fsl__b_list *li);
//void fsl__b_return(fsl__b_list *li, fsl_b *b);

/*
  The fsl_cx class is documented in the main public header. ALL of its
  members are to be considered private/internal.

  Reminder to self:

  i'd like to rename this to fsl__cx and have a public (typedef struct
  fsl__cx fsl_cx) like we do for fsl_xfer, but doing so breaks fnc,
  which uses (struct fsl_cx) in a few places and triggers an "is not a
  struct" error.
*/
struct fsl_cx {
  /**
     A pointer to the "main" db handle. Exactly which db IS the main
     db is, because we have three DBs, not generally knowable.

     The internal management of fsl_cx's db handles has changed
     a couple of times. As of 2022-01-01 the following applies:

     dbMain starts out NULL. When a repo or checkout is opened, dbMain
     is pointed at the first of those which is opened.  When its
     partner is opened, it is ATTACHed to dbMain.  dbMain->role holds
     a bitmask of fsl_dbrole_e values reflecting which roles are
     opened/attached to it.

     The db-specific separate handles (this->{repo,ckout}.db) are used
     to store the name and file path to each db. ONE of those will
     have a db->dbh value of non-NULL, and that one is the instance
     which dbMain points to.

     Whichever db is opened first gets its "main" schema aliased to
     the corresponding fsl_db_role_name() for is role so that SQL code
     need not care which db is "main" and which is "repo" or
     "ckout". (Sidebar: when this library was started, the ability to
     alias a db with another name did not exist, and thus we required
     a middle-man "main" db to which we ATTACHed the repo and checkout
     dbs. That led to locking problems.)

     As of 20211230, f->config.db is its own handle, not ATTACHed with
     the others. Its db gets aliased to
     fsl_db_role_name(FSL_DBROLE_CONFIG).

     Internal code should rely as little as possible on the actual
     arrangement of internal DB handles, and should use
     fsl_cx_db_repo(), fsl_cx_db_ckout(), and fsl_cx_db_config() to
     get a handle to the specific db they want. Whether or not they
     return the same handle or 3 different ones may change at some
     point, so the public API treats them as separate entities. That
     is especially important for the global config db, as that one
     is (for locking reason) almost certain to remain in its own
     db handle, independent of the repo/checkout dbs.

     In any case, the internals very much rely on the repo and
     checkout dbs being accessible via a single db handle because the
     checkout-related SQL requires both dbs for most queries. The
     internals are less picky about the genuine layout of those
     handles (e.g. which one, if either, is the MAIN db).
  */
  fsl_db * dbMain;

  /**
     Marker which tells us whether fsl_cx_finalize() needs
     to fsl_free() this instance or not.
  */
  void const * allocStamp;

  /**
     A bitwise copy of the config object passed to fsl_cx_init() (or
     some default).
  */
  fsl_cx_config cxConfig;

  struct {
    /**
       Holds info directly related to a checkout database.
    */
    struct {
      /** The db. */
      fsl_db db;
      /**
         The directory part of an opened checkout db. This is currently
         only set by fsl_ckout_open_dir(). It contains a trailing slash,
         largely because that simplifies porting fossil(1) code and
         appending filenames to this directory name to create absolute
         paths (a frequently-needed option).

         Useful for doing absolute-to-relative path conversions for
         checking file lists.
      */
      char * dir;
      /**
         Optimization: fsl_strlen() of dir. Guaranteed to be set to
         dir's length if dir is not NULL, else it will be 0.
      */
      fsl_size_t dirLen;
      /**
         The rid of the current checkout. May be 0 for an empty
         repo/checkout. Must be negative if not yet known.
      */
      fsl_id_t rid;
      /**
         The UUID of the current checkout. Only set if this->rid is
         positive. Owned by the containing fsl_cx object.
      */
      fsl_uuid_str uuid;
      /**
         Julian mtime of the checkout version, as reported by the
         [event] table.
      */
      double mtime;
    } ckout;

    /**
       Holds info directly related to a repo database.
    */
    struct {
      /** The db. */
      fsl_db db;
      /**
         The default user name, for operations which need one.
         See fsl_cx_user_set().
      */
      char * user;

      /** The 'main-branch' repo config setting, defaulting to trunk. */
      char * mainBranch;
    } repo;

    /**
       Holds info directly related to a global config database.
    */
    struct {
      /**
         The global config db. This handle is managed separately from
         the repo/ckout handles because this db is shared by all
         fossil instances are we have to ensure that we don't lock it
         for longer than necessary, thus this db may get opened and
         closed multiple times within even within a short-lived
         application.
      */
      fsl_db db;
    } gconfig;

    /**
       State for a context bound to a host's db handle with
       fsl_cx_host_db().
    */
    struct {
      /** The host's handle, or NULL. Owned by the host. */
      fsl_db_t * dbh;
      /**
         True once fsl_cx_host_db_closing() has been called. The handle
         may then no longer run SQL.
      */
      bool closing;
      /**
         If true, attaching skips fsl__cx_host_shadow_check(). For
         f-sanity's decoy tests only, which attach a repository ahead
         of the context's on purpose, to show that libfossil's SQL
         never reaches it.
      */
      bool noShadowCheck;
      /**
         The value libfossil last wrote to f's row of TEMP.fsl_host_gen
         (one row per context on the connection, keyed by its id). If
         the row holds anything else, the host rolled back work that
         f's caches remember. See fsl__cx_host_rollback_check().
      */
      int64_t gen;
    } host;

    int peakTxnLevel;
    fsl_size_t nBegin;
    fsl_size_t nCommit;
    fsl_size_t nRollback;
  } db;

  /**
     State for incrementally preparing a checkin operation.
  */
  struct {
    /**
       Holds a list of "selected files" in the form
       of vfile.id values.
    */
    fsl_id_bag selectedIds;

    /**
       The deck used for incrementally building certain parts of a
       checkin.
    */
    fsl_deck mf;
  } ckin;

  /**
     Confirmation callback. Used by routines which may have to
     interactively ask a user to confirm things.
  */
  fsl_confirmer confirmer;

  /**
     Artifact signing callback. See fsl_cx_signer() and
     fsl_deck_save().
  */
  fsl_signer signer;

  /**
     Storage for the checkout's files. iVersion==0 means
     fsl_ckout_fs_os, the filesystem. See fsl_cx_ckout_fs() and the
     fsl__cfs_xxx() functions, through which the checkout code reaches
     it.
  */
  fsl_ckout_fs ckoutFs;

  /**
     Output channel used by fsl_output() and friends.

     This was added primarily so that fossil client apps can share a
     single output channel which the user can swap out, e.g. to direct
     all output to a UI widget or a file.

     Though the library has adamantly avoided adding a "warning"
     output channel, features like:

     https://fossil-scm.org/home/info/52a389d3dbd4b6cc

     arguably call for one.
  */
  fsl_outputer output;

  /**
     Can be used to tie client-specific data to the context. Its
     finalizer is called when fsl_cx_finalize() cleans up. The library
     does not use this state. It is intended primarily for tying,
     e.g., scripting-engine information to the context, e.g. mapping a
     scripting engine context to this one for later use in fossil-side
     callbacks.
  */
  fsl_state clientState;

  /**
     Holds error state. As a general rule, this information is updated
     only by routines which need to return more info than a simple
     integer error code. e.g. this is often used to hold
     db-driver-provided error state. It is not used by "simple"
     routines for which an integer code always suffices. APIs which
     set this should denote it with a comment like "updates the
     context's error state on error."
  */
  fsl_error error;

  /**
     Reuseable scratchpads for low-level file canonicalization
     buffering and whatnot. Not intended for huge content: use
     this->cache.fileContent and friends for that. This list should
     stay relatively short, as should the buffers (a few kb each, at
     most).

     This struct predates fsl_cx_b_borrow(), and that API
     should generally be preferred for this purpose.

     @see fsl__cx_scratchpad()
     @see fsl__cx_scratchpad_yield()
  */
  struct {
    /**
       Strictly-internal temporary buffers we intend to reuse many
       times, mostly for filename canonicalization, holding hash
       values, and small encoding/decoding tasks. These must never be
       used for values which will be long-lived, nor are they intended
       to be used for large content, e.g. reading files, with the
       possible exception of holding versioned config settings, as
       those are typically rather small. They must also not be held
       while recursion back into a function holding one of these is
       possible.

       If needed, the lengths of this->buf[] and this->used[] may be
       extended, but anything beyond 8, maybe 10, seems a bit extreme.
       They should only be increased if we find code paths which
       require it. As of this writing (2021-03-17), the peak
       concurrently used was 5. In any case fsl__cx_scratchpad() fails
       fatally if it needs more than it has, so we won't/can't fail to
       overlook such a case.
    */
    fsl_b buf[8];
    /**
       Flags telling us which of this->buf is currenly in use.
    */
    bool used[8];
    /**
       A cursor _hint_ to try to speed up fsl__cx_scratchpad() by about
       half a nanosecond, making it O(1) instead of O(small N) for the
       common case.
    */
    short next;
    /**
       A scratchpad specific to fsl__cx_emit() and friends.
    */
    fsl_b emit;
    /**
       A scratchpad specific to fsl_cx_format() and friends. This one
       has to account for potential recursion.
    */
    fsl_b format;
  } scratchpads;

  /**
     Flags, some (or one) of which is runtime-configurable by the
     client (see fsl_cx_flags_e). We can get rid of this and add the
     flags to the cache member along with the rest of them.
  */
  fsl_flag32_t flags;

  /**
     Error flag which is intended to be set via signal handlers or a
     UI thread to tell this context to cancel any currently
     long-running operation. Not all operations honor this check, but
     the ones which are prone to "exceedingly long" operation (at
     least a few seconds) do.
  */
  volatile int interrupted;

  /**
     List of callbacks for deck crosslinking purposes.
  */
  fsl_xlinker_list xlinkers;

  /**
     A place for caching generic things.
  */
  struct {
    /**
       If true, skip "dephantomization" of phantom blobs.  This is a
       detail from fossil(1) with as-yet-undetermined utility. It's
       apparently only used during the remote-sync process, which this
       API does not (as of 2021-10) yet have.
    */
    bool ignoreDephantomizations;

    /**
       Whether or not a running commit process should be marked as
       private. This member is used for communicating this flag
       through multiple levels of API.
    */
    bool markPrivate;

    /**
       True if fsl__crosslink_begin() has been called but
       fsl__crosslink_end() is still pending.
    */
    bool isCrosslinking;

    /**
       Flag indicating that only cluster control artifacts should be
       processed by manifest crosslinking. This will only be relevant
       if/when the sync protocol is implemented.
    */
    bool xlinkClustersOnly;

    /**
       Is used to tell the content-save internals that a "final
       verification" (a.k.a. verify-before-commit) is underway.
    */
    bool inFinalVerify;

    /**
       True when a sync is active, to prevent recursive attempts to
       sync.
    */
    bool isSyncing;

    /**
       Specifies whether SOME repository-level file-name
       comparisons/searches will work case-insensitively. <0 means
       not-yet-determined, 0 = no, >0 = yes.
    */
    short caseInsensitive;

    /**
       Cached copy of the allow-symlinks config option, because it is
       (hypothetically) needed on many stat() call. Negative
       value=="not yet determined", 0==no, positive==yes. The negative
       value means we need to check the repo config resp. the global
       config to see if this is on.

       As of late 2020, fossil(1) is much more restrictive with
       symlinks due to vulnerabilities which were discovered by a
       security researcher, and we definitely must not default any
       symlink-related features to enabled/on. As of Feb. 2021, my
       personal preference, and very likely plan of attack, is to only
       treat SCM'd symlinks as if symlinks support is disabled. It's
       very unlikely that i will implement "real" symlink support but
       would, *solely* for compatibility with fossil(1), be convinced
       to permit such changes if someone else wants to implement them.
       Patches are joyfully considered!
    */
    short allowSymlinks;

    /**
       Indicates whether or not this repo has ever seen a delta
       manifest. If none has ever been seen then the repository will
       prefer to use baseline (non-delta) manifests. Once a delta is
       seen in the repository, the checkin algorithm is free to choose
       deltas later on unless it's otherwise prohibited, e.g. by the
       `forbid-delta-manifests` config db setting.

       This article provides an overview to the topic delta manifests
       and essentially debunks their ostensible benefits:

       https://fossil-scm.org/home/doc/tip/www/delta-manifests.md

       Values: negative==undetermined, 0==no, positive==yes. This is
       updated when a repository is first opened and when new content
       is written to it.
    */
    short seenDeltaManifest;

    /**
       Records whether this repository has an FTS search
       index. <0=undetermined, 0=no, >0=yes.
    */
    short searchIndexExists;

    /**
       Cache for the `manifest` config setting, as used by
       fsl_ckout_manifest_setting(), with the caveat that
       if the setting changes after it is cached, we won't necessarily
       see that here!
    */
    short manifestSetting;

    /**
       Record ID of rcvfrom entry during commits. This is likely to
       remain unused in libf until/unless the sync protocol is
       implemented.

       2025-07-21: this will probably need to be manipulated by
       fsl_xfer. rcvId is used in fsl__content_put_ex() but it's
       historically (in this library, not fossil(1)) always been 0.
       Setting the rcvId requires high-level info that fossil(1) uses,
       and it's only really relevant for the sync layer.
    */
    fsl_id_t rcvId;

    /**
       A place for temporarily holding file content. We use this in
       places where we have to loop over files and read their entire
       contents, so that we can reuse this buffer's memory if
       possible.  The loop and the reading might be happening in
       different functions, though, and some care must be taken to
       avoid use in two functions concurrently.

       All access to this must be acquired by fsl__cx_content_buffer()
       and released by fsl__cx_content_buffer_yield().
    */
    fsl_b fileContent;

    /**
       Reusable buffer for creating and fetching deltas via
       fsl_content_get() and fsl__content_deltify(). The number of
       allocations this actually saves is pretty small.
    */
    fsl_b deltaContent;

    /**
       fsl_content_get() cache.
    */
    fsl__bccache blobContent;

    /**
       Per-transaction-level cache.
    */
    fsl__ptl ptl;

    /**
       An internal cache for fsl__content_mark_availble().  This is
       only used in that routine but it's called frequently during
       checkins and sync.
    */
    fsl_id_bag markAvailableCache;

    /**
       Infrastructure for fsl_mtime_of_manifest_file(). It
       remembers the previous RID so that it knows when it has to
       invalidate/rebuild its ancestry cache.
    */
    fsl_id_t mtimeManifest;
    /**
       The "project-code" config option. This is primarily for use
       with the sync protocol. It is managed by
       fsl_repo_project_code().
    */
    char * projectCode;

    /**
       Internal optimization to avoid duplicate fsl_stat() calls
       across two functions in some cases.
    */
    fsl_fstat fstat;

    /**
       Parsed-deck cache.
    */
    fsl__mcache mcache;

    /**
       Holds various glob lists. That said... these features are
       actually app-level stuff which the library itself does not
       resp. should not enforce. We can keep track of these for users
       but the library internals _generally_ have no business using
       them.

       _THAT_ said... these have enough generic utility that we can
       justify storing them and _optionally_ applying them. See
       fsl_checkin_opt for an example of where we do this.
    */
    struct {
      /**
         Holds the "ignore-glob" globs.
      */
      fsl_list ignore;
      /**
         Holds the "binary-glob" globs.
      */
      fsl_list binary;
      /**
         Holds the "crnl-glob" globs.
      */
      fsl_list crnl;
    } globs;

    /**
       Very-frequently-used SQL statements.
    */
    struct {
/**
  This macro greatly simplifies maintenance of the caches fsl_stmt
  objects elsewhere, believe it or not. The 1st argument to E is the
  name of the fsl_cx::cache::stmt member. The 2nd argument is the SQL
  of that statement.

  Potential TODO: add a fsl_dbrole_e value to each so that we
  centrally know which db to check for (for error-reporting purposes)
  before preparation.
*/
#define fsl__cx_cache_stmt_map(E)                 \
      E(afterDephantomizeOrphans, \
        "SELECT rid FROM {{dbname.repo}}.orphan WHERE baseline=?1") \
      E(afterDephantomizeDeltas, \
        "SELECT rid FROM {{dbname.repo}}.delta AS delta WHERE srcid=?1 " \
        "AND NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.mlink WHERE mid=delta.rid)") \
      E(deltaR2S,"SELECT srcid FROM {{dbname.repo}}.delta WHERE rid=?1")  \
      E(deltaS2R,"SELECT rid FROM {{dbname.repo}}.delta WHERE srcid=?1")  \
      E(uuidToRid,\
        "SELECT rid FROM {{dbname.repo}}.blob WHERE uuid=?1")     \
      E(ridToUuid,\
        "SELECT uuid FROM {{dbname.repo}}.blob WHERE rid=?1") \
      E(ridIsLeaf,\
        "SELECT 1 FROM {{dbname.repo}}.plink AS plink "                             \
        "WHERE pid=?1 "                                    \
        "AND coalesce("                                    \
        "(SELECT value FROM {{dbname.repo}}.tagxref "                      \
        "WHERE tagid=8/*FSL_TAGID_BRANCH*/ AND rid=?1"     \
        " AND tagtype>0), "                                \
        "?2 /*main branch name*/)"                         \
        "=coalesce((SELECT value FROM {{dbname.repo}}.tagxref "            \
        "WHERE tagid=8/*FSL_TAGID_BRANCH*/ "               \
        "AND rid=plink.cid AND tagtype>0), "               \
        "?2 /*main branch name*/)")                        \
      E(ridIsPrivate,"SELECT 1 FROM {{dbname.repo}}.private WHERE rid=?1") \
      E(contentSize,"SELECT size FROM {{dbname.repo}}.blob WHERE rid=?1")  \
      E(contentBlob,"SELECT content, size FROM {{dbname.repo}}.blob WHERE rid=?1") \
      E(uuidIsShunned,"SELECT 1 FROM {{dbname.repo}}.shun WHERE uuid=?1")  \
      E(contentNew,\
        "INSERT INTO {{dbname.repo}}.blob(rcvid,size,uuid,content) " \
        "VALUES(0,-1,?1,NULL) "                      \
        "RETURNING rid")                             \
      E(insertPhantomRid,"INSERT OR IGNORE INTO {{dbname.repo}}.phantom VALUES(?1)") \
      E(insertPrivateRid,"INSERT OR IGNORE INTO {{dbname.repo}}.private VALUES(?1)") \
      E(insertUnclusteredRid,"INSERT OR IGNORE INTO {{dbname.repo}}.unclustered VALUES(?1)") \
      E(insertUnsentRid,"INSERT OR IGNORE INTO {{dbname.repo}}.unsent VALUES(?1)") \
      E(ridDelDelta,"DELETE FROM {{dbname.repo}}.delta WHERE rid=?1")              \
      E(ridDelPrivate,"DELETE FROM {{dbname.repo}}.private WHERE rid=?1")       \
      E(ridDelPhantom,"DELETE FROM {{dbname.repo}}.phantom WHERE rid=?1")       \
      E(replaceDelta,                                           \
        "REPLACE INTO {{dbname.repo}}.delta(rid,srcid) VALUES(?1,?2)")          \
      E(contentUndeltify,                                       \
        "UPDATE {{dbname.repo}}.blob SET content=?1, size=?2 WHERE rid=?3")     \
      E(blobRidSize,"SELECT rid, size FROM {{dbname.repo}}.blob WHERE uuid=?1") \
      E(blobUpdateContent,                                      \
        "UPDATE {{dbname.repo}}.blob SET content=?1 WHERE rid=?2")      \
      E(phantomPopulate,                                \
        "UPDATE {{dbname.repo}}.blob SET rcvid=?1, size=?2, "           \
        "content=?3 WHERE rid=?4")                      \
      E(blobInsertFull,                                 \
        "INSERT INTO {{dbname.repo}}.blob (rcvid,size,uuid,content) "   \
        "VALUES(?1,?2,?3,?4) RETURNING rid")            \
      E(leafInsert,                                     \
        "INSERT OR IGNORE INTO {{dbname.repo}}.leaf VALUES (?1)")       \
      E(leafDelete,                                     \
        "DELETE FROM {{dbname.repo}}.leaf WHERE rid=?1")                \
      E(leavesInsert,                                   \
        "INSERT OR IGNORE INTO {{temp.leaves}} VALUES (?1)")     \
      E(parentsOf,                                      \
        "SELECT pid FROM {{dbname.repo}}.plink WHERE cid=?1 AND pid>0") \
      E(branchOfRid,                                    \
        "SELECT value FROM {{dbname.repo}}.tagxref WHERE rid=?1 "       \
        "AND tagid=8/*==FSL_TAGID_BRANCH*/ "            \
        "AND tagtype>0")                                \
      E(ridIsCheckin,                                   \
        "SELECT 1 FROM {{dbname.repo}}.event WHERE objid=?1 "           \
        "AND type='ci'"                                 \
      )                                                 \
      E(ridHasTagId,                                    \
        "SELECT tag.tagid FROM {{dbname.repo}}.tagxref AS tagxref, {{dbname.repo}}.tag AS tag"            \
        " WHERE tagxref.rid=?1 AND tagtype>0 "          \
        " AND tag.tagid=?2"                             \
        " AND tagxref.tagid=tag.tagid")                 \
      /*
         TODO. Something akin to:

         WITH RECURSIVE
         dchain(rid,srcid,level) AS (
           SELECT ?1 rid, NULL srcid, 0 level
           UNION ALL
           SELECT delta.rid, delta.srcid, dchain.level+1
           FROM delta JOIN dchain ON delta.srcid=dchain.rid
           ORDER BY 2
         )
         SELECT rid, srcid FROM dchain WHERE level>0

       i.e.: for RID ?1, get a list of all deltas which
       depend on this. (Is it really all?).

       Remember that we can have multiple paths to a parent,
       as in this simulated delta table:

       drop table if exists dmap;
       create temp table dmap(rid INTEGER NOT NULL, srcid INTEGER NOT NULL);
       insert into dmap values(2,4),(4,6),(6,8),(8,10);
       insert into dmap values(1,11),(11,10);
       insert into dmap values(20,30),(30,0);

       For a ?1 of 10 that will emit:

       rid|srcid
       8|10
       6|8
       4|6
       2|4
       11|10 -- note that we re-visit the root here
       1|11
      */ \
      E(deltaChainForRid,"")

#define STMT(MEMBER,IGNORED) fsl_stmt MEMBER;
      fsl__cx_cache_stmt_map(STMT)
#undef STMT

    } stmt;

    /**
       Holds a list of temp-dir names. Must be allocated using
       fsl_temp_dirs_get() and freed using fsl_temp_dirs_free().
    */
    char **tempDirs;

    /**
       Buffers managed by fsl_cx_b_borrow() and
       fsl_cx_b_return(). This fundamentally does the same thing
       as the fsl__cx_scratchpad family but this list is dynamic and
       has no hard upper limit like those do.
    */
    fsl__b_library buf;
  } cache;

  /**
     Ticket-related information.
  */
  struct {
    /**
       Holds a list of (fsl_card_J*) records representing custom
       ticket table fields available in the db.

       Each entry's flags member denotes (using fsl_card_J_flags)
       whether that field is used by the ticket or ticketchng
       tables.

       TODO, eventually: add a separate type for these entries.  We
       use fsl_card_J because the infrastructure is there and they
       provide what we need, but fsl_card_J::flags only exists for
       this list. A custom type would be smaller than fsl_card_J
       (only two members) but adding it requires adding some
       infrastructure which isn't worth the effort at the moment.
    */
    fsl_list customFields;

    /**
       Gets set to true (at some point) if the client has the
       ticket db table.
    */
    bool hasTicket;

    /**
       Gets set to true (at some point) if the client has the
       ticket.tkt_ctime db field.
    */
    bool hasCTime;

    /**
       Gets set to true (at some point) if the client has the
       ticketchng db table.
    */
    bool hasChng;

    /**
       Gets set to true (at some point) if the client has the
       ticketchng.rid db field.
    */
    bool hasChngRid;

    /**
       The name of the ticket-table field which refers to a ticket's
       title. Default = "title". The bytes are owned by this object.
    */
    char * titleColumn;

    /**
       The name of the ticket-table field which refers to a ticket's
       status. Default = "status". The bytes are owned by this object.
    */
    char * statusColumn;
  } ticket;

  /**
     Various metrics.
  */
  struct {
    /** Content-specific metrics. */
    struct {
      /**
         Number of times the internal content cache was used.
      */
      fsl_size_t nCached;
      /**
         Total of the number of "used" bytes of the content cache
         each time it was relinquished.
      */
      fsl_size_t nTotalUsed;

      /**
         The maximum buffer capacity the content buffer had at
         relenquish-time.
      */
      fsl_size_t nPeakBufSize;

      /**
         The number of times the content cache buffer was trimmed
         below the built-in maximum size.
      */
      fsl_size_t nCappedMaxSize;
    } content;
  } metrics;
};

/** @internal
    Initialized-with-defaults fsl_cx instance.
*/
extern const fsl_cx fsl__cx_empty;

#if !defined(NDEBUG)
/**
   Ensure that fsl_cx::scratchpads::buf/used have the same array size.
*/
typedef int fsl__cx_StaticAssertScratchpadSizes[
 ((sizeof(fsl__cx_empty.scratchpads.buf)
  /sizeof(fsl__cx_empty.scratchpads.buf[0]))
 == (sizeof(fsl__cx_empty.scratchpads.used)
     /sizeof(fsl__cx_empty.scratchpads.used[0])))
 ? 1 : -1
];
#endif

/*
  TODO:

  int fsl_b_append_getenv( fsl_b * b, char const * env )

  Fetches the given env var and appends it to b. Returns FSL_RC_NOT_FOUND
  if the env var is not set. The primary use for this would be to simplify
  the Windows implementation of fsl_find_home_dir().
*/


/** @internal

    Expires the single oldest entry in c. Returns true if it removes
    an item, else false.
*/
bool fsl__bccache_expire_oldest(fsl__bccache * c);

/** @internal

    Removes the cache entry for the given rid, if any, freeing its
    content and updating the cache's size accounting. Returns true if
    an entry was removed, else false.
*/
bool fsl__bccache_remove(fsl__bccache * c, fsl_id_t rid);

/** @internal

    Add an entry to the content cache.

    This routines transfers the contents of pBlob over to c,
    regardless of success or failure.  The cache will deallocate the
    memory when it has finished with it.

    If the cache cannot add the entry due to cache-internal
    constraints, as opposed to allocation errors, it clears the buffer
    (for consistency's sake) and returns 0.

    Returns 0 on success, FSL_RC_OOM on allocation error. Has undefined
    behaviour if !c, rid is not semantically valid, !pBlob. An empty
    blob is normally semantically illegal but is not strictly illegal
    for this cache's purposes.
*/
int fsl__bccache_insert(fsl__bccache * c, fsl_id_t rid,
                       fsl_b * pBlob);

/** @internal

    Frees all memory held by c, and clears out c's state, but does
    not free c. Results are undefined if !c.
*/
void fsl__bccache_clear(fsl__bccache * c);

/** @internal

    Resets all bags associated with the given cache and frees all
    cached buffer memory, but keeps any fsl_id_bag memory intact for
    re-use. This does not reset the hit/miss metrics.
*/
void fsl__bccache_reuse(fsl__bccache * c);


/** @internal

    Checks f->cache.blobContent to see if rid is available in the
    repository opened by f.

    Returns 0 if the content for the given rid is available in the
    repo or the cache. Returns FSL_RC_NOT_FOUND if it is not in the
    repo nor the cache. Returns some other non-0 code for "real
    errors," e.g. FSL_RC_OOM if a cache allocation fails. This
    operation may update the cache's contents.

    If this function detects a loop in artifact lineage, it fails an
    assert() in debug builds and returns FSL_RC_CONSISTENCY in
    non-debug builds. That doesn't happen in real life, though.

    Reminder to self: it should arguably return FSL_RC_PHANTOM if it's
    a phantom but the next call for that same rid would pull from
    f->cache.blobContent.missing and lose the distinction between
    "wasn't found" and "is a phantom", so would have to return
    FSL_RC_NOT_FOUND. If we ever need another fsl_id_bag for tracking
    phantoms, we can adjust this to return FSL_RC_PHANTOM by checking
    that bag for the RID.
*/
int fsl__bccache_check_available(fsl_cx * f, fsl_id_t rid);

/** @internal

    This is THE ONLY ROUTINE IN THE LIBRARY which is permitted to add
    content to the blob table.  Only one other routine
    (fsl__phantom_new()) adds new blob entries, but that one does not
    add blobs with content.

    This writes the given buffer content into the repository
    database's blob tabe. It Returns the record ID via outRid (if it
    is not NULL).  If the content is already in the database (as
    determined by a lookup of its hash against blob.uuid), this
    routine fetches the RID (via *outRid) but has no side effects in
    the repo.

    If srcId is >0 then pBlob must contain delta content from
    the srcId record. srcId might be a phantom.

    pBlob is normally uncompressed text, but if uncompSize>0 then the
    pBlob value is assumed to be compressed (via fsl_b_compress()
    or equivalent) and uncompSize is its uncompressed size. If
    uncompSize>0 then zUuid must be valid and refer to the hash of the
    _uncompressed_ data (which is why this routine does not calculate
    it for the client).

    Sidebar 2025-08-04: it is legal for the uncompressed size to be 0
    when the content is compressed (and larger). That case can't be
    represented with the above semantics. Do we actually handle the
    empty-file case properly? 2026-09-29: the 0-size case was added
    recently to handle synced-in files.

    Sidebar: we "could" use fsl_b_is_compressed() and friends to
    determine if pBlob is compressed and get its decompressed size,
    then remove the uncompSize parameter, but that would require that
    this function decompress the content to calculate the hash. Since
    the caller likely just compressed it, that seems like a huge
    waste. Sniffing the bytes is also unreliable: ordinary content
    can look compressed, so this function never does that. A cfile
    for the empty artifact (usize 0) is passed in as empty raw
    content instead.

    zUuid is the UUID of the artifact, if it is not NULL.  When
    srcId is specified then zUuid must always be specified.  If
    srcId is zero, and zUuid is zero then the correct zUuid is
    computed from pBlob.  If zUuid is not NULL then this function
    asserts (in debug builds) that fsl_is_uuid() returns true for
    zUuid.

    If isPrivate is true or if f->cache.markPrivate is true, the blob
    is created as a private record.

    If the record already exists but is a phantom, the pBlob content
    is inserted and the phatom becomes a real record.

    The original content of pBlob is not disturbed.  The caller continues
    to be responsible for pBlob.  This routine does *not* take over
    responsibility for freeing pBlob.

    If outRid is not NULL then on success *outRid is assigned to the
    RID of the underlying blob record.

    Returns 0 on success and there are too many potential error cases
    to name - this function is a massive beast.

    On success, the new blob's RID is queued up for pre-commit content
    validation. If this is the first call to this function in the
    current transaction stack, the RID is queued in the COMMIT handler
    for the _parent_ transaction. Subsequent calls will cause the RID
    to be queued in that same transaction level. We cannot validate in
    _this_ function because the validation would trigger at the end of
    the transaction level which _this_ function installs. Content
    validation has to be delayed until we believe we have all content
    which will be injected in the current transaction stack.

    @see fsl__content_put()
*/
int fsl__content_put_ex( fsl_cx * f,
                        fsl_b const * pBlob,
                        fsl_uuid_cstr zUuid, fsl_id_t srcId,
                        fsl_size_t uncompSize, bool isPrivate,
                        fsl_id_t * outRid);
/** @internal

    Equivalent to fsl__content_put_ex(f,pBlob,NULL,0,0,false,newRid).

    This must only be used for saving raw (non-delta) content.

    @see fsl__content_put_ex()
*/
int fsl__content_put( fsl_cx * f,
                     fsl_b const * pBlob,
                     fsl_id_t * newRid);


/** @internal

    If the given blob ID refers to deltified repo content, this routine
    undeltifies it and replaces its content with its expanded
    form.

    Returns 0 on success, FSL_RC_NOT_A_REPO if f has no opened
    repository, FSL_RC_RANGE if rid is not positive, and any number of
    other potential errors during the db and content operations. This
    function treats already unexpanded content as success.

    @see fsl__content_deltify()
*/
int fsl__content_undeltify(fsl_cx * f, fsl_id_t rid);


/** @internal

    The converse of fsl__content_undeltify(), this replaces the storage
    of the given blob record so that it is a delta of srcid.

    If rid is already a delta from some other place then no conversion
    occurs and this is a no-op unless force is true, which case the
    content is undeltified and re-delta'd against srcid.

    If rid's contents are not available because the the rid is a
    phantom or depends to one, no delta is generated and 0 is
    returned.

    It never generates a delta that carries a private artifact into
    a public artifact. Otherwise, when we go to send the public
    artifact on a sync operation, the other end of the sync will
    never be able to receive the source of the delta.  It is OK to
    delta private->private, public->private, and public->public.
    Just no private->public delta. For such cases this function
    returns 0, as opposed to FSL_RC_ACCESS or some similar code, and
    leaves the content untouched.

    If srcid is a delta that depends on rid, then srcid is
    converted to undelta'd text.

    If either rid or srcid contain less than some "small,
    unspecified number" of bytes (currently 50), or if the resulting
    delta does not achieve a compression of at least 25%, the rid is
    left untouched.

    Returns 0 if a delta is successfully made or none needs to be
    made, non-0 on error.

    Requires that fsl_cx_txn_level() be greater than 0.

    @see fsl__content_undeltify()
*/
int fsl__content_deltify(fsl_cx * f, fsl_id_t rid,
                        fsl_id_t srcid, bool force);


/** @internal

    Creates a new phantom blob with the given UUID and return its
    artifact ID via *newId. Returns 0 on success, any of many codes on
    error.  If isPrivate is true _or_ f has been flagged as being in
    "private mode" then the new content is flagged as private. newId
    may be NULL, but if it is then the caller will have to find the
    record id himself by using the UUID (see fsl_uuid_to_rid()).
*/
int fsl__phantom_new( fsl_cx * f, fsl_uuid_cstr uuid,
                      bool isPrivate, fsl_id_t * newId );

/** @internal

    Schedules a leaf check for "rid" and its parents. Returns 0 on
    success.
*/
int fsl__leaf_eventually_check( fsl_cx * f, fsl_id_t rid);

/** @internal

    Perform all pending leaf checks. Returns 0 on success or if it
    has nothing to do.
*/
int fsl__leaf_do_pending_checks(fsl_cx * f);

/** @internal

    Inserts a tag into f's repo db. It does not create the related
    control artifact - use fsl_tag_an_rid() for that.

    rid is the artifact to which the tag is being applied.

    srcId is the artifact that contains the tag. It is often, but
    not always, the same as rid. This is often the RID of the
    manifest containing tags added as part of the commit, in which
    case rid==srcId. A Control Artifact which tags a different
    artifact will have rid!=srcId.

    mtime is the Julian timestamp for the tag. Defaults to the
    current time if mtime <= 0.0.

    If outRid is not NULL then on success *outRid is assigned the
    record ID of the generated tag (the tag.tagid db field).

    If a more recent (compared to mtime) entry already exists for
    this tag/rid combination then its tag.tagid is returned via
    *outRid (if outRid is not NULL) and no new entry is created.

    Returns 0 on success, and has a huge number of potential error
    codes.
*/
int fsl__tag_insert( fsl_cx * f,
                     fsl_tagtype_e tagtype,
                     char const * zTag,
                     char const * zValue,
                     fsl_id_t srcId,
                     double mtime,
                     fsl_id_t rid,
                     fsl_id_t *outRid );
/** @internal

    Propagate all propagatable tags in artifact pid to the children of
    pid. Returns 0 on... non-error. Returns FSL_RC_RANGE if pid<=0.
*/
int fsl__tag_propagate_all(fsl_cx * f, fsl_id_t pid);

/** @internal

    Propagates a tag through the various internal pipelines.

    pid is the artifact id to whose children the tag should be
    propagated.

    tagid is the id of the tag to propagate (the tag.tagid db value).

    tagType is the type of tag to propagate. Must be either
    FSL_TAGTYPE_CANCEL or FSL_TAGTYPE_PROPAGATING. Note that
    FSL_TAGTYPE_ADD is not permitted.  The tag-handling internals
    (other than this function) translate ADD to CANCEL for propagation
    purposes. A CANCEL tag is used to stop propagation. (That's a
    historical behaviour inherited from fossil(1).) A potential TODO
    is for this function to simply treat ADD as CANCEL, without
    requiring that the caller be sure to never pass an ADD tag.

    origId is the artifact id of the origin tag if tagType ==
    FSL_TAGTYPE_PROPAGATING, otherwise it is ignored.

    zValue is the optional value for the tag. May be NULL.

    mtime is the Julian timestamp for the tag. Must be a valid time
    (no defaults here).

    This function is unforgiving of invalid values/ranges, and may assert
    in debug mode if passed invalid ids (values<=0), a NULL f, or if f has
    no opened repo.
*/
int fsl__tag_propagate(fsl_cx * f,
                      fsl_tagtype_e tagType,
                      fsl_id_t pid,
                      fsl_id_t tagid,
                      fsl_id_t origId,
                      const char *zValue,
                      double mtime );

/**
   Marks libfossil as running inside a host process which owns
   SQLite, e.g. as a SQLite extension. It must be called before any
   other libfossil API. Afterwards, library-level init does not
   install an atexit() handler.
*/
void fsl__lib_hosted(void);

/**
   Makes db use a host's open sqlite3 handle. fsl_db_close() will not
   close it. db must not already be opened.
*/
void fsl__db_borrow(fsl_db * const db, sqlite3 * const dbh);

/**
   Returns true if db's sqlite3 handle came from fsl__db_borrow().
*/
bool fsl__db_is_borrowed(fsl_db const * const db);

/**
   Drops TEMP table zTable if it exists. If SQLite refuses because
   another statement is running, e.g. a host's statement which called
   us through a SQL function, it empties the table instead, so callers
   which create it again must use CREATE TEMP TABLE IF NOT EXISTS.
   Returns 0 or a db error code.
*/
int fsl__db_temp_drop(fsl_db * const db, char const * zTable);

/**
   Returns true if db's connection is inside a transaction or has a
   statement running, e.g. a host's statement which called us through
   a SQL function. A read-only operation which would open a
   transaction only so that its several statements see one consistent
   snapshot must skip that when this is true: the running statement
   or the open transaction already holds the connection's read (or
   write) lock, so no other connection can commit in between, and
   SQLite refuses to open a savepoint while a writing statement is in
   progress. Never use this to skip a transaction which protects
   writes, including writes to caches and TEMP tables.
*/
bool fsl__db_in_statement_or_txn(fsl_db * const db);

/** @internal

    Generates an fsl_appendf()-formatted message to stderr and
    fatally aborts the application by calling exit(). This is only
    (ONLY!) intended for us as a placeholder for certain test cases
    and is neither thread-safe nor reantrant.

    fmt may be empty or NULL, in which case only the code and its
    fsl_rc_cstr() representation are output.

    This function does not return.

    Possible todo: expose this in the public API as fcli_fatal().
*/
void fsl__fatal(int code, char const * fmt, ...)
#ifdef __GNUC__
  __attribute__ ((noreturn))
#endif
  ;

/** @internal

    Translate a normalized, repo-relative filename into a
    filename-id (fnid). Create a new fnid if none previously exists
    and createNew is true. On success returns 0 and sets *rv to the
    filename.fnid record value. If createNew is false and no match
    is found, 0 is returned but *rv will be set to 0. Returns non-0
    on error.  Results are undefined if any parameter is NULL.


    In debug builds, this function asserts that no pointer arguments
    are NULL and that f has an opened repository.
*/
int fsl__repo_filename_fnid2( fsl_cx * f, char const * filename,
                             fsl_id_t * rv, bool createNew );


/** @internal

    Clears and frees all (char*) members of db but leaves the rest
    intact. If alsoBuffers is true then the error state and prep
    buffer are also freed, else they are kept as well.
*/
void fsl__db_clear_strings(fsl_db * db, bool alsoBuffers );

/** @internal

    Returns 0 if db appears to have a current repository schema, 1
    if it appears to have an out of date schema, and -1 if it
    appears to not be a repository. Results are undefined if db is
    NULL or not opened.
*/
int fsl__db_repo_verify_schema(fsl_db * db);


/** @internal

    Flags for APIs which add phantom blobs to the repository.  The
    values in this enum derive from fossil(1) code and should not be
    changed without careful forethought and (afterwards) testing.  A
    phantom blob is a blob about whose existence we know but for which
    we have no content. This normally happens during sync or rebuild
    operations, but can also happen when artifacts are stored directly
    as files in a repo (like this project's repository does, storing
    artifacts from *other* projects for testing purposes).
*/
enum fsl__phantom_e {
/**
   Indicates to fsl__uuid_to_rid2() that no phantom artifact
   should be created.
*/
FSL_PHANTOM_NONE = 0,
/**
   Indicates to fsl__uuid_to_rid2() that a public phantom
   artifact should be created if no artifact is found.
*/
FSL_PHANTOM_PUBLIC = 1,
/**
   Indicates to fsl__uuid_to_rid2() that a private phantom
   artifact should be created if no artifact is found.
*/
FSL_PHANTOM_PRIVATE = 2
};
typedef enum fsl__phantom_e fsl__phantom_e;

/** @internal

    Works like fsl_uuid_to_rid(), with these differences:

    - uuid is required to be a complete UUID, not a prefix.

    - If it finds no entry and the mode argument specifies so then it
      will add either a public or private phantom entry and return its
      new rid. If mode is FSL_PHANTOM_NONE then this this behaves just
      like fsl_uuid_to_rid().

    Returns a positive value on success, 0 if it finds no entry and
    mode==FSL_PHANTOM_NONE, and1 a negative value on error (e.g. if
    fsl_is_uuid(uuid) returns false). Errors which happen after
    argument validation will "most likely" update f's error state
    with details.
*/
fsl_id_t fsl__uuid_to_rid2( fsl_cx * f, fsl_uuid_cstr uuid,
                           fsl__phantom_e mode );

/** @internal

    Schedules the given rid to be verified before it is commited, but
    whether the validation will be done at the commit of the current
    transaction level or a higher-up one is as-yet unspecified . This
    is used by routines which add artifact records to the blob table.

    The only error case, assuming the arguments are valid, is an
    allocation error while appending rid to the internal to-verify
    queue.

    @see fsl__repo_verify_at_commit()
    @see fsl_repo_verify_cancel()
*/
int fsl__repo_verify_before_commit( fsl_cx * f, fsl_id_t rid );

/** @internal

    Clears the current transaction level's verify-at-commit list of
    RIDs.

    @see fsl__repo_verify_at_commit()
    @see fsl__repo_verify_before_commit()
*/
void fsl__repo_verify_cancel( fsl_cx * f );

/** @internal

    Processes all pending verify-at-commit entries for the current
    transaction level and clears the to-verify list. Returns 0 on
    success. On error f's error state will likely be updated.

    ONLY call this from fsl_db_txn_end() or its delegate (if
    refactored).

    Verification calls fsl_content_get() to "unpack" content added in
    the current transaction. If fetching the content (which applies
    any deltas it may need to) fails or its hash does not match its
    blob.uuid value then this routine fails and returns non-0.

    @see fsl_repo_verify_cancel()
    @see fsl__repo_verify_before_commit()
*/
int fsl__repo_verify_at_commit( fsl_cx * f );

/** @internal

    Verifies one blob record: if its content can be reconstructed,
    its hash must match its blob.uuid value. Returns 0 on success, and
    also for a phantom or for a delta whose source is not yet
    available, which cannot be verified yet. On a hash mismatch it
    returns FSL_RC_CONSISTENCY. If the content cannot be reconstructed
    (e.g. a delta which does not apply) it returns that error code.
    On error it updates f's error state.

    This is the per-RID check done by fsl__repo_verify_at_commit(),
    for callers which need to verify content as it arrives.
*/
int fsl__repo_verify_rid( fsl_cx * f, fsl_id_t rid );

/** @internal

    Removes all entries from the repo's blob table which are listed
    in the shun table. Returns 0 on success. This operation is
    wrapped in a transaction. Delta content which depend on
    to-be-shunned content are replaced with their undeltad forms.

    Returns 0 on success. On error, its transaction is aborted or a
    pseudo-nested transaction is set into a rollback state.
*/
int fsl__repo_shun_artifacts(fsl_cx * f);

/** @internal.

    Return a pointer to a string that contains the RHS of an SQL IN
    operator which will select config.name values that are part of
    the configuration that matches iMatch (a bitmask of
    fsl_configset_e values). Ownership of the returned string is
    passed to the caller, who must eventually pass it to
    fsl_free(). Returns NULL on allocation error.

    Reminder to self: this is part of the infrastructure for copying
    config state from an existing repo when creating new repo.
*/
char *fsl__config_inop_rhs(int iMask);

/** @internal

    Applies a single "config" card received over the sync protocol.

    zName is the card's wire name ("/shun", "/user", ...). pContent is
    the card's payload, which is tokenized IN PLACE and thus modified;
    callers must treat it as scratch space afterwards. groupMask is a
    bitmask of FSL_CONFIGSET_* values limiting which configuration
    groups may be applied.

    The payload is a sequence of token pairs: first the mtime and the
    target row's primary key, then zero or more (column, value) pairs.
    A row is inserted if absent and overwritten only if the incoming
    mtime is strictly newer than the stored one.

    Returns 0 on success AND on every protocol-legal skip: an unknown
    or unsupported card name, a name outside groupMask, an unknown
    column, or a malformed payload. This mirrors fossil, which never
    fails a sync over a bad config card. A non-0 result means a real
    db or allocation error and should abort the transfer.
*/
int fsl__config_receive(fsl_cx * const f, char const * zName,
                        fsl_b * const pContent, int groupMask);

/** @internal

    Returns the FSL_CONFIGSET_* mask this build considers zName
    exportable/receivable under via a /config sync card (per its
    entry in the internal fslConfigXfer[] allow-list), or 0 if zName
    is unknown to that table or is on the hard-coded sensitive-setting
    deny list. A 0 result means fsl__config_receive() will always
    skip a /config card for this name, regardless of groupMask.

    This is exposed beyond src/config.c specifically so callers that
    seed local config rows outside of sync (e.g. fsl_repo_create())
    can assert that a seeded name is NOT wire-syncable: any name which
    is both locally pre-seeded with a "now" mtime AND wire-syncable
    will permanently block a real, older incoming value, since
    fsl__config_receive()'s overwrite guard is `mtime<incoming`. See
    the DBSET_INT block in fsl_repo_create() for the concrete case
    this closed (2026-07-22, "timeline-plaintext").
*/
int fsl__config_name_mask(char const * zName);

/** @internal

    Return a pointer to a string that contains the RHS of an IN
    operator that will select config.name values that are in the
    list of control settings. Ownership of the returned string is
    passed to the caller, who must eventually pass it to
    fsl_free(). Returns NULL on allocation error.

    Reminder to self: this is part of the infrastructure for copying
    config state from an existing repo when creating new repo.
*/
char *fsl__db_setting_inop_rhs(void);

/** @internal

    Creates the ticket and ticketchng tables in f's repository db,
    DROPPING them if they already exist. The schema comes from
    fsl_schema_ticket().

    TODO? Add a flag specifying whether to drop or keep existing
    copies.

    Returns 0 on success.
*/
int fsl__cx_ticket_create_table(fsl_cx * f);

/** @internal

    Frees all J-card entries in the given list.

    li is assumed to be empty or contain (fsl_card_J*)
    instances. If alsoListMem is true then any memory owned
    by li is also freed. li itself is not freed.

    Results are undefined if li is NULL.
*/
void fsl__card_J_list_free( fsl_list * li, bool alsoListMem );

/** @internal

    Values for fsl_card_J::flags.
*/
enum fsl_card_J_flags {
/**
   Sentinel value.
*/
FSL_CARD_J_INVALID = 0,
/**
   Indicates that the field is used by the ticket table.
*/
FSL_CARD_J_TICKET = 0x01,
/**
   Indicates that the field is used by the ticketchng table.
*/
FSL_CARD_J_CHNG = 0x02,
/**
   Indicates that the field is used by both the ticket and
   ticketchng tables.
*/
FSL_CARD_J_BOTH = FSL_CARD_J_TICKET | FSL_CARD_J_CHNG
};

/** @internal

    Loads all custom/customizable ticket fields from f's repo's
    ticket table info f. If f has already loaded the list and
    forceReload is false, this is a no-op.

    Returns 0 on success.

    @see fsl_cx::ticket::customFields
*/
int fsl__cx_ticket_load_fields(fsl_cx * f, bool forceReload);

/** @internal

    A comparison routine for qsort(3) which compares fsl_card_J
    instances in a lexical manner based on their names. The order is
    important for card ordering in generated manifests.

    This routine expects to get passed (fsl_card_J**) (namely from
    fsl_list entries), and will not work on an array of J-cards.
*/
int fsl__qsort_cmp_J_cards( void const * lhs, void const * rhs );

/** @internal

    This function updates the repo and/or global config databases
    with links between the dbs intended for various fossil-level
    bookkeeping and housecleaning. These links are not essential to
    fossil's functionality but assist in certain "global"
    operations.

    If no checkout is opened but a repo is, the global config (if
    opened) is updated to know about the opened repo db.

    If a checkout is opened, global config (if opened) and the
    repo are updated to point to the checked-out db.
*/
int fsl__repo_record_filename(fsl_cx * f);

/** @internal

    Updates f->ckout.uuid and f->ckout.rid to reflect the current
    checkout state. If no checkout is opened, the uuid is freed/NULLed
    and the rid is set to 0. Returns 0 on success. If it returns an
    error (OOM or db-related), the f->ckout state is left in a
    potentially inconsistent state, and it should not be relied upon
    until/unless the error is resolved.

    This is done when a checkout db is opened, when performing a
    checkin, and otherwise as needed, and so calling it from other
    code is normally not necessary.

    @see fsl__ckout_version_write()
*/
int fsl__ckout_version_fetch( fsl_cx * f );

/** @internal

    Updates f->ckout's state to reflect the given version info and
    writes the 'checkout' and 'checkout-hash' properties to the
    currently-opened checkout db. Returns 0 on success,
    FSL_RC_NOT_A_CKOUT if no checkout is opened (may assert() in that
    case!), or some other code if writing to the db fails.

    If vid is 0 then the version info is null'd out. Else if uuid is
    NULL then fsl_rid_to_uuid() is used to fetch the UUID for vid.

    If the RID differs from f->ckout.rid then f->ckout's version state
    is updated to the new values.

    This routine also updates or removes the checkout's manifest
    files, as per fsl_ckout_manifest_write(). If vid is 0 then it
    removes any such files which themselves are not part of the
    current checkout.

    @see fsl__ckout_version_fetch()
    @see fsl_cx_ckout_version_set()
*/
int fsl__ckout_version_write( fsl_cx * f, fsl_id_t vid,
                             fsl_uuid_cstr uuid );

/**
   @internal

   Exports the file with the given [vfile].[id] to the checkout,
   overwriting (if possible) anything which gets in its way. If
   the file is determined to have not been modified, it is
   unchanged.

   If the final argument is not NULL then it is set to 0 if the file
   was not modified, 1 if only its permissions were modified, and 2 if
   its contents were updated (which also requires resetting its
   permissions to match their repo-side state).

   Returns 0 on success, any number of potential non-0 codes on
   error, including, but not limited to:

   - FSL_RC_NOT_A_CKOUT - no opened checkout.
   - FSL_RC_NOT_FOUND - no matching vfile entry.
   - FSL_RC_OOM - we cannot escape this eventuality.

   Trivia:

   - fossil(1)'s vfile_to_disk() is how it exports a whole vfile, or a
   single vfile entry, to disk. e.g. it performs a checkout that way,
   whereas we currently perform a checkout using the "repo extraction"
   API. The checkout mechanism was probably the first major core
   fossil feature which was structured radically differently in
   libfossil, compared to the feature's fossil counterpart, when it
   was ported over.

   - This routine always writes to the vfile.pathname entry, as
   opposed to vfile.origname.

   Maintenance reminders: internally this code supports handling
   multiple files at once, but (A) that's not part of the interface
   and may change and (B) the 3rd parameter makes little sense in that
   case unless maybe we change it to a callback, which seems like
   overkill for our use cases.

   BUGS:

   - When doing a fsl_ckout_revert(), this function does not recognize
     a file which has been modified (only) via a merge as modified, so
     does not set `*wasWritten`. Whether that bug is in _this_
     function or fsl__is_locally_modified() is not yet clear.
     fsl_ckout_revert() works around that so that the client can be
     notified of reverted files, but that's only hiding the underlying
     discrepancy.
*/
int fsl__vfile_to_ckout(fsl_cx * f, fsl_id_t vfileId,
                       int * wasWritten);

/** @internal

    On Windows platforms (only), if fsl_isalpha(*zFile)
    and ':' == zFile[1] then this returns zFile+2,
    otherwise it returns zFile.
*/
char * fsl__file_without_drive_letter(char * zFile);

/** @internal

    This is identical to the public-API member fsl_deck_F_search(),
    except that it returns a non-const F-card.

    Locate a file named zName in d->F.list.  Return a pointer to the
    appropriate fsl_card_F object. Return NULL if not found. Names
    match byte for byte, whatever the context's case-sensitivity
    setting, as fossil(1)'s manifest_file_seek() does;
    fsl_deck_F_search() also matches case-insensitively when that
    setting is off.

    If d->f is set (as it is when loading decks via
    fsl_deck_load_rid() and friends), this routine works even if p is
    a delta-manifest. The pointer returned might be to the baseline
    and d->B.baseline is loaded on demand if needed.

    If the returned card's uuid member is NULL, it means that the file
    was removed in the checkin represented by d.

    If !d, zName is NULL or empty, or FSL_SATYPE_CHECKIN!=d->type, it
    asserts in debug builds and returns NULL in non-debug builds.

    We assume that filenames are in sorted order and use a binary
    search. As an optimization, to support the most common use case,
    searches through a deck update d->F.cursor to the last position a
    search was found. Because searches are normally done in lexical
    order (because of architectural reasons), this is normally an O(1)
    operation. It degrades to O(N) if out-of-lexical-order searches
    are performed.
*/
fsl_card_F * fsl__deck_F_seek(fsl_deck * d, const char *zName);

/** @internal

    Works like fsl__deck_F_seek() but tells a missing file from a
    search which could not be done: sets *rv to the entry or NULL and
    returns 0, or returns an error code, with d->f's error state set,
    if the search cannot be done (a delta manifest's baseline cannot
    be loaded). *rv is NULL whenever the result is not 0.
*/
int fsl__deck_F_seek2(fsl_deck * d, const char *zName, fsl_card_F ** rv);

/**
   Works like fsl_deck_F_add(), but if strictNames is false, name and
   oldName get only the structural check of fsl_is_simple_pathname(),
   not its check for new filenames. Use false where the names come from
   existing artifacts or the checkout, which may hold names that older
   versions of fossil(1) or an import wrote and that the strict check
   refuses. fsl_deck_F_add() passes true.
*/
int fsl__deck_F_add2( fsl_deck * mf, char const * name,
                      char const * uuid, fsl_fileperm_e perms,
                      char const * oldName, bool strictNames );

/** @internal

    Ensures that f's single file content buffer is available for use
    and returns it to the caller. If it appears to already be in use,
    this function fails fatally via fsl__fatal(), indicating a serious
    misuse of the internal API.

    Calling this obligates the caller to call
    fsl__cx_content_buffer_yield() as soon as they are done with the
    buffer.
*/
fsl_b * fsl__cx_content_buffer(fsl_cx * f);

/** @internal

    Part of the fsl_cx::cache::fileContent optimization. Passes
    f->cache.fileContent to fsl_b_reuse() and if its capacity is
    over a certain (unspecified, unconfigurable) size then it is
    trimmed to that size. It also updates some of f's metrics.
*/
void fsl__cx_content_buffer_yield(fsl_cx * f);

/**
   Inserts the given rid into the repo.private table.
*/
int fsl__private_rid_add(fsl_cx * f, fsl_id_t rid);

/**
   Deletes the given rid from the repo.private table.
*/
int fsl__private_rid_delete(fsl_cx * f, fsl_id_t rid);

/**
   Inserts the given rid into the repo.unclustered table.
*/
int fsl__unclustered_rid_add(fsl_cx * f, fsl_id_t rid);
/**
   Inserts the given rid into the repo.phantom table.
*/
int fsl__phantom_rid_add(fsl_cx * f, fsl_id_t rid);
/**
   Inserts the given rid into the repo.unsent table.
*/
int fsl__unsent_rid_add(fsl_cx * f, fsl_id_t rid);
/**
   Replaces the repo.delta entry with the given rid. This does not
   manipulate the related blobs in any way.
*/
int fsl__delta_replace(fsl_cx * f, fsl_id_t rid, fsl_id_t srcid);
/**
   Replaces the repo.delta entry with the given rid. This does not
   manipulate the related blobs in any way.
*/
int fsl__delta_delete(fsl_cx * f, fsl_id_t rid);

/**
   Expects zTable to name a table with an rid field. That record
   is deleted.
*/
int fsl__rid_delete(fsl_cx * f, fsl_dbrole_e dbRole,
                    char const *zTable, fsl_id_t rid);

/** @internal

   Currently disabled (always returns 0) pending resolution of a
   "wha???" result from one of the underlying queries.

   Queues up the given artifact for a search index update. This is
   only intended to be called from crosslinking steps and similar
   content updates. Returns 0 on success.

   The final argument is intended only for wiki titles (the L-card of
   a wiki post).

   If the repository database has no search index or the given content
   is marked as private, this function returns 0 and makes no changes
   to the db.
*/
int fsl__search_doc_touch(fsl_cx * f, fsl_satype_e saType,
                         fsl_id_t rid, const char * docName);

/** @internal

   Returns true if the given file name is a reserved filename
   (case-insensitive) on Windows platforms, else returns false.

   zPath must be a canonical path with forward-slash directory
   separators. nameLen is the length of zPath. If negative, fsl_strlen()
   is used to determine its length.
*/
bool fsl__is_reserved_fn_windows(const char *zPath, fsl_int_t nameLen);

/** @internal

   Modes for fsl__ckout_clear_merge_state(), describing the caller's
   intent so that the checkout-level merge markers (vmerge.id<=0:
   merge, cherry-pick, backout, integrate) are only discarded when the
   user has plausibly abandoned them.
*/
enum fsl__ckout_merge_clear_e {
/**
   Partial wipe for state-refresh scans (fsl_vfile_changes_scan()):
   clears per-file merge state (vmerge.id>0) for unchanged files but
   never removes the checkout-level markers. A scan performed on
   behalf of some other operation must not unilaterally decide that a
   pending merge has been abandoned. fossil(1)'s scan never touches
   vmerge.
*/
FSL__MERGE_CLEAR_SCAN = 0,
/**
   Unconditionally wipes all vmerge state. For use once a commit has
   consumed the merge state or a checkout/update has invalidated it.
*/
FSL__MERGE_CLEAR_ALL = 1,
/**
   Like FSL__MERGE_CLEAR_SCAN except that cherry-pick/backout markers
   may also be swept once no vfile entry shows active merge
   involvement (chnged>1) and no per-file merge state remains. For
   use by explicit-abandonment operations (fsl_ckout_revert()), where
   the user reverting the merged file's changes is the signal that
   the pending cherry-pick/backout is being abandoned.
*/
FSL__MERGE_CLEAR_REVERT = 2
};

/** @internal

   Clears pending merge state from the f's checkout db's vmerge
   table, as described for the given fsl__ckout_merge_clear_e mode.
   Returns 0 on success, non-0 on db error.
*/
int fsl__ckout_clear_merge_state( fsl_cx * f,
                                  enum fsl__ckout_merge_clear_e mode );

/** @internal

   Installs or reinstalls the checkout database schema into f's open
   checkout db. Returns 0 on success, FSL_RC_NOT_A_CKOUT if f has
   no opened checkout, or an code if a lower-level operation fails.

   If dropIfExists is true then all affected tables are dropped
   beforehand if they exist. "It's the only way to be sure."

   If dropIfExists is false and the schema appears to already exists
   (without actually validating its validity), 0 is returned.
*/
int fsl__ckout_install_schema(fsl_cx * f, bool dropIfExists);

/** @internal

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

   The second argument must be the canonicalized absolute path to some
   directory under the checkout root. The contents of the buffer may,
   for efficiency's sake, be modified by this routine as it traverses
   the directory tree. It will never grow the buffer but may mutate
   its memory's contents.

   Returns the number of directories it is able to remove.

   Results are undefined if tgtDir is not an absolute path rooted in
   f's current checkout.

   There are any number of valid reasons removal of a directory might
   fail, and this routine stops at the first one which does.
*/
unsigned int fsl__ckout_rm_empty_dirs(fsl_cx * f,
                                      fsl_b const * tgtDir);

/** @internal

   This is intended to be passed the name of a file which was just
   deleted and "might" have left behind an empty directory. The name
   _must_ an absolute path based in f's current checkout. This routine
   uses fsl_file_dirpart() to strip path components from the string
   and remove directories until either removing one fails or the top
   of the checkout is reached. Since removal of a directory can fail for
   any given reason, this routine ignores such errors. It returns 0 on
   success, FSL_RC_OOM if allocation of the working buffer for the
   filename hackery fails, and FSL_RC_MISUSE if zFilename is not
   rooted in the checkout (in which case it may assert(), so don't do
   that).

   @see fsl_is_rooted_in_ckout()
   @see fsl_rm_empty_dirs()
*/
int fsl__ckout_rm_empty_dirs_for_file(fsl_cx * f, char const *zAbsPath);

/** @internal

    If f->cache.seenDeltaManifest<=0 then this routine sets it to 1
    and sets the 'seen-delta-manifest' repository config setting to 1,
    else this has no side effects. Returns 0 on success, non-0 if
    there is an error while writing to the repository config.
*/
int fsl__cx_update_seen_delta_deck(fsl_cx * f);

/** @internal

   Very, VERY internal.

   Returns the next available buffer from f->scratchpads. Fatally
   aborts if there are no free buffers because "that should not
   happen."  Calling this obligates the caller to eventually pass
   its result to fsl__cx_scratchpad_yield().

   This function guarantees the returned buffer's 'used' member will be
   set to 0.

   Maintenance note: the number of buffers is hard-coded in the
   fsl_cx::scratchpads anonymous struct.
*/
fsl_b * fsl__cx_scratchpad(fsl_cx * f);

/** @internal

   Very, VERY internal.

   "Yields" a buffer which was returned from fsl__cx_scratchpad(),
   making it available for re-use. The caller must treat the buffer as
   if this routine frees it: using the buffer after having passed it
   to this function will internally be flagged as explicit misuse and
   will lead to a fatal crash the next time that buffer is fetched via
   fsl__cx_scratchpad(). So don't do that.
*/
void fsl__cx_scratchpad_yield(fsl_cx * f, fsl_b * b);

/** @internal

   Run automatically by fsl_deck_save(), so it needn't normally be run
   aside from that, at least not from average client code.

   Runs postprocessing on the Structural Artifact represented by
   d. d->f must be set, d->rid must be set and valid and d's contents
   must accurately represent the stored manifest for the given
   rid. This is normally run just after the insertion of a new
   manifest, but is sometimes also run after reading a deck from the
   database (in order to rebuild all db relations and add/update the
   timeline entry).

   Returns 0 on succes, FSL_RC_MISUSE !d->f, FSL_RC_RANGE if
   d->rid<=0, FSL_RC_MISUSE (with more error info in f) if d does not
   contain all required cards for its d->type value. It may return
   various other codes from the many routines it delegates work to.

   Crosslinking of ticket artifacts is currently (2021-11 resp.
   2026-09) only partially implemented.

   Design note: d "really should" be const here but some internals
   (d->F.cursor and delayed baseline loading) prohibit it.

   @see fsl__deck_crosslink_one()
*/
int fsl__deck_crosslink( fsl_deck /* const */ * d );

/** @internal

   Run automatically by fsl_deck_save(), so it needn't normally be run
   aside from that, at least not from average client code.

   This is a convience form of crosslinking which must only be used
   when a single deck (and only a single deck) is to be crosslinked.
   This function wraps the crosslinking in fsl_crosslink_begin()
   and fsl__crosslink_end(), but otherwise behaves the same as
   fsl__deck_crosslink(). If crosslinking fails, any in-progress
   transaction will be flagged as failed.

   Returns 0 on success.
*/
int fsl__deck_crosslink_one( fsl_deck * d );

/** @internal

   Checks whether the given filename is "safe" for writing to within
   f's current checkout.

   zFilename must be in canonical form: only '/' directory separators.
   If zFilename is not absolute, it is assumed to be relative to the top
   of the current checkout, else it must point to a file under the current
   checkout.

   Checks made on the filename include:

   - It must refer to a file under the current checkout.

   - Ensure that each directory listed in the file's path is actually
   a directory, and fail if any part other than the final one is a
   non-directory.

   If the name refers to something not (yet) in the filesystem, that
   is not considered an error.

   Returns 0 on success. On error f's error state is updated with
   information about the problem.
*/
int fsl__ckout_safe_file_check(fsl_cx * f, char const * zFilename);

/**
   Starts recording undo state for an operation (see undo.c and
   undo.h) labeled zLabel, or, if zLabel is NULL, suppresses
   recording for the duration of an operation. If another operation
   is already recording (or suppressing) on f's connection, this does
   nothing. *owner is set to true if this call started it, and the
   caller must then pass the operation's result and owner to
   fsl__undo_end(). Returns 0 on success.
*/
int fsl__undo_begin(fsl_cx * const f, char const * zLabel,
                    bool * const owner);

/**
   Finishes what fsl__undo_begin() started: if rc is 0 and the
   operation recorded, its record becomes the one fsl_undo() uses;
   otherwise the record in progress is dropped. Returns rc if it is
   non-0, else the result of finishing.
*/
int fsl__undo_end(fsl_cx * const f, int rc, bool owner);

/**
   If an operation is recording undo state, saves a copy of stash
   stashId (or all stashes if it is negative), which the operation is
   about to remove, so that undo can put it back. Returns 0 on
   success.
*/
int fsl__undo_keep_stash(fsl_cx * const f, fsl_id_t stashId);

/** @internal
   Creates zLinkFile as a symlink to zTgtFile, as fossil(1)'s
   symlink_create() does: a real symlink if f's 'allow-symlinks'
   setting is on and the platform and f's checkout filesystem support
   them, else a regular file holding the single line zTgtFile (which
   is how fossil manages symlinks on Windows and, since late 2020,
   by default). Whatever was at zLinkFile is removed first, so this
   never writes through an existing symlink.

   zLinkFile may be an absolute path rooted at f's current checkout or
   may be a checkout-relative path.

   Returns 0 on success, non-0 on error:

   - FSL_RC_NOT_A_CKOUT if f has no opened checkout.

   - FSL_RC_RANGE if zLinkFile is an absolute path outside of the
   current checkout.

   - FSL_RC_OOM on allocation error.

   - The result of fsl__cfs_symlink_create() if creating zLinkFile
   fails, in which case f's error state names the file.
*/
int fsl__ckout_symlink_create(fsl_cx * f, char const *zTgtFile,
                              char const * zLinkFile);


/** @internal
   Compute all file name changes that occur going from check-in iFrom
   to check-in iTo. Requires an opened repository.

   If revOK is true, the algorithm is free to move backwards in the
   chain. This is the opposite of the oneWayOnly parameter for
   fsl_vpath_shortest().

   On success, the number of name changes is written into *pnChng.
   For each name change, two integers are allocated for *piChng. The
   first is the filename.fnid for the original name as seen in
   check-in iFrom and the second is for new name as it is used in
   check-in iTo. If *pnChng is 0 then *aiChng will be NULL.

   On error returns non-0, pnChng and aiChng are not modified, and
   f's error state might (depending on the error) contain a description
   of the problem.

   Space to hold *aiChng is obtained from fsl_malloc() and must
   be released by the caller.
*/
int fsl__find_filename_changes(fsl_cx * f,
                               fsl_id_t iFrom,
                               fsl_id_t iTo,
                               bool revOK,
                               uint32_t *pnChng,
                               fsl_id_t **aiChng);

/**  @internal
   Bitmask of file change types for use with
   fsl__is_locally_modified().
*/
enum fsl__localmod_e {
/** Sentinel value. */
FSL__LOCALMOD_NONE = 0,
/**
   Permissions changed.
*/
FSL__LOCALMOD_PERM = 0x01,
/**
   File size or hash (i.e. content) differ.
*/
FSL__LOCALMOD_CONTENT = 0x02,
/**
   The file type was switched between symlink and normal file.  In
   this case, no check for content change, beyond the file size
   change, is performed.
*/
FSL__LOCALMOD_LINK = 0x04,
/**
   File was not found in the local checkout.
 */
FSL__LOCALMOD_NOTFOUND = 0x10
};
typedef enum fsl__localmod_e fsl__localmod_e;
/** @internal

   Checks whether the given file has been locally modified compared to
   a known size, hash value, and permissions. Requires that f has an
   opened checkout.

   If zFilename is not an absolute path, it is assumed to be relative
   to the checkout root (as opposed to the current directory) and is
   canonicalized into an absolute path for purposes of this function.

   fileSize is the "original" version's file size.  zOrigHash is the
   initial hash of the file to use as a basis for comparison.
   zOrigHashLen is the length of zOrigHash, or a negative value if
   this function should use fsl_is_uuid() to determine the length. If
   the hash length is not that of one of the supported hash types,
   FSL_RC_RANGE is returned and f's error state is updated. This
   length is used to determine which hash to use for the comparison.

   If the file's current size differs from the given size, it is
   quickly considered modified, otherwise the file's contents get
   hashed and compared to zOrigHash.

   Because this is used for comparing local files to their state from
   the fossil database, where files have no timestamps, the local
   file's timestamp is never considered for purposes of modification
   checking.

   If isModified is not NULL then on success it is set to a bitmask of
   values from the fsl__localmod_e enum specifying the type(s) of
   change(s) detected:

   - FSL__LOCALMOD_PERM = permissions changed.

   - FSL__LOCALMOD_CONTENT = file size or hash (i.e. content) differ.

   - FSL__LOCALMOD_LINK = the file type was switched between symlink
     and normal file. In this case, no check for content change,
     beyond the file size change, is performed.

   - FSL__LOCALMOD_NOFOUND = file was not found in the local checkout.

   Noting that:

   - Combined values of (FSL__LOCALMOD_PERM | FSL__LOCALMOD_CONTENT) are
   possible, but FSL__LOCALMOD_NOTFOUND will never be combined with one
   of the other values.

   If stat() fails for any reason other than file-not-found
   (e.g. permissions), an error is triggered.

   Returns 0 on success. On error, returns non-0 and f's error state
   will be updated and isModified...  isNotModified. Errors include,
   but are not limited to:

   - Invalid hash length: FSL_RC_RANGE
   - f has no opened checkout: FSL_RC_NOT_A_CKOUT
   - Cannot find the file: FSL_RC_NOT_FOUND
   - Error accessing the file: FSL_RC_ACCESS
   - Allocation error: FSL_RC_OOM
   - I/O error during hashing: FSL_RC_IO

   And potentially other errors, roughly translated from errno values,
   for corner cases such as passing a directory name instead of a
   file.

   Results are undefined if any pointer argument is NULL or invalid.

   This function currently does NOT follow symlinks for purposes of
   resolving zFilename, but that behavior may change in the future or
   may become dependent on the repository's 'allow-symlinks' setting.

   Internal detail, not relevant for clients: this updates f's
   cache stat entry.
*/
int fsl__is_locally_modified(fsl_cx * f,
                            const char * zFilename,
                            fsl_size_t fileSize,
                            const char * zOrigHash,
                            fsl_int_t zOrigHashLen,
                            fsl_fileperm_e origPerm,
                            int * isModified);

/** @internal

   This routine cleans up the state of selected cards in the given
   deck. The 2nd argument is an list of upper-case letters
   representing the cards which should be cleaned up, e.g. "ADG". If
   it is NULL, all cards are cleaned up but d has non-card state
   which is not cleaned up by this routine. Unknown letters are simply
   ignored.
*/
void fsl__deck_clean_cards(fsl_deck * d, char const * letters);

/** @internal

    This starts a transaction (possibly nested) on the repository db
    and initializes some temporary db state needed for the
    crosslinking certain artifact types. It "should" (see below) be
    called at the start of the crosslinking process. Crosslinking
    *can* work without this but certain steps for certain (subject to
    change) artifact types will be skipped, possibly leading to
    unexpected timeline data or similar funkiness. No permanent
    SCM-relevant state will be missing, but the timeline might not be
    updated and tickets might not be fully processed. This should be
    used before crosslinking any artifact types, but will only have
    significant side effects for certain (subject to change) types.

    Returns 0 on success.

    If it returns 0 then the caller is OBLIGATED to either 1) call
    fsl__crosslink_end() or 2) call fsl_db_txn_rollback() and
    set f->cache.isCrosslinking to false. This process may install
    temporary tables and/or triggers, so failing to call one or the
    other of those will result in misbehavior.

    @see fsl__deck_crosslink()
*/
int fsl__crosslink_begin(fsl_cx * f);

/** @internal

    Must not be called unless fsl__crosslink_begin() has
    succeeded. This performs crosslink post-processing on certain
    artifact types and cleans up any temporary db state initialized by
    fsl__crosslink_begin().

    If the 2nd argument is not 0 then this routine triggers a rollback
    of the transaction started by fsl__crosslink_begin() and
    propagates any pending error code from f or (if f has no error
    code) from f's db handle.

    The second argument is intended to be the value of any pending
    result code (0 or otherwise) from any work done _after_
    fsl__crosslink_begin() succeeded. If passed 0, it assumes that
    there is no propagating error state and will attempt to complete
    the crosslinking process. If passed non-0, it triggers a rollback
    and unsets the f->cache.isCrosslinking flag, but does no
    additional work, then returns resultCode.

    Returns 0 on success. On error it initiates (or propagates) a
    rollback for the current transaction. If called when a rollback is
    pending, it unsets the crosslink-is-running flag and returns the
    propagating result code.
*/
int fsl__crosslink_end(fsl_cx * f, int resultCode);

/** @internal

   Installs the core timeline crosslink listeners. Defined in deck.c.
*/
int fsl__cx_install_timeline_crosslinkers(fsl_cx * const f);

/** @internal

   Searches the current repository database for a fingerprint and
   returns it as a string in *zOut.

   If rcvid<=0 then the fingerprint matches the last entry in the
   [rcvfrom] table, where "last" means highest-numbered rcvid (as
   opposed to most recent mtime, for whatever reason). If rcvid>0 then
   it searches for an exact match.

   Returns 0 on non-error. Finding no matching rcvid results in
   FSL_RC_NOT_FOUND. If 0 is returned then *zOut will be non-NULL and
   ownership of that value is transferred to the caller, who must
   eventually pass it to fsl_free(). On error, *zOut is not modified.

   Returns FSL_RC_NOT_A_REPO if f has no opened repository, FSL_RC_OOM
   on allocation error, or any number of potential db-related codes if
   something goes wrong at the db level.

   This API internally first checks for "version 1" fossil
   fingerprints and falls back to "version 0" fingerprint if a v1
   fingerprint is not found. Version 0 was very short-lived and is not
   expected to be in many repositories which are accessed via this
   library. Practice has, however, revealed some.

   @see fsl_ckout_fingerprint_check()
*/
int fsl__repo_fingerprint_search(fsl_cx * f, fsl_id_t rcvid,
                                 char ** zOut);
/**
   When a record is converted from a phantom to a real record, if that
   record has other records that are derived by delta, then call
   fsl__deck_crosslink() on those other records.

   If the formerly phantom record or any of the other records derived
   by delta from the former phantom are a baseline manifest, then also
   invoke fsl__deck_crosslink() on the delta-manifests associated with
   that baseline.

   Returns 0 on success, any number of non-0 results on error.

   The 3rd argument must always be 0 except in recursive
   calls to this function.
*/
int fsl__after_dephantomize(fsl_cx * f, fsl_id_t rid, bool tryCrosslink);

/** @internal

   Returns true if rid's content can be reconstructed: it is not a
   phantom and no delta in its chain is based on a phantom. The
   counterpart of fossil(1)'s content_is_available().
*/
bool fsl__content_is_available(fsl_cx * f, fsl_id_t rid);

/** @internal

   State for running a raw diff.

   @see fsl__diff_all()
*/
struct fsl__diff_cx {
  /**
     aEdit 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. The array is terminated with a triple of (0,0,0).
  */
  int *aEdit /*TODO unsigned*/;
  /** Number of integers (3x num of triples) in aEdit[]. */
  int nEdit /*TODO unsigned*/;
  /** Number of elements allocated for aEdit[]. */
  int nEditAlloc /*TODO unsigned*/;
  /** File content for the left side of the diff. */
  fsl_dline *aFrom;
  /** Number of lines in aFrom[]. */
  int nFrom /*TODO unsigned*/;
  /** File content for the right side of the diff. */
  fsl_dline *aTo;
  /** Number of lines in aTo[]. */
  int nTo /*TODO unsigned*/;
  /** Predicate for comparing LHS/RHS lines for equivalence. */
  int (*cmpLine)(const fsl_dline * const, const fsl_dline *const);
};
/** @internal
   Convenience typeef.
*/
typedef struct fsl__diff_cx fsl__diff_cx;
/** @internal
    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 \
}
/** @internal
   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 * p);

/** @internal */
void fsl__diff_cx_clean(fsl__diff_cx * cx);



/** @internal

    Undocumented. For internal debugging only. The 2nd argument is
    intended to be __FILE__ and the 3rd is intended to be __LINE__.
*/
void fsl__dump_triples(fsl__diff_cx const * p,
                       char const * zFile, int ln );

/** @internal

    Removes from the BLOB table all artifacts that are in the SHUN
    table. Returns 0 on success. Requires (asserts) that a repo is
    opened. Note that this is not a simple DELETE operation, as it
    requires ensuring that all removed blobs have been undeltified
    first so that no stale delta records are left behind.
*/
int fsl__shunned_remove(fsl_cx * f);

/** @internal

   This function is, as of this writing, only exposed via a header file
   for the sake of fnc, which still relies on it after we moved the
   "v1" diff code out of this library and into fnc.

   Attempt to shift insertion or deletion blocks so that they begin and
   end on lines that are pure whitespace.  In other words, try to transform
   this:

   ```
        int func1(int x){
           return x*10;
       +}
       +
       +int func2(int x){
       +   return x*20;
        }

        int func3(int x){
           return x/5;
        }
   ```

   Into one of these:

   ```
        int func1(int x){              int func1(int x){
           return x*10;                   return x*10;
        }                              }
       +
       +int func2(int x){             +int func2(int x){
       +   return x*20;               +   return x*20;
       +}                             +}
                                      +
        int func3(int x){              int func3(int x){
           return x/5;                    return x/5;
        }                              }
   ```
*/
void fsl__diff_optimize(fsl__diff_cx * p);

/** @internal

   This is a fossil-specific internal detail not needed by the more
   generic parts of the fsl_db API. It loops through all "cached"
   prepared statements for which stmt->role has been assigned a value
   which bitmasks as true against the given role and finalizes
   them. If such a statement is currently held by a call to/via
   fsl_db_prepare_cachedv() then this will NOT finalize that
   statement, will update db's error state, and return
   FSL_RC_MISUSE.

   Returns 0 on success.

   As a special case, if role==0 then ALL cached statements are
   closed, with the caveat that the process will still fail if any
   statement is currently flagged as active.
*/
int fsl__db_cached_clear_role(fsl_db * db, fsl_flag32_t role);

/** @internal

    Part of the crosslinking bits: rebuilds the entry for the ticket
    with the given K-card value.
*/
int fsl__ticket_rebuild(fsl_cx * f, char const * zTktId);

/** @internal

    Values for the srctype column of the repo.backlink table, which
    say what kind of artifact a link was found in. Their numeric values
    are shared with fossil(1) and must not change.
*/
enum fsl__bklnk_e {
/** A check-in comment. srcid is the check-in's rid. */
FSL_BKLNK_COMMENT = 0,
/** A ticket change. srcid is the rid of the ticket artifact. */
FSL_BKLNK_TICKET = 1,
/** A wiki page. srcid is the id of its "wiki-NAME" tag. */
FSL_BKLNK_WIKI = 2,
/** A technote. fossil(1) defines this but does not use it. */
FSL_BKLNK_EVENT = 3,
/** A forum post. srcid is the post's rid. */
FSL_BKLNK_FORUM = 4
};

/** @internal

    Markup languages which links can be extracted from, as parsed by
    fsl__backlink_mimetype().
*/
enum fsl__bklnk_mt_e {
/** No mimetype was specified. Treated like FSL_BKLNK_MT_WIKI. */
FSL_BKLNK_MT_NONE = 0,
/** Fossil wiki. */
FSL_BKLNK_MT_WIKI = 1,
/** Markdown. */
FSL_BKLNK_MT_MARKDOWN = 2,
/** Anything else. Nothing is extracted from it. */
FSL_BKLNK_MT_UNKNOWN = 3
};

/** @internal

    Transforms a mimetype string into one of the FSL_BKLNK_MT_xxx
    values. A NULL mimetype is FSL_BKLNK_MT_NONE. Port of fossil(1)'s
    parse_mimetype().
*/
int fsl__backlink_mimetype(char const * zMimetype);

/** @internal

    Callback type for fsl__backlink_scan(). It is called once for each
    hyperlink which targets an artifact, in the order the links appear
    in the text, with the link's target in canonical form: 4 to 64
    lower-case hex digits. If it returns non-0 then scanning stops and
    that code is returned from fsl__backlink_scan().
*/
typedef int (*fsl__backlink_f)(void * state, char const * zTarget);

/** @internal

    Scans zSrc, which must be NUL-terminated, for hyperlinks which look
    like references to artifacts and passes each to cb. The text is
    interpreted per the given FSL_BKLNK_MT_xxx value. If wikiHtml is
    true then, for the wiki mimetype, the text is taken to be HTML
    in which only [target] and [target|label] are interpreted, as for
    fossil(1)'s wiki-use-html setting. This does not touch the
    database. zSrc is not modified.

    Returns 0 on success, FSL_RC_OOM if allocation fails, or the first
    non-0 result of cb.

    Port of the scanning done by fossil(1)'s backlink_extract().
*/
int fsl__backlink_scan(char const * zSrc, int mimetype, bool wikiHtml,
                       fsl__backlink_f cb, void * cbState);

/** @internal

    Scans zSrc as per fsl__backlink_scan() and records each link in
    f's repository's backlink table as coming from the artifact of type
    srcType (one of FSL_BKLNK_xxx) with id srcId, with the time mtime
    (a Julian day). If replace is true then any links already recorded
    for that artifact are removed first, even if zSrc is NULL. Does
    nothing if the repository has no backlink table.

    Returns 0 on success, else a FSL_RC_xxx code with f's error state
    updated.

    Port of fossil(1)'s backlink_extract().
*/
int fsl__backlink_extract(fsl_cx * f, char const * zSrc, int mimetype,
                          fsl_id_t srcId, int srcType, double mtime,
                          bool replace);

/** @internal

    Replaces the links recorded for the wiki page named zWikiTitle with
    those in its latest version. Does nothing if there is no such page.

    Returns 0 on success, else a FSL_RC_xxx code with f's error state
    updated.

    Port of fossil(1)'s backlink_wiki_refresh().
*/
int fsl__backlink_wiki_refresh(fsl_cx * f, char const * zWikiTitle);

/** @internal

    Removes the links recorded for all of the artifacts of the ticket
    whose "tkt-UUID" tag has the id tagId, as the first step of
    recording them anew when the ticket is rebuilt. Does nothing if the
    repository has no backlink table.

    Returns 0 on success, else a FSL_RC_xxx code with f's error state
    updated.
*/
int fsl__backlink_ticket_reset(fsl_cx * f, fsl_id_t tagId);

/** @internal

   Calls all registered crosslink link listeners, passing each the
   given deck. Returns 0 if there are no listeners or if all return 0,
   else it propagates an error from a failed listener.

   This must only be called while crosslinking is underway.

   @see fsl_xlink_listener()
*/
int fsl__call_xlink_listeners(fsl_deck * d);

/** @internal

   Copies symlink zFrom to a new symlink or pseudo-symlink named
   zTo.

   If realLink is true and this is a non-Windows platform,
   symlink zFrom is copied to zTo.

   If realLink is false or this is a Windows platform them...

   - On Windows this has currently undesired, or at least, highly
     arguable, behavior (historical, inherited from fossil(1)), in
     that an empty file named zTo will be created. In fossil(1) this
     function's counterpart is (apparently) never called on Windows,
     so that behavior seems to be moot. It is, however, important that
     this library never call it on Windows.

   - On non-Windows, a pseudo-symlink will be created: the string
     zFrom will be written to a regular file named zTo. That is, the
     file zTo will hold, as its contents, what it would point to if
     it were a symlink.
*/
int fsl__symlink_copy(char const *zFrom, char const *zTo, bool realLink);

/** @internal

   Translates sqliteCode (or, if it's 0, sqlite3_errcode()) to an
   approximate FSL_RC_xxx match but treats SQLITE_ROW and SQLITE_DONE
   as non-errors (result code 0). If non-0 is returned db's error
   state is updated with the current sqlite3_errmsg() string.
*/
int fsl__db_errcode(fsl_db * db, int sqliteCode);

/** @internal

   Plug in fsl_cx-specific db functionality into the given db handle.
   This must only be passed the MAIN db handle for the context,
   immediately after opening that handle, before f->dbMain is
   assigned.

   This function has very limited applicability and various
   preconditions which are assert()ed.
*/
int fsl__cx_init_db(fsl_cx * f, fsl_db * db);

/**
   Undoes what fsl__cx_init_db() did to a borrowed db handle: removes
   f's SQL functions and modules and its "fsl_cx" client data.
*/
void fsl__cx_uninit_db(fsl_cx * const f, fsl_db * const db);

/**
   For a context bound to a host db handle: if the host has rolled
   back a transaction holding libfossil's writes since f last looked,
   clears f's caches, which may hold artifacts and RIDs which no
   longer exist. A host transaction can end without libfossil seeing
   it, and libfossil cannot use the connection's one rollback hook
   without displacing the host's, so libfossil keeps a marker row in
   TEMP.fsl_host_gen instead: TEMP tables roll back with the host's
   transaction. This is a no-op for other contexts. Returns 0 or a db
   error code.
*/
int fsl__cx_host_rollback_check(fsl_cx * const f);

/** @internal

    Attaches the given db file to f with the given role. This function "should"
    be static but we need it in repo.c when creating a new repository.

    This function has tightly-controlled preconditions which will assert
    if not met. r must be one of FSL_DBROLE_CKOUT or FSL_DBROLE_REPO.

    If createIfNotExists is true and zDbName does not exist in the
    filesystem, it is created before/as part of the OPEN or ATTACH. This is
    almost never desired, but is required for operations which create a
    repo (e.g. the aptly-named fsl_repo_create()) or a checkout db
    (e.g. fsl_repo_open_ckout()).
*/
int fsl__cx_attach_role(fsl_cx * f, const char *zDbName,
                        fsl_dbrole_e r, bool createIfNotExists);

/** @internal

    Returns one of f->{repo,ckout}.db 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);

/** @internal

    Frees/clears the non-db state of f->ckout.
*/
void fsl__cx_ckout_clear(fsl_cx * f);


/** @internal
   Register the "files of checkin" (fsl_foci) SQLite3 virtual table.
*/
int fsl__foci_register(fsl_cx * f, fsl_db * db);

/** @internal

    Maximum length of a line in a text file, in bytes. (2**15 = 32k)
*/
#define FSL__LINE_LENGTH_MASK_SZ  15

/** @internal

    Bitmask which, when AND-ed with a number, will result in the
    bottom FSL__LINE_LENGTH_MASK_SZ bits of that number.
*/
#define FSL__LINE_LENGTH_MASK     ((1<<FSL__LINE_LENGTH_MASK_SZ)-1)

/** @internal

    Internal impl of fsl_b_err(), implemented as a macro for
    efficiency's sake.
*/
#define fsl__buffer_err(B) (B)->errCode

//#if FSL_ENABLE_MUTEX
/** @internal

    If the lib is built with FSL_ENABLE_MUTEX, locks the library's
    global non-recursive mutex, which only guards a small amount of
    state. If the lib is not built with FSL_ENABLE_MUTEX, this is a
    no-op.
*/
void fsl__mutex_enter(void);

/** @internal

    If the lib is built with FSL_ENABLE_MUTEX, unlocks the library's
    global non-recursive mutex, else it's a no-op.

    May assert() that fsl__mutex_enter() has been called.
*/
void fsl__mutex_leave(void);

/** @internal

    Returns true if fsl__mutex_enter() is active, else false. Always
    returns true(!) in-single-threaded builds because that's how
    SQLite does it. This is only intended for use in assert() and the
    like - it must not be used for flow control.

    May assert() that fsl__mutex_enter() has been called.
*/
bool fsl__mutex_held(void);
//#else /* !FSL_ENABLE_MUTEX */
//#define fsl__mutex_held(X) ((void)(X),1)
//#define fsl__mutex_enter() (void)0
//#define fsl__mutex_leave() (void)0
//#endif
/** @internal

    Internal helper for parsing manifests and sync protocol lines.
    Holds the (mutable) content of a source file or input line and
    gets parsed and updated by fsl__tokenizer_next().
*/
struct fsl__tokenizer {
  /**
      First char of the next token.
  */
  unsigned char * z;
  /**
      One-past-the-end of the input.
  */
  unsigned char * zEnd;
  /**
      True if z points to the start of a new line.
  */
  bool atEol;
};
typedef struct fsl__tokenizer fsl__tokenizer;
#define fsl__tokenizer_empty_m {NULL,NULL,false}
extern const fsl__tokenizer fsl__tokenizer_empty;

/** @internal

   Returns a pointer to the next space-separated token in pIn. The
   token is zero-terminated.  Return NULL if there are no more tokens
   on the current line, but the call after that will return non-NULL
   unless we have reached the end of the input. If this function
   returns non-NULL then *pLen (which must not be NULL) is set to the
   byte length of the new token. Once the end of the input is reached,
   this function always returns NULL.

   A token is defined as a sequence of a non-whitespace (0x20),
   non-newline (0x0A) bytes. The input is modified, replacing
   spaces and newlines with a NUL.
*/
unsigned char *fsl__tokenizer_next(fsl__tokenizer * pIn,
                                   fsl_size_t * pLen);

enum {
  /**
     Max number of expected tokens in fsl_xfer::line.  This number is
     inherited from fossil(1).
  */
  fsl__xfer_max_tokens = 6
};

/** @internal

   Internal state for an ongoing fsl_sync(). Modelled largely after
   fossil(1)'s xfer.c:Xfer class.
*/
struct fsl_xfer {
  /**
     This object's fossil context. Errors encountered by the channel
     should be sent here using fsl_xfer_error() and friends. A channel's
     impl may use the context for other purposes, e.g. fetching or
     storing channel-specific configuration info like credentials or
     using a db-side cache.

     f must outlive this object.
  */
  fsl_cx * f;

  /**
     The underlying communication channel.
  */
  fsl_sc * ch;

  /**
     The configuration object for a given xfer trip. Its initial state
     represents the initial request parameters and it may get updated
     as the sync progresses.
  */
  fsl_xfer_config * config;

  /**
     Almost all APIs which deal with this class (A) become no-ops if
     this is non-0, returning this value instead, and (B) set their
     result code in this member. This simplifies some internals by
     allowing us to forego explicit error checks when making multiple
     xfer-related calls in a row.
  */
  int rc;

  /** One line of sync protocol input, which we tokenize via
      fsl__xfer_readln() for ease of processing. */
  struct {
    /**
       Holds the current input line. Populated and tokenized by
       fsl__xfer_readln().
    */
    fsl_b b;
    /**
       A raw, untokenized copy of b.
    */
    fsl_b bRaw;
    /** Holds pointers to the individual tokens of b.
        The memory lives in this->b. These are non-const
        only so that we can use fsl_bytes_defossilize()
        on them. */
    unsigned char * aToken[fsl__xfer_max_tokens];
    /**
       Holds the strlen() of each token in aTokens.
    */
    fsl_size_t aTokLen[fsl__xfer_max_tokens];
    /** The number of tokens in use in aToken. */
    uint8_t nToken;
  } line;
  /** Memory buffers */
  struct {
    /**
       When using compressed responses, this is where it will store
       the uncompressed response. We decompress it on behalf of the
       fsl_sc so that those impls don't have to all do this on their
       own.
    */
    fsl_b uresp;
    /** Hashing and UUID-fetching buffer */
    fsl_b hash;
    /** Generic scratchpad buffer */
    fsl_b scratch;
    /** Card payloads */
    fsl_b cardPayload;
  } buf;
  /** Prepared statements */
  struct {
    fsl_stmt igotInsert;
    fsl_stmt igotHasRid;
    fsl_stmt gimmeInsert;
    //fsl_stmt gimmeDelete;
    fsl_stmt remoteUnkUuid;
  } q;
  /** Various flags. */
  /* TODO: move some of this into fsl_xfer_config. */
  struct {
    unsigned configRcvMask;
    unsigned configSendMask;
    /** True once a reqconfig card has been queued, so that we ask
        exactly once and know not to end a clone before asking. */
    bool configReqSent;
    char const *zAltPCode;
    /** True to enable syncing private content */
    bool syncPrivate;
    /** If true, next "file" received is a private artifact. */
    bool nextIsPrivate;
    /** True if the current error came from the contents of a reply
        (an error card, a card that could not be handled, or a body
        that did not match its headers) rather than from local storage
        or memory. fsl__xfer_client_run() records the first such error
        in replyErr and goes on (or, in the first clone reply, ignores
        it), and this is set again if the session ends with a reply
        error. fsl_sync_client() then keeps what was received. */
    bool peerError;
    /** True if the current error must end the session and keep
        nothing received, e.g. a received file or cfile which did not
        match its hash (sync draft section 10.1). Never a peerError. */
    bool fatalError;
    /** True if fsl_sync_client() opened the outermost transaction,
        i.e. its caller had none open. Only then can a round give
        the write lock back during the exchange. */
    bool ownsTxn;
  } flag;
  /** RIDs gimme'd in the pending request, so that
      fsl__xfer_request_phantoms() does not ask twice. */
  fsl_id_bag gimmePending;
  /** RIDs of private artifacts the peer asked for, without private
      sync in effect, to be answered with "igot HASH 1" in the next
      request (sync draft section 8.6). */
  fsl_id_bag privateIgot;
  /** RIDs from the unsent table which the pending request pushes.
      Their unsent rows are deleted in the transaction which
      processes the reply, so that a failed exchange leaves them
      queued. */
  fsl_id_bag unsentPending;
  /** RIDs crosslinked so far by fsl__xfer_crosslink_rcvd(). */
  fsl_id_bag xlinked;
  /** The first reply error (see flag.peerError) of a sync session,
      which becomes the session's result unless a fatal or local
      error ends the session first. */
  fsl_error replyErr;
  /** Info about the remote. */
  struct {
    int releaseVersion;
    int manifestDate;
    int manifestTime;
    /** Seconds of offset from localhost. */
    int clockSkewSeen;
    /* Reminder to self: calculating the clock skew currently requires
       parsing a comment line from the sync protocol. TODO is add a
       pragma to simplify that on the remote end. */
  } remote;
  struct {
    int number;
    int date;
    int time;
    /**
       Tells us whether the remote project-code matches this one.
       If not, some operations won't work (like logging in - that
       only works when project codes match because the project code
       is part of the password hash).

       Values: <0=unknown, 0=mismatch, >0=match.
    */
    short projCodeMatch;
  } clientVersion;
  struct {
    int protocolVersion;
    fsl_size_t seqNo;
    /** True if the most recent reply held a well-formed push card.
        A modern (protocol 2+) clone asks for more only if it did
        (sync draft section 8.2). */
    bool pushSeen;
  } clone;
  /**
     Info about the user which is relevant for sync.
  */
  struct {
    /**
       User name memory owned by fsl_xfer::url.
    */
    char const * name;
    /**
       Password memory owned by fsl_xfer::url.
    */
    char const * password;
    /**
       Password memory owned by this object. Gets extracted from the
       repo.user table if no password is otherwise provided.
    */
    char * passwordToFree;

    /**
       Permissions calculated for the current user from sync login
       info.
    */
    fsl_uperm perm;
  } user;
  /**
     When using compressed responses, we need a layer of buffer to do
     the decompression. This object, if populated, is a _partial_
     fsl_sc implementation which buffers the whole uncompressed
     response and only supports reading.
  */
  fsl_sc chz;
  /** Various counters. */
  fsl_xfer_metrics n;

  struct {
    /**
       Hash of all request payload content, for generating the sync
       login card.
    */
    fsl_sha1_cx sha1;
    fsl_b loginCard;
    /**
       Number of bytes submitted for the request body, before any
       compression.
    */
    fsl_size_t nBytes;
    /**
       For a compressed request (FSL_SC_F_COMPRESSED): the body being
       built. It is compressed and handed to the channel only when the
       request is complete, because the compressed container leads with
       the uncompressed length and Content-Length must give the
       compressed one (draft-fossil-sync-protocol-00 section 4.1).
    */
    fsl_b body;
  } request;

  struct {
    int httpVersion;
    int httpCode;
  } response;
#if 0
  /* From fossil(1) xfer.c:Xfer struct: */
  fsl_size_t mxSend;         /* Stop sending "file" when pOut reaches this size */
  int resync;         /* Send igot cards for all holdings */
  uint32_t remoteVersion;  /* Version of fossil running on the other side */
  uint32_t remoteDate;     /* Date for specific client software edition */
  uint32_t remoteTime;     /* Time of date correspoding on remoteDate */
  fsl_time_t maxTime;     /* Time when this transfer should be finished */
#endif
};
/** Empty-initialized fsl_xfer instance, intended for copy
    initialization. */
extern const fsl_xfer fsl_xfer_empty;

/** @internal

   Initializes xf's core-most state. Defined, and documented, in
   xfer.c.
*/
int fsl__xfer_setup(fsl_cx * const f, fsl_xfer * const xf,
                    fsl_xfer_config * xc, fsl_sc * const channel);

/** @internal

   Create a child process running command "zCmd". *pfdIn gets
   assigned to the stdout from the child process. If zStdinFile is
   not NULL the child reads its stdin from that file and *ppOut is
   set to NULL; otherwise *ppOut is a FILE which becomes the child's
   stdin. On Unix zCmd runs through /bin/sh; on Windows it runs
   directly as a command line, without a shell. *pChildPid gets the
   child's id for fsl__pclose2().

   On success the values returned via *pfdIn, *ppOut, and *pChildPid
   must be passed to fsl__pclose2() to properly clean up.

   Return 0 on success, non-0 on error.

   @internal
*/
int fsl__popen2(const char *zCmd, const char *zStdinFile,
                int *pfdIn, FILE **ppOut, int *pChildPid);

/** @internal

   Close the connection to a child process previously created using
   fsl__popen2(). All 3 arguments are assumed to values returned via
   fsl__popen2()'s output parameters: the input file descriptor,
   output FILE handle, and child process PID.

   Blocks until the child exits. Returns the child's exit status, or
   (on Unix) the negated number of the signal which ended it, or 0 if
   its status cannot be determined.
*/
int fsl__pclose2(int fdIn, FILE *pOut, int childPid);


/** @internal

   Hash value for fsl_xfcard card name hashing.

   This algo historically uses 32-bit hashes because the values
   (generated at build-time) were used in switch/case contexts, where
   64-bit values are not portable.

   @internal
*/
typedef uint32_t fsl_xfcard_hash_t;

/** @internal

   Objects for mapping known sync cards to their fsl_xfcard_e and
   hash of their name.
*/
struct fsl_xfcard {
  /** Card type ID. */
  const fsl_xfcard_e type;
  /** The protocol-level name of this card, e.g. "file" or "cfile". */
  char const * const name;
  /** A hash unique (in the context of fsl_xfcard) to this->name.
      Not const: fsl__xfcard_search() computes it on first use. */
  fsl_xfcard_hash_t hash;
};
typedef struct fsl_xfcard fsl_xfcard;

/** @internal

   Searches for a sync card with the given name. Returns a
   static/const instance of one on success, else NULL. This is a
   binary search ordered on the card names' hashes, so is fairly fast:
   hash z, binary search on that hash, and one fsl_strcmp() on a
   match.  The hash algo bails early if z is not shaped like a card
   name.

   Design note: this takes an unsigned string because its argument is
   invariably from fsl_xfer::line::aToken.
*/
fsl_xfcard const *fsl__xfcard_search(unsigned char const *z);
/** Non-unsigned-qualified C-string convenience form of fsl__xfcard_search(). */
#define fsl__xfcard_searchNU(WORD) fsl__xfcard_search((unsigned const char *)(WORD))

/** @internal

   An fgets() workalike which uses an unbuffered file descriptor for
   reading.

   Scans the input 1 byte at a time for a '\n', appending each read
   character to pOut, including the '\n' and a trailing NUL, up to a
   maximum of nOut-1 (to account for the NUL). If it hits EOF before
   finding a \n, that is not treated as an error, and downstream code
   may need to special-case that.

   On success it returns 0, sets *ppOut to pOut, and *pnOut to the
   number of bytes filled out in pOut. On error, returns FSL_RC_IO on
   read error or FSL_RC_RANGE if no newline is found before nOut bytes
   are read.

   If called when fdIn is at EOF, it will return 0 but set *pnOut to
   0.

   On error it will return either FSL_RC_RANGE (if it finds now
   newline before nOut bytes) or propagate an error from the read()
   call, in the form of another non-0 fsl_rc_e value.
*/
int fsl__fdgets(int fdIn, unsigned char * pOut, fsl_size_t nOut,
                char **ppOut, fsl_size_t * pnOut);

/** @internal

   fsl_file_tempname() proxy which uses fsl_temp_dirs_get() to get the
   target dir. zBaseName may be NULL but library routines are strongly
   enouraged to use a of "libfossil-PURPOSE", where PURPOSE is a
   descrtive identifier, e.g. "PopenRequest" or "popen-request".
*/
int fsl__tmpfile( fsl_b * tgt, char const * zBaseName );

/**
   If FSL_PLATFORM_IS_UNIX then this returns the result of chmod(2)
   for the given file name, converted from errno using
   fsl_errno_to_rc(). It uses permissions 0600.

   On other platforms this is a no-op and returns 0.
*/
int fsl__tmpchmod( char const * z );

// Potential TODO
//int fsl__tmpfile_open( char const * zBaseName, FILE **fOut );

/** @internal

   Searches the OS path zPath for a binary named zBinName. If found,
   it puts a library-allocated copy of the resolved name to *zOut
   (which the caller must eventually pass to fsl_free()) then returns
   0.

   If zPath is NULL, getenv("PATH") is used.

   On error, *zOut is not modified and non-0 is returned:

   - FSL_RC_NOT_FOUND if no match is found. This will also be returned
     if both zPath and $PATH are NULL.

   - FSL_RC_OOM on allocation error.

   On Windows platforms it will extend the search to include a ".exe"
   extension.
*/
int fsl__find_bin( char const *zPath, char const *zBinName, char **zOut );

/**
   If d->P.used then this makes d->P.list[0] a delta from d->rid, else
   this is a no-op. Returns non-0 if fetching the parent RID or
   deltification fail. Returns 0 if there's nothing to do or if what
   needs doing gets done.
*/
int fsl__deck_deltify_parent(fsl_deck * d);

/**
   Imports content to f's opened repository's BLOB table using a
   client-provided input source. f must have an opened repository
   db. inFunc is the source of the data and inState is the first
   argument passed to inFunc(). If inFunc() succeeds in fetching all
   data (i.e. if it always returns 0 when called by this function)
   then that data is inserted into the blob table _if_ no existing
   record with the same hash is already in the table. If such a record
   exists, it is assumed that the content is identical and this
   function has no side-effects vis-a-vis the db in that case.

   If rid is not NULL then the BLOB.RID record value (possibly of an
   older record!) is stored in *rid.  If uuid is not NULL then the
   BLOB.UUID record value is stored in *uuid and the caller takes
   ownership of those bytes, which must eventually be passed to
   fsl_free() to release them.

   rid and uuid are only modified on success and only if they are
   not NULL.

   Returns 0 on success, non-0 on error. For errors other than basic
   argument validation and OOM conditions, f's error state is
   updated with a description of the problem. Returns FSL_RC_MISUSE
   if either f or inFunc are NULL. Whether or not inState may be
   NULL depends on inFunc's concrete implementation.

   Be aware that BLOB.RID values can (but do not necessarily) change
   in the life of a repod db (via a reconstruct, a full re-clone, or
   similar, or simply when referring to different clones of the same
   repo). Thus clients should always store the full UUID, as opposed
   to the RID, for later reference. RIDs should, in general, be
   treated as session-transient values. That said, for purposes of
   linking tables in the db, the RID is used exclusively (clients are
   free to link their own extension tables using UUIDs, but doing so
   has a performance penalty comared to RIDs). For long-term storage
   of external links, and to guaranty that the data be usable with
   other copies of the same repo, the UUID is required.

   Note that Fossil may deltify, compress, or otherwise modify
   content on its way into the blob table, and it may even modify
   content long after its insertion (e.g. to make it a delta against
   a newer version). Thus clients should normally never try
   to read back the blob directly from the database, but should
   instead read it using fsl_content_get().

   That said: this routine has no way of associating and older version
   (if any) of the same content with this newly-imported version, and
   therefore cannot delta-compress the older version.

   Maintenance reminder: this is basically just a glorified form of
   the internal fsl__content_put(). Interestingly, fsl__content_put()
   always sets content to public (by default - the f object may
   override that later). It is not yet clear whether this routine
   needs to have a flag to set the blob private or not. Generally
   speaking, privacy is applied to fossil artifacts, as opposed to
   content blobs.

   @see fsl__repo_import_buffer()
*/
int fsl__repo_import_blob( fsl_cx * f, fsl_input_f inFunc,
                          void * inState, fsl_id_t * rid,
                          fsl_uuid_str * uuid );

/**
   A convenience form of fsl__repo_import_blob(), equivalent to:

   ```
   fsl__repo_import_blob(f, fsl_input_f_buffer, bIn, rid, uuid )
   ```

   except that (A) bIn is const in this call and non-const in the
   other form (due to cursor traversal requirements) and (B) it
   returns FSL_RC_MISUSE if bIn is NULL.
*/
int fsl__repo_import_buffer( fsl_cx * f, fsl_b const * bIn,
                            fsl_id_t * rid, fsl_uuid_str * uuid );

enum fsl__cx_stmt_e {
#define E(NAME,IGNORED) fsl__cx_stmt_e_ ## NAME,
  fsl__cx_cache_stmt_map(E)
#undef E
};

/**
   Returns the given cached statement object, preparing it if needed.
   If preparation fails then NULL is returned and f->error will
   hold the details.

   This function MUST NOT be used in routines may, perhaps indirectly,
   recurse. That is, the returned statement WILL misbehave if served
   twice by this function without an intervening fsl__cx_stmt_yield()
   between them.

   If this returns non-NULL then the caller is obligated to pass the
   same q object to fsl__cx_stmt_yield().
*/
fsl_stmt * fsl__cx_stmt(fsl_cx * f, enum fsl__cx_stmt_e which);

/**
   Must be passed all statement pointers obtained via fsl__cx_stmt().
   It MUST NOT be passed any statement from elsewhere except that
   q==NULL is permitted to simplify its usage. This resets the
   statement and clears any bindings.

   Callers must treat q as if this function finalizes it, i.e. they
   must not derefence any members or pass it to another API after
   this. It can only be legally used again after fetching it from
   fsl__cx_stmt().
*/
void fsl__cx_stmt_yield(fsl_cx * f, fsl_stmt * q);

/**
   Steps q for a row-iteration loop. If *rc is non-zero, returns false
   without stepping. On a row, returns true. On completion, returns
   false. On a step error, uplifts q's database error to f, stores the
   result in *rc, and returns false.
*/
static inline bool fsl__cx_stmt_step_each(fsl_cx * f, fsl_stmt * q,
                                          int *rc){
  int stepRc;
  if( *rc ) return false;
  stepRc = fsl_stmt_step(q);
  if( FSL_RC_STEP_ROW==stepRc ) return true;
  if( FSL_RC_STEP_DONE!=stepRc ){
    *rc = fsl_cx_uplift_db_error2(f, q->db, stepRc);
  }
  return false;
}

/**
    Clears various internal caches and resets various
    internally-cached values related to repository and checkout
    dbs. Its argument must be true if we're clearing caches as a
    result of a transaction commit, else false (i.e. a rollback is in
    process).
*/
void fsl__cx_caches_reset(fsl_cx * f, bool isTxnCommit);

/**
   May clear or reset cached data. This is intended to be called as
   part of a transaction commit/rollback hook and be passed true for a
   commit and false for a rollback.
*/
void fsl__cx_reset_for_txn(fsl_cx * f, bool isCommit);

/**
   Clears only caches which are relevant to content lookup.
*/
void fsl__cx_content_caches_clear(fsl_cx * f);

/**
   Clears the contents of f->cache.mcache.
*/
void fsl__cx_mcache_clear(fsl_cx * f);

/**
   An experiment.

   Runs BODY ( a {...} block) in the context of a fsl_cx savepoint.
   The body is expected to assign int-type RcVar to 0 on success and
   false on error. If RcVar is 0 when this is invoked, BODY is not
   run.  If BODY succeeds, the savepoint is saved if KeepSPOnSuccess
   is true, else it is silently discarded. If RollbackTopOnError is
   true then any outer savepoint is put into a persistent rollback
   state, else any outer savepoint is unaffected. If BODY succeeds but
   the commit/rollback fails, RcVar is set to that failure code.
*/
#define fsl__cx_txn(FslCx, RcVar, RollbackTopOnError, KeepSPOnSuccess, BODY) { \
    RcVar = fsl_cx_txn_begin(FslCx);                                \
    if( 0==RcVar ){                                                 \
      BODY                                                          \
    }                                                               \
    int const RcVar ## __ =                                         \
      fsl_cx_txn_end_v2((FslCx), (0==RcVar) && (KeepSPOnSuccess),   \
                        ((RollbackTopOnError) && (0!=RcVar)));      \
    if( !RcVar ) RcVar = RcVar ## __;                               \
  }

/**
   fsl__cx_txn() proxy for use with local savepoints which should not
   trigger a global savepoint rollback on error.
*/
#define fsl__cx_txn_local(FslCx, RcVar, KeepSPOnSuccess, BODY) \
    fsl__cx_txn(FslCx, RcVar, 0, KeepSPOnSuccess, BODY)

/**
   fsl__cx_txn() proxy for use with local savepoints which should
   trigger a global savepoint rollback on error.
*/
#define fsl__cx_txn_global(FslCx, RcVar, KeepSPOnSuccess, BODY) \
    fsl__cx_txn(FslCx, RcVar, 1, KeepSPOnSuccess, BODY)

void fsl__id_bag_dump(fsl_id_bag const * src, FILE *to/*NULL==stdout*/,
                      char const *zHeader);

/* fsl__ptl details are in cache.c */
int fsl__ptl_init(fsl__ptl * c, uint16_t prealloc);
void fsl__ptl_clear(fsl__ptl * c);
bool fsl__ptl_has(fsl__ptl const * c, fsl__ptl_e where, fsl_id_t rid);
int fsl__ptl_insert(fsl__ptl * c, fsl__ptl_e where, fsl_id_t rid);
bool fsl__ptl_remove(fsl__ptl const * c, fsl__ptl_e where, fsl_id_t rid);

/**
   Can fail with OOM if isCommit and f->cache.ptl.level>0.
*/
int fsl__cx_ptl_pop(fsl_cx * f, bool isCommit);
int fsl__cx_ptl_push(fsl_cx * f);
/**
   Returns the given bag for the current transaction level.  Never
   returns NULL unless "which" is invalid, in which case it prefers to
   fail fatally.
*/
fsl_id_bag * fsl__cx_ptl_bag(fsl_cx *f, fsl__ptl_e which);
/**
   Removes rid from the given PTL list.
*/
bool fsl__cx_ptl_remove(fsl_cx * f, fsl__ptl_e where, fsl_id_t rid);
#define fsl__cx_ptl_has(F,W,R) fsl__ptl_has(&(F)->cache.ptl, W, R)
#define fsl__cx_ptl_insert(F,W,R) fsl__ptl_insert(&(F)->cache.ptl, W, R)

/**
   Works like the public fsl_cx_b_borrow() but if honorErrorState
   is false then it will attempt to retrieve or allocate a buffer even
   if f->error is flagged as having an allocation error.
*/
fsl_b * fsl__cx_buffer_borrow(fsl_cx *f, bool honorErrorState);

/**
   Sets *rid to f->db.ckout.rid, fetching the latter if
   needed. Returns non-0 if fetching fails.
*/
int fsl__ckout_rid(fsl_cx * f, fsl_id_t *rid);

/**
   Passed dest to fsl_xfer_config_cleanup() then bitwise copies src to
   dest and rewires some memory to avoid duplicate frees and the like:

   dest->url points to src->url's memory, but as an "external"
   buffer. src must outlive dest.

   dest->debug.b is zeroed out.

   This is intended for making call-local copies.
*/
void fsl__xfer_config_almost_copy(fsl_xfer_config const *src,
                                  fsl_xfer_config *dest);


/**
   Functionally identical to fsl_deck_B_set() except that it sets
   the R-card. Returns 0 on succes, FSL_RC_SYNTAX if md5 is neither
   NULL nor exactly FSL_STRLEN_MD5 hexadecimal digits (not including
   trailing NUL). If md5==NULL the current R value is cleared.

   It would be highly unusual to have to set the R-card manually,
   as its calculation is quite intricate/intensive. See
   fsl_deck_R_calc() and fsl_deck_unshuffle() for details
*/
int fsl__deck_R_set( fsl_deck * mf, char const *md5);

#if !defined(NDEBUG)
/**
   A place to put a breakpoint to help trace down errors. Pass it the
   rc of a just-failed operation and set a breakpoint in the if(rc)
   block of this function in fsl.c. Returns its argument.
*/
int fsl__bprc(int rc);
#else
#define fsl__bprc(X) (X)
#endif

/** @internal

   The fsl__cfs_xxx() functions are the checkout code's file
   operations. Each does the same as the public function it is named
   after, through f's checkout file storage (fsl_cx_ckout_fs()), which
   is fsl_ckout_fs_os, the filesystem, unless another is installed.

   - fsl__cfs_stat(): fsl_stat()
   - fsl__cfs_size(): fsl_file_size()
   - fsl__cfs_mtime(): fsl_file_mtime()
   - fsl__cfs_is_file(): fsl_is_file()
   - fsl__cfs_is_file_or_link(): fsl_is_file_or_link()
   - fsl__cfs_is_symlink(): fsl_is_symlink(); always false for a
     storage with no symlinks
   - fsl__cfs_isexec(): fsl_file_isexec()
   - fsl__cfs_dir_check(): fsl_dir_check()
   - fsl__cfs_dir_is_empty(): fsl_dir_is_empty()
   - fsl__cfs_read(): fsl_b_fill_from_filename()
   - fsl__cfs_write(): fsl_b_to_filename()
   - fsl__cfs_unlink(): fsl_file_unlink()
   - fsl__cfs_rename(): fsl_file_rename()
   - fsl__cfs_rmdir(): fsl_rmdir()
   - fsl__cfs_mkdir_for_file(): fsl_mkdir_for_file()
   - fsl__cfs_exec_set(): fsl_file_exec_set()
   - fsl__cfs_mtime_set(): fsl_file_mtime_set()
   - fsl__cfs_copy(): fsl_file_copy()
   - fsl__cfs_sha1sum(): fsl_sha1sum_filename()
   - fsl__cfs_sha3sum(): fsl_sha3sum_filename()
   - fsl__cfs_dircrawl(): fsl_dircrawl()
   - fsl__cfs_symlink_read(): fsl_symlink_read(); for a storage with
     no symlinks, reads the file holding the link's target
   - fsl__cfs_symlink_create(): fsl_symlink_create(); for a storage
     with no symlinks, realLink is ignored and the target is written
     as a file
   - fsl__cfs_symlink_copy(): fsl_symlink_copy(), likewise

   And one with no fs.c counterpart:

   - fsl__cfs_write_blob(): writes blob rid's content to file zName
     through the storage's xWriteBlob() if it has one, else does what
     the checkout code did before it existed: fsl_content_get() into
     *content (skipped if loaded is true: content already holds the
     blob), then fsl__cfs_write(). content is the caller's scratch
     buffer, which holds the blob afterwards only in the second case
     (content->used is 0 otherwise, if it was on entry). If
     pWriteFailed is not NULL, it is set to whether a failure came
     from the write (xWriteBlob() or xWrite()) rather than from
     fsl_content_get(), whose error state is set by it: the caller
     adds context to a write failure, as it did around
     fsl__cfs_write(). Creating the directory, the executable bit and
     mtime stay the caller's, as around fsl__cfs_write().
*/

/** @internal

   The libfossil contexts (fsl_cx) using one db connection: a host's
   connection (fsl_cx_host_db()) can carry several, and a connection
   of the library's own has exactly one. It is the connection's
   "fsl_cxreg" client data, which owns it. The SQL functions which need
   a context get it from here (fsl__cx_for_dbh()), as no function can
   be told about more than one.
*/
typedef struct fsl__cxreg fsl__cxreg;
struct fsl__cxreg {
  /**
     The context whose statement is being stepped, set around each
     sqlite3_step() by the fsl_db functions on a shared connection,
     or NULL outside of them.
  */
  fsl_cx * cur;
  /**
     The context the host's own SQL gets (fsl__cx_for_dbh()) when no
     library statement is stepping, if set (fsl__cxreg_default_set()),
     else the first to join.
  */
  fsl_cx * dflt;
  /** The contexts, in the order they joined. */
  fsl_cx ** a;
  unsigned n;
  unsigned cap;
  /** The id given to the last context to join. Ids start at 1. */
  unsigned lastId;
  /**
     The main dbs of the contexts which own the connection's open
     savepoints, innermost last. RELEASE and ROLLBACK TO also end the
     savepoints opened after the one they name, so a context may only
     end a transaction level of its own when no other context's
     savepoint is inside it (see fsl_db_txn_end_v2()).
  */
  fsl_db ** sp;
  unsigned nSp;
  unsigned capSp;
};

/** @internal

   Adds f to the registry of db's connection, creating it if needed,
   and records the registry, f and f's new id in db->impl.share. Sets
   *pFirst to true if f is the connection's only context. Returns 0
   or FSL_RC_OOM.
*/
int fsl__cxreg_join(fsl_cx * const f, fsl_db * const db, bool * pFirst);

/** @internal

   False if another context sharing db's (host's) connection owns a
   savepoint inside db's innermost one, which ending db's would end
   too (see fsl__cxreg::sp), else true.
*/
bool fsl__db_txn_is_innermost(fsl_db const * const db);

/** @internal

   Forgets db's open transaction levels without ending them, for a
   context closing while fsl__db_txn_is_innermost() is false. Its
   savepoints stay open in the host's transaction, which the host
   ends.
*/
void fsl__db_txn_abandon(fsl_db * const db);

/** @internal

   Removes db's context from its connection's registry and clears
   db->impl.share's registry fields. Returns the number of contexts
   left. If none are, the registry is freed and the connection's
   client data cleared.
*/
unsigned fsl__cxreg_leave(fsl_db * const db);

/** @internal

   Returns the context for a SQL function running on connection dbh:
   the one whose statement is stepping, else the default
   (fsl__cxreg_default_set()), else the first to join, else NULL if
   none has.
*/
fsl_cx * fsl__cx_for_dbh(sqlite3 * dbh);

/** @internal

   Makes f, which must be one of dbh's contexts, the one the host's own
   SQL on dbh gets from the SQL functions, e.g. for the SQL extension's
   fsl_use(). NULL, or a context not on dbh, restores the first to
   join. A no-op if dbh has no registry.
*/
void fsl__cxreg_default_set(sqlite3 * dbh, fsl_cx * f);

/** @internal

   Returns the name of role r's schema on db's connection, e.g. "repo"
   in "SELECT ... FROM repo.blob". This is where a role's schema name
   comes from, for SQL text (via the {{dbname.repo}} and
   {{dbname.ckout}} placeholders, which the fsl_db SQL functions and
   fsl_cx_format() expand) and for sqlite3 calls taking a schema name.
   That is fsl_db_role_name(r) unless db's context shares a connection
   with another one, which gets names of its own (e.g. "repo_2"), or
   "main" while the role's tables are prefixed tables of the host's
   main db (fsl__db_ckout_prefix(), fsl__db_repo_prefix()), whose names
   then need that prefix too (fsl__db_table_name()).
*/
char const * fsl__db_schema(fsl_db const * const db, fsl_dbrole_e r);

/** @internal

   Appends the expansion of placeholder token zTok (n bytes, the X of
   {{X}}) for db to b: "dbname.repo" and "dbname.ckout" become the
   schema names (fsl__db_schema()), and "temp.NAME" becomes the TEMP
   table NAME of db's context, "temp.NAME" for a connection's first
   context and "temp.fslN_NAME" for its Nth, and "bare.temp.NAME" that
   name without its schema, for e.g. CREATE INDEX's ON clause.
   "bare.ckout.NAME" becomes the checkout table NAME without its
   schema, for the same uses: NAME, or "PNAME" (quoted) while db's
   checkout tables are prefixed with P (fsl__db_ckout_prefix()).
   "bare.repo.NAME" does the same for a repository table
   (fsl__db_repo_prefix()).

   zTail, if not NULL, is the NUL-terminated text after the token's
   closing braces, and *pnConsumed (which must then not be NULL
   either) gets the number of bytes of it which this call expanded
   along with the token, 0 unless noted. While db's checkout tables are
   prefixed, "dbname.ckout" must be followed by ".IDENT", where IDENT
   is a table (or index or trigger) name of [A-Za-z0-9_] characters:
   the whole of "{{dbname.ckout}}.IDENT" becomes main."PIDENT" and
   *pnConsumed is the length of ".IDENT". Without such a tail, or with
   a NULL zTail, the token is then refused with FSL_RC_MISUSE, so that
   no SQL names a checkout table which the prefix would miss. The same
   holds for "dbname.repo" while db's repository tables are prefixed.
   Without a prefix, the token's expansion is the schema name alone,
   as for the other tokens.

   db may be NULL, for the defaults. Returns FSL_RC_NOT_FOUND for any
   other token.
*/
int fsl__db_schema_token(fsl_db const * const db, char const * zTok,
                         fsl_size_t n, char const * zTail,
                         fsl_size_t * pnConsumed, fsl_b * const b);

/** @internal

   For fsl_repo_open_ckout() with a
   fsl_repo_open_ckout_opt::hostTablePrefix: makes the tables of f's
   host's main db whose names start with zPrefix f's checkout db,
   instead of ATTACHing one. f must have a repository opened on a host
   db handle, whose main db must be a file, and zPrefix must match
   [A-Za-z_][A-Za-z0-9_]* and not be another context's on that handle.
   The checkout fsl_db then has the name "main" and the main db's file
   name. Creates no tables. Returns 0 or an error code, with f's error
   state set.
*/
int fsl__cx_attach_ckout_prefixed(fsl_cx * const f, char const * zPrefix);

/** @internal

   The checks of fsl__cx_attach_ckout_prefixed() on f and zPrefix,
   without attaching anything: f has a repository on a host db handle
   whose main db is a file, and zPrefix is a valid prefix which does
   not overlap (one being the start of the other, ignoring case)
   another context's on that handle. Returns 0 or an error code, with
   f's error state set.
*/
int fsl__cx_ckout_prefix_check(fsl_cx * const f, char const * zPrefix);

/** @internal

   For fsl_repo_open_host() and fsl_repo_create() resp.
   fsl_repo_import() with a table prefix: makes the tables of the main
   db of f's host db handle whose names start with zPrefix f's
   repository db, instead of ATTACHing a file. f must be bound to a
   host db handle (fsl_cx_host_db()), whose main db must be a file, and
   have no repository opened; if it has a checkout opened (as for
   fsl_ckout_open_dir() of a checkout of such a repository), that
   becomes the repository's counterpart, else the repository becomes
   f's main db. zPrefix must match [A-Za-z_][A-Za-z0-9_]*, not start
   with "sqlite_", and overlap (one being the start of the other,
   ignoring case) neither another prefix of a context on that handle
   nor the SQLite extension's working copies' "fslfiles_", "fslclock_"
   and "fslwc_". The repository fsl_db then has the name "main" and
   the main db's file name. Checks no tables and creates none (see
   fsl__host_prefix_recorded_check()). Returns 0 or an error code,
   with f's error state set.
*/
int fsl__cx_attach_repo_prefixed(fsl_cx * const f, char const * zPrefix);

/** @internal

   The checks of fsl__cx_attach_repo_prefixed() on zPrefix, on dbM,
   f's main db or a fsl_db on the host's handle it is to use: zPrefix
   is a valid prefix which overlaps no other of a context on that
   handle, nor the names of the SQLite extension's working copies,
   which are tables fslfiles_NAME and fslclock_NAME beside checkout
   tables prefixed with fslwc_NAME_, and which
   fsl__host_prefix_recorded_check() does not see. Returns 0 or an
   error code, with f's error state set.
*/
int fsl__cx_repo_prefix_check(fsl_cx * const f, fsl_db * const dbM,
                              char const * zPrefix);

/** @internal

   Refuses zPre as a table prefix for role r (FSL_DBROLE_REPO or
   FSL_DBROLE_CKOUT) in the main db of db's connection if it and the
   prefix P of a repository or working copy recorded there, other than
   one of role r with prefix zPre itself, are leading parts of one
   another, ignoring case (FSL_RC_ALREADY_EXISTS). A recorded working
   copy is a P for which main has tables Pvvar, with a 'ckout-root'
   row, and Pvfile; a recorded repository one for which it has tables
   Pblob and Pconfig, with a 'content-schema' row. Some tables of each
   are created as they are first used (the stash's and undo's, the
   forum's), so a recorded prefix stands for its whole namespace.
   Returns 0 or an error code, with f's error state set.
*/
int fsl__host_prefix_recorded_check(fsl_cx * const f, fsl_db * const db,
                                    fsl_dbrole_e r, char const * zPre);

/** @internal

   True if f's newly opened repository has the tables which fossil(1)'s
   db_looks_like_a_repository() requires, with their prefix if they
   are tables of a host's main db (fsl__db_repo_prefix()). Clears any
   db-level error state the check leaves behind.
*/
bool fsl__repo_looks_valid(fsl_cx * const f);

/** @internal

   What a checkout of a repository which is tables of a host's main db
   (fsl_repo_open_host()) records as its repository (its vvar
   "repository" entry), followed by their prefix. It is not an absolute
   file name, so it is never one which libfossil or fossil(1) records
   for a repository db file, which they record canonically.
*/
#define FSL__REPO_HOST_REF "fsl-host-prefix:"

/** @internal

   The name a checkout records for f's opened repository (its vvar
   "repository" entry): its db's file name, or FSL__REPO_HOST_REF and
   its table prefix if it is tables of a host's main db. Returns a
   string for the caller to fsl_free(), or NULL on OOM, with f's error
   state set.
*/
char * fsl__cx_repo_ref(fsl_cx * const f);

/** @internal

   Updates f's cached state after a repository, or a checkout and its
   repository, was opened: the checkout's version, the glob lists, the
   user name. Returns 0 or an error code.
*/
int fsl__cx_after_open(fsl_cx * const f);

/** @internal

   Detaches (or, for prefixed checkout tables, just forgets) f's
   checkout, which must be opened alongside its repository, leaving the
   repository opened.
*/
int fsl__cx_detach_ckout(fsl_cx * const f);

/** @internal

   Sets PRAGMA synchronous=FULL on f's repository db, for a check-in's
   atomic commit of the repository and checkout dbs. SQLite refuses
   that inside a transaction. Returns 0 or an error code, with f's
   error state set.
*/
int fsl__cx_repo_sync_full(fsl_cx * const f);

/** @internal

   Takes the write lock of db's main db for the transaction which must
   be open on it (e.g. by fsl_db_txn_begin()), as BEGIN IMMEDIATE
   would, without locking the other attached dbs, and without changing
   anything. Returns 0 or the db error code (e.g. FSL_RC_LOCKED if
   another connection holds it).
*/
int fsl__db_main_write_lock(fsl_db * const db);

/** @internal

   Replaces the absolute file name in b with the same file's name with
   symbolic links resolved, as realpath() does: the whole name's if the
   file exists, else its directory part's, so that a file which does
   not exist yet, e.g. a db's -wal file, compares equal however its
   directory is spelled. Leaves b as it is if neither can be resolved
   (and on Windows, where it does nothing). Returns 0 or FSL_RC_OOM.
*/
int fsl__file_realpath(fsl_b * const b);

/** @internal

   The prefix of the names of db's checkout tables while they are
   tables of the host's main db (fsl_repo_open_ckout_opt::hostTablePrefix),
   else NULL.
*/
char const * fsl__db_ckout_prefix(fsl_db const * const db);

/** @internal

   The prefix of the names of db's repository tables while they are
   tables of the host's main db (fsl_repo_open_host()), else NULL.
*/
char const * fsl__db_repo_prefix(fsl_db const * const db);

/** @internal

   Appends the name of table zTable of role r (FSL_DBROLE_REPO or
   FSL_DBROLE_CKOUT) of db's connection to b. If qualified is true it
   is SQL which names the table: schema.zTable, as
   {{dbname.repo}}.zTable resp. {{dbname.ckout}}.zTable expand,
   including main."PzTable" for prefixed repository or checkout tables
   (fsl__db_repo_prefix(), fsl__db_ckout_prefix()). Else it is the
   table's bare name, unquoted, for APIs which take a table's name as
   a value, e.g. sqlite3_table_column_metadata() or PRAGMA
   table_info(%Q): zTable, or PzTable for prefixed tables. zTable may also name an
   index or trigger of that schema. Returns 0 or b->errCode.
*/
int fsl__db_table_name(fsl_db const * const db, fsl_dbrole_e r,
                       char const * zTable, bool qualified,
                       fsl_b * const b);

/** @internal

   fsl_db_table_has_column() for table zTable in role r's schema of
   db's connection (fsl__db_schema()), rather than whichever schema an
   unqualified name finds first.
*/
bool fsl__db_table_has_column(fsl_db * const db, fsl_dbrole_e r,
                              char const *zTable, char const *zCol);

/** @internal

   fsl_b_appendf(b, zFmt, ...) after replacing the schema placeholders
   ({{dbname.repo}}, {{dbname.ckout}}, {{temp.NAME}},
   {{bare.temp.NAME}}, see fsl__db_schema_token()) in zFmt, never in
   the values formatted into it, for db. For SQL built up in a buffer
   and then prepared as a "%b" argument, which the fsl_db SQL
   functions do not expand.
*/
int fsl__db_appendf(fsl_db * const db, fsl_b * const b,
                    char const * zFmt, ... );

/** @internal

   Appends zIn, SQL which creates the ticket tables (from
   fsl_cx_schema_ticket(): libfossil's default schema or a repository's
   own "ticket-table" setting, which fossil(1) writes without schema
   names), to out, with the object name of each CREATE TABLE and
   CREATE [UNIQUE] INDEX given db's repository schema name
   (fsl__db_schema()): a name's own qualifier, if any, is replaced.
   Strings, quoted identifiers and comments are copied as they are.
   The schema is data, so the placeholders of fsl__db_schema_token()
   are not used for it. Returns 0 or FSL_RC_OOM.
*/
int fsl__ticket_schema_qualify(fsl_db * const db, char const * zIn,
                               fsl_b * const out);

/** @internal

   Creates the ticket tables of f's repository from zSql (see
   fsl__ticket_schema_qualify()). If the repository is tables of a
   host's main db (fsl__db_repo_prefix()), every object which zSql
   makes gets the prefix, and every reference to its tables follows,
   by way of a scratch db and SQLite's ALTER TABLE RENAME, and a schema
   which names any other table, or makes anything but tables, indexes,
   views and triggers, is refused with FSL_RC_CONSISTENCY, so that
   nothing of it binds to the host's tables. Returns 0 or an error
   code, with f's error state set.
*/
int fsl__ticket_schema_install(fsl_cx * const f, char const * zSql);

/** @internal

   Checks that a repository with table prefix zPre can be made in the
   main db of db's connection: that the prefix overlaps no recorded
   one and that main has no object whose name starts with it, ignoring
   case. Returns 0 or an error code, with f's error state set.
*/
int fsl__repo_host_free_check(fsl_cx * f, fsl_db * db, char const * zPre);

/** @internal

   Appends zSql, the CREATE statement of a table, index, view or
   trigger as SQLite records it in sqlite_schema ("CREATE [UNIQUE]
   TABLE|INDEX|VIEW|TRIGGER name..."), to b with its name replaced
   by zSchema."zName". Returns 0, FSL_RC_RANGE if zSql has no such
   form, or FSL_RC_OOM.
*/
int fsl__repo_copy_sql(fsl_b * const b, char const * zSql,
                       char const * zSchema, char const * zName);

/** @internal

   Callback type for fsl__brace_expand(): appends the replacement for
   the n-byte token zTok (the X of {{X}}) to b, doubling each '%' in
   it if escPct is true. zTail is the NUL-terminated rest of the format
   string after the token's closing braces. A callback which expands
   some of that along with the token sets *pnConsumed (0 on entry) to
   the number of bytes of zTail it expanded, which the parser then
   skips. Returns 0 on success, FSL_RC_NOT_FOUND if zTok is not one it
   knows, in which case nothing may have been appended, or another
   code (normally b->errCode) on error.
*/
typedef int (*fsl__brace_f)(void * state, char const * zTok, fsl_size_t n,
                            char const * zTail, fsl_size_t * pnConsumed,
                            fsl_b * const b, bool escPct);

/** @internal

   Appends zFmt to b with each {{X}} placeholder replaced by xToken():
   the parser behind fsl_cx_formatv() and behind the {{dbname.repo}}
   and {{dbname.ckout}} schema placeholders in the fsl_db SQL
   functions. Unknown
   and empty placeholders are passed through as-is, as is everything
   after a "{{" which is never closed. Text after a placeholder which
   xToken() reports having expanded along with it (see fsl__brace_f)
   is skipped. Stops at and returns the first error code from xToken()
   other than FSL_RC_NOT_FOUND, else returns b->errCode.
*/
int fsl__brace_expand(fsl_b * const b, char const * const zFmt,
                      bool escPct, fsl__brace_f xToken, void * state);

/** @internal

   Calls cb() for each entry of directory zDir, by name (as
   fsl_dircrawl() presents names: UTF-8, precomposed on macOS), except
   "." and "..", stopping at and returning the first non-0 result.
   Returns non-0 if the directory cannot be read. This is
   fsl_ckout_fs_os's xDirList().
*/
int fsl__dir_list(char const * zDir,
                  int (*cb)(void * cbState, char const * zEntry),
                  void * cbState);

int fsl__cfs_stat(fsl_cx * const f, char const *zName, fsl_fstat * fst,
                  bool derefLinks);
fsl_int_t fsl__cfs_size(fsl_cx * const f, char const *zName);
fsl_time_t fsl__cfs_mtime(fsl_cx * const f, char const *zName);
bool fsl__cfs_is_file(fsl_cx * const f, char const *zName);
bool fsl__cfs_is_file_or_link(fsl_cx * const f, char const *zName);
bool fsl__cfs_is_symlink(fsl_cx * const f, char const *zName);
bool fsl__cfs_isexec(fsl_cx * const f, char const *zName);
int fsl__cfs_dir_check(fsl_cx * const f, char const *zName);
int fsl__cfs_dir_is_empty(fsl_cx * const f, char const *zName);
int fsl__cfs_read(fsl_cx * const f, fsl_b * const dest, char const *zName);
int fsl__cfs_write(fsl_cx * const f, fsl_b const * const b,
                   char const *zName);
int fsl__cfs_write_blob(fsl_cx * const f, char const *zName,
                        fsl_id_t rid, fsl_b * const content,
                        bool loaded, bool * const pWriteFailed);
int fsl__cfs_unlink(fsl_cx * const f, char const *zName);
int fsl__cfs_rename(fsl_cx * const f, char const *zFrom, char const *zTo);
int fsl__cfs_rmdir(fsl_cx * const f, char const *zName);
int fsl__cfs_mkdir_for_file(fsl_cx * const f, char const *zName,
                            bool forceFlag);
int fsl__cfs_exec_set(fsl_cx * const f, char const *zName, bool isExec);
int fsl__cfs_mtime_set(fsl_cx * const f, char const *zName,
                       fsl_time_t mtime);
int fsl__cfs_copy(fsl_cx * const f, char const *zFrom, char const *zTo);
int fsl__cfs_sha1sum(fsl_cx * const f, char const *zName, fsl_b * const tgt);
int fsl__cfs_sha3sum(fsl_cx * const f, char const *zName, fsl_b * const tgt);
int fsl__cfs_dircrawl(fsl_cx * const f, char const *zDir,
                      fsl_dircrawl_f callback, void * cbState);
int fsl__cfs_symlink_read(fsl_cx * const f, fsl_b * const tgt,
                          char const *zName);
int fsl__cfs_symlink_create(fsl_cx * const f, char const *zTarget,
                            char const *zLink, bool realLink);
int fsl__cfs_symlink_copy(fsl_cx * const f, char const *zFrom,
                          char const *zTo, bool realLink);

/** @internal

   Reads checkout file zName into tgt as fossil(1)'s
   blob_read_from_file(...,RepoFILE) does: with the allow-symlinks
   setting on, a symlink's content is its target name, else the
   symlink is followed. If isLink is not NULL, *isLink is set to
   whether zName was read as a symlink.

   Returns 0 on success or the non-0 result of fsl__cfs_read() or
   fsl__cfs_symlink_read(), e.g. FSL_RC_NOT_FOUND. It does not set
   f's error state.
*/
int fsl__cfs_read_repofile(fsl_cx * const f, fsl_b * const tgt,
                           char const *zName, bool * isLink);

/** @internal

   Returns the permission of a checkout file as fossil(1)'s
   file_perm(...,RepoFILE) does, given its fsl_fstat. fst must come
   from a successful fsl__cfs_stat() which dereferenced symlinks
   unless allowSymlinks, which must be the allow-symlinks setting
   (fsl_cx_allows_symlinks()). A symlink is FSL_FILE_PERM_LINK, and
   never also executable.
*/
fsl_fileperm_e fsl__fstat_perm(fsl_fstat const * fst, bool allowSymlinks);


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_INTERNAL_H_INCLUDED */
#endif /*defined(FSL_EXPOSE_INTERNAL_APIS)*/
#endif /*ORG_FOSSIL_SCM_LIBFOSSIL_AMAL_H_INCLUDED*/