Index: CHANGES.md ================================================================== --- CHANGES.md +++ CHANGES.md @@ -1,48 +1,5 @@ -**fnc 0.7** 2022-01-09 - -- factor out common make(1) and gmake build bits -- make build depend on make file -- make all commands compatible with `-R|--repository` (i.e., no checkout needed) -- implement Vim-like smartcase for commands that filter repository results -- improve timeline arg parsing for more informative output upon invalid input -- plug small memory leak when the timeline command fails to initialise a view -- fix database locking issue when opening multiple tree views from the timeline -- add pledge(2) and unveil(2) support on OpenBSD builds -- add (s)ort keymap (i.e., `--sort` CLI option counterpart) to the branch view -- add (d)ate keymap to toggle display of last modified timestamp in tree view -- allow blame of empty files rather than erroring out -- fix NULL dereference UB when the ".." parent dir is selected in tree view -- merge upstream fix when annotating files with shallow history -- add support for configurable horizontal split view mode (timeline -> diff) -- keep the last/first line in view when paging down/up to stay oriented -- expand horizontal splitscreen support to include tree -> blame views -- improve handling of cached commit builder statements -- plug small memleak of file labels when traversing commits from the diff view -- display message rather than error out when binary files are blamed -- expand horizontal split coverage to include timeline -> tree views -- implement '#' keymap to display line numbers in blame view -- implement (L)ine keymap to navigate directly to the entered line in blame view -- convert diff code to use upstream v2 API -- keep lines on screen in view when using keymaps that modify diff content -- reset diff search state when traversing commits from the diff view -- apply upstream diff fix to render consecutive edited lines as one block -- implement '#' keymap to display line numbers in diff view -- improve `C-f/C-b` paging in the in-app help window -- add user-defined option to configure search highlight colours -- implement navigate to (L)ine keymap in diff view -- enhance timeline and diff view headers -- implement user-defined option to configure line selection cursor in diff view -- implement Vim-like `C-e/C-y` keymaps to scroll down/up one line in diff view -- implement horizontal scrolling in diff and blame views -- improve view request handling and optimise new view initialisation -- implement `C-n/C-p` keymap to navigate to the next/previous file in the diff -- implement (F)ile keymap to navigate directly to a file in the diff -- apply upstream diff v2 fix for rendering untouched lines as changed -- implement Vim-like `C-d/C-u` keymaps to scroll the view down/up half a page -- enhance search behaviour in all views - **fnc 0.6** 2021-11-22 - implement support for user-defined colours in tl, diff, tree and blame views - make branch view accessible from all other views - optimise colour scheme initialisation Index: GNUmakefile ================================================================== --- GNUmakefile +++ GNUmakefile @@ -1,17 +1,94 @@ # -# FNC GNU Makefile +# FNC Makefile # -# CONFIGURATION -include fnc.bld.mk +# CONFIGUGRAION +CC ?= cc +PREFIX ?= /usr/local +MANDIR ?= /share/man +VERSION ?= 0.6 +# USED BELOW FOR PLATFORM SPECIFIC LDFLAGS UNAME := $(shell uname -s) +# FLAGS NEEDED TO BUILD SQLITE3 +SQLITE_CFLAGS = ${CFLAGS} -Wall -Werror -Wno-sign-compare -pedantic -std=c99 \ + -DNDEBUG=1 \ + -DSQLITE_DQS=0 \ + -DSQLITE_THREADSAFE=0 \ + -DSQLITE_DEFAULT_MEMSTATUS=0 \ + -DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 \ + -DSQLITE_LIKE_DOESNT_MATCH_BLOBS \ + -DSQLITE_OMIT_DECLTYPE \ + -DSQLITE_OMIT_PROGRESS_CALLBACK \ + -DSQLITE_OMIT_SHARED_CACHE \ + -DSQLITE_OMIT_LOAD_EXTENSION \ + -DSQLITE_MAX_EXPR_DEPTH=0 \ + -DSQLITE_USE_ALLOCA \ + -DSQLITE_ENABLE_LOCKING_STYLE=0 \ + -DSQLITE_DEFAULT_FILE_FORMAT=4 \ + -DSQLITE_ENABLE_EXPLAIN_COMMENTS \ + -DSQLITE_ENABLE_FTS4 \ + -DSQLITE_ENABLE_DBSTAT_VTAB \ + -DSQLITE_ENABLE_JSON1 \ + -DSQLITE_ENABLE_FTS5 \ + -DSQLITE_ENABLE_STMTVTAB \ + -DSQLITE_HAVE_ZLIB \ + -DSQLITE_INTROSPECTION_PRAGMAS \ + -DSQLITE_ENABLE_DBPAGE_VTAB \ + -DSQLITE_TRUSTED_SCHEMA=0 + +# This makefile +MAKEFILE := $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) + +# FLAGS NEEDED TO BUILD LIBFOSSIL +FOSSIL_CFLAGS = ${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99 + +# On SOME Linux (e.g., Ubuntu 18.04.6), we have to include wchar curses from +# I/.../ncursesw, but linking to -lncursesw (w/ no special -L path) works fine. +# FLAGS NEEDED TO BUILD FNC +FNC_CFLAGS = ${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99 \ + -I./lib -I./include -I/usr/include/ncursesw \ + -D_XOPEN_SOURCE_EXTENDED -DVERSION=${VERSION} + +FNC_LDFLAGS = ${LDFLAGS} -lm -lutil -lz -lpthread -fPIC + # OSX has ncursesw, and needs iconv. ifeq ($(UNAME),Darwin) # OSX FNC_LDFLAGS += -lncurses -lpanel -liconv else # Linux (tested on Debian), OpenBSD, FreeBSD FNC_LDFLAGS += -lncursesw -lpanelw endif + +all: bin + +bin: lib/sqlite3.o lib/libfossil.o src/fnc.o src/fnc + +lib/sqlite3.o: lib/sqlite3.c lib/sqlite3.h $(MAKEFILE) + ${CC} ${SQLITE_CFLAGS} -c $< -o $@ + +lib/libfossil.o: lib/libfossil.c lib/libfossil.h $(MAKEFILE) + ${CC} ${FOSSIL_CFLAGS} -c $< -o $@ + +src/fnc.o: src/fnc.c include/settings.h $(MAKEFILE) + ${CC} ${FNC_CFLAGS} -c $< -o $@ + +src/fnc: src/fnc.o lib/libfossil.o lib/sqlite3.o $(MAKEFILE) + ${CC} -o $@ src/fnc.o lib/libfossil.o lib/sqlite3.o ${FNC_LDFLAGS} + +install: + install -s -m 0755 src/fnc ${PREFIX}/bin/fnc + install -m 0644 src/fnc.1 ${PREFIX}${MANDIR}/man1/fnc.1 + +uninstall: + rm -f ${PREFIX}/bin/fnc ${PREFIX}${MANDIR}/man1/fnc.1 + +clean: + rm -f lib/*.o src/*.o src/fnc + +release: clean + tar czvf ../fnc-${VERSION}.tgz -C .. fnc-${VERSION} + +.PHONY: clean release Index: LICENSE ================================================================== --- LICENSE +++ LICENSE @@ -1,6 +1,6 @@ -Copyright (c) 2021, 2022 Mark Jamsek +Copyright (c) 2021 Mark Jamsek Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. Index: Makefile ================================================================== --- Makefile +++ Makefile @@ -1,17 +1,91 @@ # # FNC Makefile # -# CONFIGURATION -.include "fnc.bld.mk" +# CONFIGUGRAION +CC ?= cc +PREFIX ?= /usr/local +MANDIR ?= /share/man +VERSION ?= 0.6 +# USED BELOW FOR PLATFORM SPECIFIC LDFLAGS UNAME != uname -s +# FLAGS NEEDED TO BUILD SQLITE3 +SQLITE_CFLAGS = ${CFLAGS} -Wall -Werror -Wno-sign-compare -pedantic -std=c99 \ + -DNDEBUG=1 \ + -DSQLITE_DQS=0 \ + -DSQLITE_THREADSAFE=0 \ + -DSQLITE_DEFAULT_MEMSTATUS=0 \ + -DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 \ + -DSQLITE_LIKE_DOESNT_MATCH_BLOBS \ + -DSQLITE_OMIT_DECLTYPE \ + -DSQLITE_OMIT_PROGRESS_CALLBACK \ + -DSQLITE_OMIT_SHARED_CACHE \ + -DSQLITE_OMIT_LOAD_EXTENSION \ + -DSQLITE_MAX_EXPR_DEPTH=0 \ + -DSQLITE_USE_ALLOCA \ + -DSQLITE_ENABLE_LOCKING_STYLE=0 \ + -DSQLITE_DEFAULT_FILE_FORMAT=4 \ + -DSQLITE_ENABLE_EXPLAIN_COMMENTS \ + -DSQLITE_ENABLE_FTS4 \ + -DSQLITE_ENABLE_DBSTAT_VTAB \ + -DSQLITE_ENABLE_JSON1 \ + -DSQLITE_ENABLE_FTS5 \ + -DSQLITE_ENABLE_STMTVTAB \ + -DSQLITE_HAVE_ZLIB \ + -DSQLITE_INTROSPECTION_PRAGMAS \ + -DSQLITE_ENABLE_DBPAGE_VTAB \ + -DSQLITE_TRUSTED_SCHEMA=0 + +# FLAGS NEEDED TO BUILD LIBFOSSIL +FOSSIL_CFLAGS = ${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99 + +# On SOME Linux (e.g., Ubuntu 18.04.6), we have to include wchar curses from +# I/.../ncursesw, but linking to -lncursesw (w/ no special -L path) works fine. +# FLAGS NEEDED TO BUILD FNC +FNC_CFLAGS = ${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99 \ + -I./lib -I./include -I/usr/include/ncursesw \ + -D_XOPEN_SOURCE_EXTENDED -DVERSION=${VERSION} + +FNC_LDFLAGS = ${LDFLAGS} -lm -lutil -lz -lpthread -fPIC + # OSX has ncursesw, and needs iconv. .if $(UNAME) == Darwin # OSX FNC_LDFLAGS += -lncurses -lpanel -liconv .else # Linux (tested on Debian), OpenBSD, FreeBSD FNC_LDFLAGS += -lncursesw -lpanelw .endif + +all: bin + +bin: lib/sqlite3.o lib/libfossil.o src/fnc.o src/fnc + +lib/sqlite3.o: lib/sqlite3.c lib/sqlite3.h + ${CC} ${SQLITE_CFLAGS} -c $< -o $@ + +lib/libfossil.o: lib/libfossil.c lib/libfossil.h + ${CC} ${FOSSIL_CFLAGS} -c $< -o $@ + +src/fnc.o: src/fnc.c include/settings.h + ${CC} ${FNC_CFLAGS} -c $< -o $@ + +src/fnc: src/fnc.o lib/libfossil.o lib/sqlite3.o Makefile + ${CC} -o $@ src/fnc.o lib/libfossil.o lib/sqlite3.o ${FNC_LDFLAGS} + +install: + install -s -m 0755 src/fnc ${PREFIX}/bin/fnc + install -m 0644 src/fnc.1 ${PREFIX}${MANDIR}/man1/fnc.1 + +uninstall: + rm -f ${PREFIX}/bin/fnc ${PREFIX}${MANDIR}/man1/fnc.1 + +clean: + rm -f lib/*.o src/*.o src/fnc + +release: clean + tar czvf ../fnc-${VERSION}.tgz -C .. fnc-${VERSION} + +.PHONY: clean release Index: README.md ================================================================== --- README.md +++ README.md @@ -1,8 +1,8 @@ # README -# fnc 0.6 +# fnc 0.5 ## An ncurses browser for [Fossil][0] repositories in the terminal. `fnc` uses [libfossil][1] to create a [`fossil ui`][2] experience in the terminal. @@ -81,20 +81,10 @@ ![tree split screen](https://fnc.bsdbox.org/uv/resources/img/fnc-tree-splitscreen.png "fnc tree split screen") ![branch split screen](https://fnc.bsdbox.org/uv/resources/img/fnc-branch-splitscreen.png "fnc branch split screen") ![in-app help](https://fnc.bsdbox.org/uv/resources/img/fnc-inapp_help.png "fnc in-app help") ![timeline help](https://fnc.bsdbox.org/uv/resources/img/fnc-timeline-help.png "fnc timeline help") -# Trivia - -**fnc** [fɪŋk] -*noun* (n.) -1. an ncurses browser for [Fossil][0] repositories in the terminal -*verb* (v.) -2. to inform -etymology -From the German word *Fink*, meaning "finch", a type of bird. - [0]: https://fossil-scm.org [1]: https://fossil.wanderinghorse.net/r/libfossil [2]: https://fossil-scm.org/home/help?cmd=ui [3]: https://fnc.bsdbox.org/uv/download.html [4]: https://fnc.bsdbox.org/uv/resources/doc/fnc.1.html DELETED fnc.bld.mk Index: fnc.bld.mk ================================================================== --- fnc.bld.mk +++ fnc.bld.mk @@ -1,79 +0,0 @@ -# -# FNC Common Build -# - -# CONFIGURATION -CC ?= cc -PREFIX ?= /usr/local -MANDIR ?= /share/man -VERSION ?= 0.7 - -# FLAGS NEEDED TO BUILD SQLITE3 -SQLITE_CFLAGS = ${CFLAGS} -Wall -Werror -Wno-sign-compare -pedantic -std=c99 \ - -DNDEBUG=1 \ - -DSQLITE_DQS=0 \ - -DSQLITE_THREADSAFE=0 \ - -DSQLITE_DEFAULT_MEMSTATUS=0 \ - -DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 \ - -DSQLITE_LIKE_DOESNT_MATCH_BLOBS \ - -DSQLITE_OMIT_DECLTYPE \ - -DSQLITE_OMIT_PROGRESS_CALLBACK \ - -DSQLITE_OMIT_SHARED_CACHE \ - -DSQLITE_OMIT_LOAD_EXTENSION \ - -DSQLITE_MAX_EXPR_DEPTH=0 \ - -DSQLITE_USE_ALLOCA \ - -DSQLITE_ENABLE_LOCKING_STYLE=0 \ - -DSQLITE_DEFAULT_FILE_FORMAT=4 \ - -DSQLITE_ENABLE_EXPLAIN_COMMENTS \ - -DSQLITE_ENABLE_FTS4 \ - -DSQLITE_ENABLE_DBSTAT_VTAB \ - -DSQLITE_ENABLE_JSON1 \ - -DSQLITE_ENABLE_FTS5 \ - -DSQLITE_ENABLE_STMTVTAB \ - -DSQLITE_HAVE_ZLIB \ - -DSQLITE_INTROSPECTION_PRAGMAS \ - -DSQLITE_ENABLE_DBPAGE_VTAB \ - -DSQLITE_TRUSTED_SCHEMA=0 - -# FLAGS NEEDED TO BUILD LIBFOSSIL -FOSSIL_CFLAGS = ${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99 - -# On SOME Linux (e.g., Ubuntu 18.04.6), we have to include wchar curses from -# I/.../ncursesw, but linking to -lncursesw (w/ no special -L path) works fine. -# FLAGS NEEDED TO BUILD FNC -FNC_CFLAGS = ${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99 \ - -I./lib -I./include -I/usr/include/ncursesw \ - -D_XOPEN_SOURCE_EXTENDED -DVERSION=${VERSION} - -FNC_LDFLAGS = ${LDFLAGS} -lm -lutil -lz -lpthread -fPIC - -all: bin - -bin: lib/sqlite3.o lib/libfossil.o src/fnc.o src/fnc - -lib/sqlite3.o: lib/sqlite3.c lib/sqlite3.h - ${CC} ${SQLITE_CFLAGS} -c $< -o $@ - -lib/libfossil.o: lib/libfossil.c lib/libfossil.h - ${CC} ${FOSSIL_CFLAGS} -c $< -o $@ - -src/fnc.o: src/fnc.c include/settings.h fnc.bld.mk - ${CC} ${FNC_CFLAGS} -c $< -o $@ - -src/fnc: src/fnc.o lib/libfossil.o lib/sqlite3.o fnc.bld.mk - ${CC} -o $@ src/fnc.o lib/libfossil.o lib/sqlite3.o ${FNC_LDFLAGS} - -install: - install -s -m 0755 src/fnc ${PREFIX}/bin/fnc - install -m 0644 src/fnc.1 ${PREFIX}${MANDIR}/man1/fnc.1 - -uninstall: - rm -f ${PREFIX}/bin/fnc ${PREFIX}${MANDIR}/man1/fnc.1 - -clean: - rm -f lib/*.o src/*.o src/fnc - -release: clean - tar czvf ../fnc-${VERSION}.tgz -C .. fnc-${VERSION} - -.PHONY: clean release Index: include/settings.h ================================================================== --- include/settings.h +++ include/settings.h @@ -12,85 +12,40 @@ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#define GEN_ENUM_SYM(pfx, id) pfx##_##id -#define GEN_ENUM(name, pfx, info) \ - enum name { info(pfx, GEN_ENUM_SYM) }; - -#define GEN_STR_SYM(pfx, id) #pfx"_"#id -#define GEN_STR(name, pfx, info) \ - static const char *name[] = { info(pfx, GEN_STR_SYM) }; - /* * All configurable fnc settings, which can be stored in either the fossil(1) - * repository (e.g., ./repo.fossil) or shell envvars with `export SETTING=val`. - */ -#define USER_OPTIONS(pfx, _) \ - _(pfx, START_SETTINGS), \ - _(pfx, COLOUR_COMMIT), \ - _(pfx, COLOUR_USER), \ - _(pfx, COLOUR_DATE), \ - _(pfx, COLOUR_DIFF_META), \ - _(pfx, COLOUR_DIFF_MINUS), \ - _(pfx, COLOUR_DIFF_PLUS), \ - _(pfx, COLOUR_DIFF_CHUNK), \ - _(pfx, COLOUR_DIFF_TAGS), \ - _(pfx, COLOUR_TREE_LINK), \ - _(pfx, COLOUR_TREE_DIR), \ - _(pfx, COLOUR_TREE_EXEC), \ - _(pfx, COLOUR_BRANCH_OPEN), \ - _(pfx, COLOUR_BRANCH_CLOSED), \ - _(pfx, COLOUR_BRANCH_CURRENT), \ - _(pfx, COLOUR_BRANCH_PRIVATE), \ - _(pfx, COLOUR_HL_LINE), \ - _(pfx, COLOUR_HL_SEARCH), \ - _(pfx, VIEW_SPLIT_MODE), \ - _(pfx, VIEW_SPLIT_WIDTH), \ - _(pfx, VIEW_SPLIT_HEIGHT), \ - _(pfx, EOF_SETTINGS) - -#define LINE_ATTR_ENUM(pfx, _) \ - _(pfx, AUTO), \ - _(pfx, MONO) - -#define INPUT_TYPE_ENUM(pfx, _) \ - _(pfx, ALPHA), \ - _(pfx, NUMERIC) - -#define LINE_TYPE_ENUM(pfx, _) \ - _(pfx, TIMELINE_HEADER), \ - _(pfx, TIMELINE_COMMIT), \ - _(pfx, DIFF_HEADER), \ - _(pfx, DIFF_ARTIFACT), \ - _(pfx, DIFF_USER), \ - _(pfx, DIFF_TAGS), \ - _(pfx, DIFF_DATE), \ - _(pfx, DIFF_COMMENT), \ - _(pfx, DIFF_CHANGESET), \ - _(pfx, DIFF_INDEX), \ - _(pfx, DIFF_META), \ - _(pfx, DIFF_MINUS), \ - _(pfx, DIFF_PLUS), \ - _(pfx, DIFF_CHUNK), \ - -#define VIEW_MODE_ENUM(pfx, _) \ - _(pfx, NONE), \ - _(pfx, VERT), \ - _(pfx, HRZN) - -#define ENUM_INFO(_) \ - _(fnc_opt_id, FNC, USER_OPTIONS) \ - _(line_attr, SLINE, LINE_ATTR_ENUM) \ - _(input_type, INPUT, INPUT_TYPE_ENUM) \ - _(line_type, LINE, LINE_TYPE_ENUM) \ - _(view_mode, VIEW_SPLIT, VIEW_MODE_ENUM) - -#define GEN_ENUMS(name, pfx, info) GEN_ENUM(name, pfx, info) -ENUM_INFO(GEN_ENUMS) - -#define STR_INFO(_) \ - _(fnc_opt_name, FNC, USER_OPTIONS) - -#define GEN_STRINGS(name, pfx, info) GEN_STR(name, pfx, info) -STR_INFO(GEN_STRINGS) + * repository (e.g., repo.fossil) or global (i.e., $HOME/.fossil) db. Note that + * each setting _MAY_ be mapped to a valid enum, in which case its index here + * _MUST_ be mapped to the index/value of its enum counterpart (i.e., either + * explicitly set equivalent values in the enum, or use offsets when indexing + * them). + */ +#define SETTINGS(SET) \ + SET(FNC_START_SETTINGS) /* 0 */ \ + SET(FNC_COLOUR_COMMIT) /* 1 */ \ + SET(FNC_COLOUR_USER) /* 2 */ \ + SET(FNC_COLOUR_DATE) /* 3 */ \ + SET(FNC_COLOUR_DIFF_META) /* 4 */ \ + SET(FNC_COLOUR_DIFF_MINUS) /* 5 */ \ + SET(FNC_COLOUR_DIFF_PLUS) /* 6 */ \ + SET(FNC_COLOUR_DIFF_CHUNK) /* 7 */ \ + SET(FNC_COLOUR_DIFF_TAGS) /* 8 */ \ + SET(FNC_COLOUR_TREE_LINK) /* 9 */ \ + SET(FNC_COLOUR_TREE_DIR) /* 10 */ \ + SET(FNC_COLOUR_TREE_EXEC) /* 11 */ \ + SET(FNC_COLOUR_BRANCH_OPEN) /* 12 */ \ + SET(FNC_COLOUR_BRANCH_CLOSED) /* 13 */ \ + SET(FNC_COLOUR_BRANCH_CURRENT) /* 14 */ \ + SET(FNC_COLOUR_BRANCH_PRIVATE) /* 15 */ \ + SET(FNC_EOF_SETTINGS) /* 16 */ + +/* + * To construct the string array and enum: + * static const char *fnc_settings[] = { SETTINGS(GEN_STR) }; + * enum settings { SETTINGS(GEN_ENUM) }; + */ +#define GEN_ENUM(_id) _id, +#define GEN_STR(_str) #_str, + Index: lib/libfossil-config.h ================================================================== --- lib/libfossil-config.h +++ lib/libfossil-config.h @@ -53,11 +53,11 @@ #endif #if !defined(_DEFAULT_SOURCE) # define _DEFAULT_SOURCE 1 #endif #if !defined(_XOPEN_SOURCE) -# define _XOPEN_SOURCE 700 +# define _XOPEN_SOURCE 500 #endif #else #if !defined(HAVE_LSTAT) # define HAVE_LSTAT 0 #endif Index: lib/libfossil.c ================================================================== --- lib/libfossil.c +++ lib/libfossil.c @@ -1,7 +1,7 @@ #include "libfossil.h" -/* start of file ./src/fsl.c */ +/* start of file fsl.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -46,12 +46,10 @@ const fsl_card_F_list fsl_card_F_list_empty = fsl_card_F_list_empty_m; const fsl_card_J fsl_card_J_empty = fsl_card_J_empty_m; const fsl_card_Q fsl_card_Q_empty = fsl_card_Q_empty_m; const fsl_card_T fsl_card_T_empty = fsl_card_T_empty_m; const fsl_checkin_opt fsl_checkin_opt_empty = fsl_checkin_opt_empty_m; -const fsl_cidiff_opt fsl_cidiff_opt_empty = fsl_cidiff_opt_empty_m; -const fsl_cidiff_state fsl_cidiff_state_empty = fsl_cidiff_state_empty_m; const fsl_ckout_manage_opt fsl_ckout_manage_opt_empty = fsl_ckout_manage_opt_empty_m; const fsl_ckout_unmanage_opt fsl_ckout_unmanage_opt_empty = fsl_ckout_unmanage_opt_empty_m; const fsl_ckup_opt fsl_ckup_opt_empty = fsl_ckup_opt_m; @@ -379,13 +377,13 @@ int fsl_stricmp_cmp( void const * lhs, void const * rhs ){ return fsl_stricmp((char const *)lhs, (char const *)rhs); } fsl_size_t fsl_strlen( char const * src ){ - char const * const b = src; - if(src) while( *src ) ++src; - return (fsl_size_t)(src - b); + fsl_size_t i = 0; + if(src) for( ; *src; ++i, ++src ){} + return i; } char * fsl_strndup( char const * src, fsl_int_t len ){ if(!src) return NULL; else{ @@ -926,11 +924,11 @@ /** Convenience form of fsl_simplify_sql() which assumes b holds an SQL string. It gets processed by fsl_simplify_sql() and its 'used' length potentially gets adjusted to match the adjusted SQL string. */ -fsl_size_t fsl_simplify_sql_buffer( fsl_buffer * const b ){ +fsl_size_t fsl_simplify_sql_buffer( fsl_buffer * b ){ return b->used = fsl_simplify_sql( (char *)b->mem, (fsl_int_t)b->used ); } char const *fsl_preferred_ckout_db_name(){ #if FSL_PLATFORM_IS_WINDOWS @@ -938,12 +936,12 @@ #else return ".fslckout"; #endif } -bool fsl_isatty(int fd){ - return isatty(fd) ? true : false; +char fsl_isatty(int fd){ + return isatty(fd) ? 1 : 0; } bool fsl__is_reserved_fn_windows(const char *zPath, fsl_int_t nameLen){ static const char *const azRes[] = { "CON", "PRN", "AUX", "NUL", "COM", "LPT" @@ -1022,20 +1020,16 @@ return false; } } } -void fsl_randomness(unsigned int n, void *tgt){ - sqlite3_randomness((int)n, tgt); -} - #undef MARKER #if defined(_WIN32) || defined(WIN32) #undef isatty #endif -/* end of file ./src/fsl.c */ -/* start of file ./src/annotate.c */ +/* end of file fsl.c */ +/* start of file annotate.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -1329,16 +1323,12 @@ goto end; } a->aVers = x; a->naVers = n; } -#define AnnStr(COL,FLD) zCol = NULL; \ - rc = fsl_stmt_get_text(&q, COL, &zCol, &nCol); \ - if(rc) goto end; \ - else if(!zCol){ goto end; \ - /*zCol=""; nCol=0; //causes downstream 'RID 0 is invalid' error*/} \ - zTmp = fsl_strndup(zCol, (fsl_int_t)nCol); \ +#define AnnStr(COL,FLD) zCol = fsl_stmt_g_text(&q, COL, &nCol); \ + zTmp = fsl_strndup(zCol, nCol); \ if(!zTmp){ rc = FSL_RC_OOM; goto end; } \ a->aVers[a->nVers].FLD = zTmp AnnStr(0,zFUuid); AnnStr(1,zMUuid); AnnStr(2,zUser); @@ -1499,12 +1489,12 @@ return rc; } #undef MARKER #undef blob_to_utf8_no_bom -/* end of file ./src/annotate.c */ -/* start of file ./src/appendf.c */ +/* end of file annotate.c */ +/* start of file appendf.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************************ The printf-like implementation in this file is based on the one found in the sqlite3 distribution is in the Public Domain. @@ -2281,26 +2271,22 @@ if( c=='\\' || c=='"' ){ out("\\", 1); outc; }else if( c<' ' ){ out("\\",1); - switch(c){ - case '\b': out("b",1); break; - case '\f': out("f",1); break; - case '\n': out("n",1); break; - case '\t': out("t",1); break; - case '\r': out("r",1); break; - default:{ - unsigned char ubuf[5] = {'u',0,0,0,0}; - int i; - for(i = 4; i>0; --i){ - ubuf[i] = "0123456789abcdef"[c&0xf]; - c >>= 4; - } - out(ubuf,5); - break; - } + if( c=='\n' ){ + out("n",1); + }else if( c=='\r' ){ + out("r",1); + }else{ + unsigned char ubuf[5] = {'u',0,0,0,0}; + int i; + for(i = 4; i>0; --i){ + ubuf[i] = "0123456789abcdef"[c&0xf]; + c >>= 4; + } + out(ubuf,5); } }else if(c<128){ outc; }/* At this point we know that c is part of a multi-byte character. We're assuming legal UTF8 input, which means @@ -2944,11 +2930,11 @@ bufpt = va_arg(ap,char*); length = bufpt ? StrNLen32(bufpt, (precision>0 && flag_alternateform) ? precision*4/*max bytes per char*/ - : (precision>=0 ? precision : -1)) + : (precision ? precision : -1)) : (int)0; if(flag_alternateform && length && (precision>0 || width>0)){ appendf__utf8_altform(bufpt, &length, &precision, &width); }else if( length && precision>=0 && precision0 && flag_alternateform) ? precision*4/*max bytes per char*/ - : (precision>=0 ? precision : -1)) + : (precision ? precision : -1)) : (int)0; if(flag_alternateform && length && (precision>0 || width>0)){ appendf__utf8_altform(bufpt, &length, &precision, &width); }else if( length && precision>=0 && precisionmem && 0==b->capacity) - -/** - Materializes external buffer b by allocating b->used+extra+1 - bytes, copying b->used bytes from b->mem to the new block, - NUL-terminating the block, and replacing b->mem with the new - block. Returns 0 on success, else FSL_RC_OOM. - - Asserts that b is an external buffer. -*/ -static int fsl__buffer_materialize( fsl_buffer * const b, fsl_size_t extra ){ - assert(buffer_is_external(b)); - fsl_size_t const n = b->used + extra + 1; - unsigned char * x = (unsigned char *)fsl_malloc(n); - if(!x) return FSL_RC_OOM; - memcpy(x, b->mem, b->used); - b->capacity = n; - x[b->used] = 0; - b->mem = x; - return 0; -} - -int fsl_buffer_materialize( fsl_buffer * const b ){ - return buffer_is_external(b) ? fsl__buffer_materialize(b, 0) : 0; -} - -#define buffer_materialize(B,N) (buffer_is_external(B) ? fsl__buffer_materialize((B),(N)) : 0) - -void fsl_buffer_external( fsl_buffer * const b, void const * mem, fsl_int_t n ){ - if(b->mem) fsl_buffer_clear(b); - if(n<0) n =(fsl_int_t)fsl_strlen((char const *)mem); - b->used = n; - b->cursor = 0; - b->mem = (unsigned char *)mem; - b->capacity = 0; -} - -fsl_buffer * fsl_buffer_reuse( fsl_buffer * const b ){ - if(buffer_is_external(b)){ - *b = fsl_buffer_empty; - }else{ - if(b->capacity){ - assert(b->mem); - b->mem[0] = 0; - b->used = 0; - } - b->cursor = 0; - } + +fsl_buffer * fsl_buffer_reuse( fsl_buffer * b ){ + if(b->capacity){ + assert(b->mem); + b->mem[0] = 0; + } + b->used = b->cursor = 0; return b; } -void fsl_buffer_clear( fsl_buffer * const buf ){ - if(buf->capacity) fsl_free(buf->mem); - *buf = fsl_buffer_empty; +void fsl_buffer_clear( fsl_buffer * buf ){ + if(buf){ + if(buf->mem) fsl_free(buf->mem); + *buf = fsl_buffer_empty; + } } -int fsl_buffer_reserve( fsl_buffer * const buf, fsl_size_t n ){ +int fsl_buffer_reserve( fsl_buffer * buf, fsl_size_t n ){ if( ! buf ) return FSL_RC_MISUSE; else if( 0 == n ){ - if(!buffer_is_external(buf)){ - fsl_free(buf->mem); - }/* else if it has memory, it's owned elsewhere */ + fsl_free(buf->mem); *buf = fsl_buffer_empty; return 0; - }else if( !buffer_is_external(buf) && buf->capacity >= n ){ - assert(buf->mem); + }else if( buf->capacity >= n ){ return 0; }else{ unsigned char * x; - bool const isExt = buffer_is_external(buf); assert((buf->used < n) && "Buffer in-use greater than capacity!"); - if(isExt && n<=buf->used){ - /*For external buffers, always keep at least the initially-pointed-to - size. */ - n = buf->used + 1; - } - x = (unsigned char *)fsl_realloc( isExt ? NULL : buf->mem, n ); - if( !x ) return FSL_RC_OOM; - else if(isExt){ - memcpy( x, buf->mem, buf->used ); - x[buf->used] = 0; - }else{ - memset( x + buf->used, 0, n - buf->used ); - } + x = (unsigned char *)fsl_realloc( buf->mem, n ); + if( ! x ) return FSL_RC_OOM; + memset( x + buf->used, 0, n - buf->used ); buf->mem = x; buf->capacity = n; return 0; } } -int fsl_buffer_resize( fsl_buffer * const b, fsl_size_t n ){ - if(buffer_is_external(b)){ - if(n==b->used) return 0; - else if(n==0){ - b->capacity = 0; - fsl_buffer_external(b, "", 0); - return 0; - } - unsigned char * x = (unsigned char *)fsl_malloc( n+1/*NUL*/ ); - if( !x ) return FSL_RC_OOM; - memcpy(x, b->mem, n < b->used ? n : b->used); - x[n] = 0; - b->mem = x; - b->capacity = n+1; - b->used = n; - return 0; - }else if(n && (b->capacity == n+1)){ - b->used = n; - b->mem[n] = 0; +int fsl_buffer_resize( fsl_buffer * buf, fsl_size_t n ){ + if( !buf ) return FSL_RC_MISUSE; + else if(n && (buf->capacity == n+1)){ + buf->used = n; + buf->mem[n] = 0; return 0; }else{ - unsigned char * x = (unsigned char *)fsl_realloc( b->mem, + unsigned char * x = (unsigned char *)fsl_realloc( buf->mem, n+1/*NUL*/ ); if( ! x ) return FSL_RC_OOM; - if(n > b->capacity){ + if(n > buf->capacity){ /* zero-fill new parts */ - memset( x + b->capacity, 0, n - b->capacity +1/*NUL*/ ); + memset( x + buf->capacity, 0, n - buf->capacity +1/*NUL*/ ); } - b->capacity = n + 1 /*NUL*/; - b->used = n; - b->mem = x; - b->mem[b->used] = 0; + buf->capacity = n + 1 /*NUL*/; + buf->used = n; + buf->mem = x; + buf->mem[buf->used] = 0; return 0; } } -int fsl_buffer_compare(fsl_buffer const * const lhs, fsl_buffer const * const rhs){ +int fsl_buffer_compare(fsl_buffer const * lhs, fsl_buffer const * rhs){ fsl_size_t const szL = lhs->used; fsl_size_t const szR = rhs->used; fsl_size_t const sz = (szLmem, rhs->mem, sz); if(0 == rc){ @@ -3724,11 +3642,11 @@ /* Compare two blobs in constant time and return zero if they are equal. Constant time comparison only applies for blobs of the same length. If lengths are different, immediately returns 1. */ -int fsl_buffer_compare_O1(fsl_buffer const * const lhs, fsl_buffer const * const rhs){ +int fsl_buffer_compare_O1(fsl_buffer const * lhs, fsl_buffer const * rhs){ fsl_size_t const szL = lhs->used; fsl_size_t const szR = rhs->used; fsl_size_t i; unsigned char const *buf1; unsigned char const *buf2; @@ -3741,27 +3659,32 @@ } return rc; } -int fsl_buffer_append( fsl_buffer * const b, - void const * const data, +int fsl_buffer_append( fsl_buffer * b, + void const * data, fsl_int_t len ){ - fsl_size_t sz = b->used; - if(len<0) len = (fsl_int_t)fsl_strlen((char const *)data); - if(buffer_materialize(b, (fsl_size_t)len + 1)) return FSL_RC_OOM; - assert(b->capacity ? !!b->mem : !b->mem); - assert(b->used <= b->capacity); - sz += len + 1/*NUL*/; - int const rc = b->capacitycapacity >= sz); - if(len>0) memcpy(b->mem + b->used, data, (size_t)len); - b->used += len; - b->mem[b->used] = 0; - } - return rc; + if(!b || !data) return FSL_RC_MISUSE; + else{ + fsl_size_t sz = b->used; + int rc = 0; + assert(b->capacity ? !!b->mem : !b->mem); + assert(b->used <= b->capacity); + if(len<0){ + len = (fsl_int_t)fsl_strlen((char const *)data); + } + sz += len + 1/*NUL*/; + rc = b->capacitycapacity >= sz); + if(len>0) memcpy(b->mem + b->used, data, (size_t)len); + b->used += len; + b->mem[b->used] = 0; + } + return rc; + } } int fsl_buffer_appendfv( fsl_buffer * const b, char const * fmt, va_list args){ return fsl_appendfv( fsl_output_f_buffer, b, fmt, args ); @@ -3779,39 +3702,37 @@ va_end(args); return rc; } } -char const * fsl_buffer_cstr(fsl_buffer const * const b){ +char const * fsl_buffer_cstr(fsl_buffer const *b){ return b ? (char const *)b->mem : NULL; } -char const * fsl_buffer_cstr2(fsl_buffer const * const b, fsl_size_t * const len){ +char const * fsl_buffer_cstr2(fsl_buffer const *b, fsl_size_t * len){ char const * rc = NULL; if(b){ rc = (char const *)b->mem; if(len) *len = b->used; } return rc; } -char * fsl_buffer_str(fsl_buffer const * const b){ - return (char *)b->mem; +char * fsl_buffer_str(fsl_buffer const *b){ + return b ? (char *)b->mem : NULL; } -#if 0 -fsl_size_t fsl_buffer_size(fsl_buffer const * const b){ - return b->used; +fsl_size_t fsl_buffer_size(fsl_buffer const * b){ + return b ? b->used : 0U; } -fsl_size_t fsl_buffer_capacity(fsl_buffer const * const b){ - return b->capacity; +fsl_size_t fsl_buffer_capacity(fsl_buffer const * b){ + return b ? b->capacity : 0; } -#endif -bool fsl_data_is_compressed(unsigned char const * const mem, fsl_size_t len){ +bool fsl_data_is_compressed(unsigned char const * mem, fsl_size_t len){ if(!mem || (len<6)) return 0; #if 0 else return ('x'==mem[4]) && (0234==mem[5]); /* @@ -3975,89 +3896,52 @@ } return rc; } } -int fsl_buffer_uncompress(fsl_buffer const * const pIn, fsl_buffer * const pOut){ +int fsl_buffer_uncompress(fsl_buffer const *pIn, fsl_buffer *pOut){ unsigned int nOut; unsigned char *inBuf; - unsigned int const nIn = pIn->used; + unsigned int nIn = pIn->used; fsl_buffer temp = fsl_buffer_empty; int rc; unsigned long int nOut2; - if(nIn<=4 || !fsl_data_is_compressed(pIn->mem, pIn->used)){ - if(pIn==pOut || !pIn->mem) rc = 0; - else{ - fsl_buffer_reuse(pOut); - rc = fsl_buffer_append(pOut, pIn->mem, pIn->used); - } - return rc; + if( nIn<=4 ){ + return FSL_RC_RANGE; } inBuf = pIn->mem; nOut = (inBuf[0]<<24) + (inBuf[1]<<16) + (inBuf[2]<<8) + inBuf[3]; /* MARKER(("decompress size: %u\n", nOut)); */ - if(pIn!=pOut && pOut->capacity>=nOut+1){ - assert(pIn->mem != pOut->mem); -#if 0 - /* why does this cause corruption (in the form of overwriting a - buffer somewhere in the fsl_content_get() constellation)? - fsl_repo_rebuild() works but fsl_repo_extract() can trigger - it: - - (FSL_RC_RANGE): Delta: copy extends past end of input - */ - fsl_buffer_external(&temp, pOut->mem, pOut->capacity); -#else - fsl_buffer_swap(&temp, pOut); -#endif - }else{ - rc = fsl_buffer_reserve(&temp, nOut+1); - if(rc) return rc; - temp.mem[nOut] = 0; - } - + rc = fsl_buffer_reserve(&temp, nOut+1); + if(rc) return rc; nOut2 = (long int)nOut; - rc = uncompress(temp.mem, &nOut2, &inBuf[4], nIn - 4) - /* In some libz versions (<1.2.4, apparently), valgrind says - there's an uninitialized memory access somewhere under - uncompress(), _presumably_ for one of these arguments, but i - can't find it. fsl_buffer_reserve() always memsets() new bytes - to 0. + rc = uncompress(temp.mem, &nOut2, + &inBuf[4], nIn - 4) + /* valgrind says there's an uninitialized memory access + somewhere under uncompress(), _presumably_ for one of + these arguments, but i can't find it. fsl_buffer_reserve() + always memsets() new bytes to 0. Turns out it's a known problem: https://www.zlib.net/zlib_faq.html#faq36 */; - switch(rc){ - case 0: - /* this is always true but having this assert - here makes me nervous: assert(nOut2 == nOut); */ - assert(nOut2<=nOut); - temp.mem[nOut2] = 0; - temp.used = (fsl_size_t)nOut2; -#if 1 - fsl_buffer_swap(&temp, pOut); -#else - if(temp.mem!=pOut->mem){ - if(pOut->capacity>=temp.capacity){ - pOut->used = 0; - MARKER(("uncompress() re-using target buffer.\n")); - fsl_buffer_append(pOut, temp.mem, temp.capacity); - }else{ - fsl_buffer_swap(pOut, &temp); - } - } -#endif - break; - case Z_DATA_ERROR: rc = FSL_RC_CONSISTENCY; break; - case Z_MEM_ERROR: rc = FSL_RC_OOM; break; - case Z_BUF_ERROR: - assert(!"Cannot happen!"); - rc = FSL_RC_RANGE; break; - default: rc = FSL_RC_ERROR; break; - } - if(temp.mem!=pOut->mem) fsl_buffer_clear(&temp); + if( rc!=Z_OK ){ + fsl_buffer_reserve(&temp, 0); + return FSL_RC_ERROR; + } + rc = fsl_buffer_resize(&temp, nOut2); + if(!rc){ + temp.used = (fsl_size_t)nOut2; + if( pOut==pIn ){ + fsl_buffer_reserve(pOut, 0); + } + assert(!pOut->mem); + *pOut = temp; + }else{ + fsl_buffer_reserve(&temp, 0); + } return rc; } int fsl_buffer_fill_from( fsl_buffer * const dest, fsl_input_f src, @@ -4142,14 +4026,14 @@ return src->used ? fsl_buffer_append( dest, src->mem, src->used ) : 0; } -int fsl_buffer_delta_apply2( fsl_buffer const * const orig, - fsl_buffer const * const pDelta, - fsl_buffer * const pTarget, - fsl_error * const pErr){ +int fsl_buffer_delta_apply2( fsl_buffer const * orig, + fsl_buffer const * pDelta, + fsl_buffer * pTarget, + fsl_error * pErr){ int rc; fsl_size_t n = 0; fsl_buffer out = fsl_buffer_empty; rc = fsl_delta_applied_size( pDelta->mem, pDelta->used, &n); if(rc){ @@ -4161,28 +4045,32 @@ rc = fsl_buffer_resize( &out, n ); if(rc) return rc; rc = fsl_delta_apply2( orig->mem, orig->used, pDelta->mem, pDelta->used, out.mem, pErr); - if(0==rc){ - fsl_buffer_swap(&out, pTarget); + if(rc){ + fsl_buffer_clear(&out); + }else{ + fsl_buffer_clear(pTarget); + *pTarget = out; } - fsl_buffer_clear(&out); return rc; } -int fsl_buffer_delta_apply( fsl_buffer const * const orig, - fsl_buffer const * const pDelta, - fsl_buffer * const pTarget){ +int fsl_buffer_delta_apply( fsl_buffer const * orig, + fsl_buffer const * pDelta, + fsl_buffer * pTarget){ return fsl_buffer_delta_apply2(orig, pDelta, pTarget, NULL); } -void fsl_buffer_defossilize( fsl_buffer * const b ){ - fsl_bytes_defossilize( b->mem, &b->used ); +void fsl_buffer_defossilize( fsl_buffer * b ){ + if(b){ + fsl_bytes_defossilize( b->mem, &b->used ); + } } -int fsl_buffer_to_filename( fsl_buffer const * const b, char const * fname ){ +int fsl_buffer_to_filename( fsl_buffer const * b, char const * fname ){ FILE * f; int rc = 0; if(!b || !fname) return FSL_RC_MISUSE; f = fsl_fopen(fname, "wb"); if(!f) rc = fsl_errno_to_rc(errno, FSL_RC_IO); @@ -4194,28 +4082,35 @@ fsl_fclose(f); } return rc; } -int fsl_buffer_delta_create( fsl_buffer const * const src, - fsl_buffer const * const newVers, - fsl_buffer * const delta){ - if((src == newVers) - || (src==delta) - || (newVers==delta)) return FSL_RC_MISUSE; - int rc = fsl_buffer_reserve( delta, newVers->used + 60 ); - if(!rc){ - delta->used = 0; - rc = fsl_delta_create( src->mem, src->used, - newVers->mem, newVers->used, - delta->mem, &delta->used ); - } - return rc; +int fsl_buffer_delta_create( fsl_buffer const * src, + fsl_buffer const * newVers, + fsl_buffer * delta){ + if(!src || !newVers || !delta) return FSL_RC_MISUSE; + else if((src == newVers) + || (src==delta) + || (newVers==delta)) return FSL_RC_MISUSE; + else{ + int rc = fsl_buffer_reserve( delta, newVers->used + 60 ); + if(!rc){ + delta->used = 0; + rc = fsl_delta_create( src->mem, src->used, + newVers->mem, newVers->used, + delta->mem, &delta->used ); + if(!rc){ + rc = fsl_buffer_resize( delta, delta->used ); + } + } + return rc; + } } -int fsl_output_f_buffer( void * state, void const * src, fsl_size_t n ){ +int fsl_output_f_buffer( void * state, + void const * src, fsl_size_t n ){ return (!state || !src) ? FSL_RC_MISUSE : fsl_buffer_append((fsl_buffer*)state, src, n); } @@ -4230,12 +4125,13 @@ const struct tm *timeptr){ if(!b || !format || !*format || !timeptr) return FSL_RC_MISUSE; else{ enum {BufSize = 128}; char buf[BufSize]; - fsl_size_t const len = fsl_strftime(buf, BufSize, format, timeptr); - return len ? fsl_buffer_append(b, buf, (fsl_int_t)len) : FSL_RC_RANGE; + fsl_size_t len = fsl_strftime(buf, BufSize, format, timeptr); + if(!len) return FSL_RC_RANGE; + return fsl_buffer_append(b, buf, (fsl_int_t)len); } } int fsl_buffer_stream_lines(fsl_output_f fTo, void * const toState, fsl_buffer * const pFrom, fsl_size_t N){ @@ -4352,15 +4248,12 @@ return rc; } } char * fsl_buffer_take(fsl_buffer * const b){ - char * z = NULL; - if(0==buffer_materialize(b,0)){ - z = (char *)b->mem; - *b = fsl_buffer_empty; - } + char * z = (char *)b->mem; + *b = fsl_buffer_empty; return z; } fsl_size_t fsl_buffer_seek(fsl_buffer * const b, fsl_int_t offset, fsl_buffer_seek_e whence){ @@ -4412,29 +4305,24 @@ } return rc; } int fsl_buffer_append_tcl_literal(fsl_buffer * const b, - bool escapeSquigglies, char const * z, fsl_int_t n){ int rc; if(n<0) n = fsl_strlen(z); rc = fsl_buffer_append(b, "\"", 1); for(fsl_int_t i=0; 0==rc && iused; - fsl_buffer * const fbuf = &f->cache.fileContent; + fsl_buffer * fbuf = &f->fileContent; char const * fn; int rc; fsl_id_t fnid = 0; fsl_id_t rcRid = 0; assert(!fbuf->used && "Misuse of f->fileContent"); @@ -4899,11 +4783,11 @@ rc = fsl_cx_uplift_db_error2(f, db, fsl_db_transaction_commit(db)); } return rc; } -int fsl_checkin_dequeue(fsl_cx * const f, fsl_checkin_queue_opt const * opt){ +int fsl_checkin_dequeue(fsl_cx * f, fsl_checkin_queue_opt const * opt){ fsl_db * const db = fsl_needs_ckout(f); if(!db) return FSL_RC_NOT_A_CKOUT; int rc = fsl_db_transaction_begin(db); if(rc) return fsl_cx_uplift_db_error2(f, db, rc); fsl_id_bag list = fsl_id_bag_empty; @@ -4940,14 +4824,15 @@ rc = fsl_cx_uplift_db_error2(f, db, fsl_db_transaction_commit(db)); } return rc; } -bool fsl_checkin_is_enqueued(fsl_cx * const f, char const * zName, +bool fsl_checkin_is_enqueued(fsl_cx * f, char const * zName, bool relativeToCwd){ - if(!zName || !*zName) return false; - else if(!fsl_cx_db_ckout(f)) return false; + fsl_db * db; + if(!f || !zName || !*zName) return 0; + else if(!(db = fsl_needs_ckout(f))) return 0; else if(!f->ckin.selectedIds.entryCount){ /* Behave like fsl_is_enqueued() SQL function. */ return true; } else { @@ -4968,11 +4853,12 @@ fsl__cx_scratchpad_yield(f, canon); return rv; } } -void fsl_checkin_discard(fsl_cx * const f){ + +void fsl_checkin_discard(fsl_cx * f){ if(f){ fsl_id_bag_clear(&f->ckin.selectedIds); fsl_deck_finalize(&f->ckin.mf); } } @@ -5791,11 +5677,11 @@ if(!rc) rc = fsl__ckout_version_write(f, d->rid, NULL); RC; assert(d->f == f); rc = fsl_checkin_add_unsent(f, d->rid); RC; - rc = fsl__ckout_clear_merge_state(f, true); + rc = fsl__ckout_clear_merge_state(f); RC; /* todo(?) from fossil(1) follows. Most of this seems to be what the vfile handling does (above). @@ -5885,12 +5771,12 @@ return rc; } #undef MARKER -/* end of file ./src/checkin.c */ -/* start of file ./src/checkout.c */ +/* end of file checkin.c */ +/* start of file checkout.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -5922,12 +5808,12 @@ */ static int fsl_strnicmp_int(char const *zA, char const * zB, fsl_size_t nByte){ return fsl_strnicmp( zA, zB, (fsl_int_t)nByte); } -int fsl_ckout_filename_check( fsl_cx * const f, bool relativeToCwd, - char const * zOrigName, fsl_buffer * const pOut ){ +int fsl_ckout_filename_check( fsl_cx * f, bool relativeToCwd, + char const * zOrigName, fsl_buffer * pOut ){ int rc; if(!zOrigName || !*zOrigName) return FSL_RC_MISUSE; else if(!fsl_needs_ckout(f)/* will update f's error state*/){ return FSL_RC_NOT_A_CKOUT; } @@ -5943,11 +5829,11 @@ else{ char const * zLocalRoot; char const * zFull; fsl_size_t nLocalRoot; fsl_size_t nFull; - fsl_buffer * const full = fsl__cx_scratchpad(f); + fsl_buffer * full = fsl__cx_scratchpad(f); int (*xCmp)(char const *, char const *,fsl_size_t); bool endsWithSlash; assert(f->ckout.dir); zLocalRoot = f->ckout.dir; assert(zLocalRoot); @@ -5969,11 +5855,11 @@ zOrigName); } goto end; } zFull = fsl_buffer_cstr2(full, &nFull); - xCmp = fsl_cx_is_case_sensitive(f,false) + xCmp = fsl_cx_is_case_sensitive(f) ? fsl_strncmp : fsl_strnicmp_int; assert(zFull); assert(nFull>0); endsWithSlash = '/' == zFull[nFull-1]; @@ -6149,29 +6035,19 @@ " WHERE vid=%"FSL_ID_T_PFMT " AND pathname=%Q %s", f->ckout.rid, zFilename, fsl_cx_filename_collation(f)); } - - -/** Initialized-with-defaults fsl_ckout_manage_state structure, intended for - const-copy initialization. */ -#define fsl_ckout_manage_state_empty_m {NULL,NULL,NULL} -/** Initialized-with-defaults fsl_ckout_manage_state structure, intended for - non-const copy initialization. */ -static const fsl_ckout_manage_state fsl_ckout_manage_state_empty -= fsl_ckout_manage_state_empty_m; - /** Internal machinery for fsl_ckout_manage(). zFilename MUST be a checkout-relative file which is known to exist. fst MUST be an object populated by fsl_stat()'ing zFilename. isInVFile MUST be the result of having passed zFilename to fsl_co_is_in_vfile(). */ -static int fsl_ckout_manage_impl(fsl_cx * const f, char const *zFilename, - fsl_fstat const *fst, - bool isInVFile){ +static int fsl_ckout_manage_impl( fsl_cx * f, char const *zFilename, + fsl_fstat const *fst, + bool isInVFile){ int rc = 0; fsl_db * const db = fsl_needs_ckout(f); assert(fsl_is_simple_pathname(zFilename, true)); if( isInVFile ){ rc = fsl_db_exec(db, "UPDATE vfile SET deleted=0," @@ -6225,11 +6101,11 @@ /** Attempts to add file or directory (recursively) cas->absBuf to the current repository. isCrawling must be true if this is a fsl_dircrawl()-invoked call, else false. */ -static int co_add_one(CoAddState * const cas, bool isCrawling){ +static int co_add_one(CoAddState * cas, bool isCrawling){ int rc = 0; fsl_buffer_reuse(cas->coRelBuf); rc = fsl_cx_stat2(cas->f, cas->opt->relativeToCwd, fsl_buffer_cstr(cas->absBuf), &cas->fst, fsl_buffer_reuse(cas->coRelBuf), false) @@ -6256,15 +6132,12 @@ fsl_cx_glob_matches(cas->f, FSL_GLOBS_IGNORE, zCoRel); if(m) skipped = true; } if(!skipped && cas->opt->callback){ bool yes = false; - fsl_ckout_manage_state mst = fsl_ckout_manage_state_empty; - mst.opt = cas->opt; - mst.filename = zCoRel; - mst.f = cas->f; - rc = cas->opt->callback( &mst, &yes ); + rc = cas->opt->callback( zCoRel, &yes, + cas->opt->callbackState ); if(rc) goto end; else if(!yes) skipped = true; } } if(skipped){ @@ -6306,50 +6179,17 @@ } end: return rc; } -/** - fsl_dircrawl_f() impl for fsl_ckout_manage(). -*/ static int fsl_dircrawl_f_add(fsl_dircrawl_state const *dst){ - switch(dst->entryType){ - case FSL_FSTAT_TYPE_DIR: - case FSL_FSTAT_TYPE_FILE:{ - CoAddState * const cas = (CoAddState*)dst->callbackState; - int const rc = fsl_buffer_appendf(fsl_buffer_reuse(cas->absBuf), - "%s/%s", dst->absoluteDir, dst->entryName); - if(rc) return rc; - switch(dst->entryType){ - case FSL_FSTAT_TYPE_DIR: - return fsl_is_top_of_ckout(fsl_buffer_cstr(cas->absBuf)) - /* Never recurse into nested checkouts */ - ? FSL_RC_NOOP : 0; - case FSL_FSTAT_TYPE_FILE: - return co_add_one(cas, true); - default: - fsl__fatal(FSL_RC_ERROR,"Not possible: caught above."); - return 0; - } - } - default: - return 0; - } -} - -/** - Returns true if the absolute path zAbsName is f->ckout.dir, disregarding - an optional trailing slash on zAbsName. -*/ -static bool fsl__is_ckout_dir(fsl_cx * const f, char const * const zAbsName){ - /* Keeping in mind that f->ckout.dir is always slash-terminated...*/ - assert(f->ckout.dirLen>0); - return (0==fsl_strncmp(zAbsName, f->ckout.dir, f->ckout.dirLen-1) - && 0==zAbsName[f->ckout.dirLen-1] - /* ==> matches except that zAbsName is NUL-terminated where - ckout.dir has a trailing slash. */) - || 0==fsl_strcmp(zAbsName, f->ckout.dir); + if(FSL_FSTAT_TYPE_FILE!=dst->entryType) return 0; + CoAddState * cas = (CoAddState*)dst->callbackState; + int rc = fsl_buffer_appendf(fsl_buffer_reuse(cas->absBuf), + "%s/%s", dst->absoluteDir, dst->entryName); + if(!rc) rc = co_add_one(cas, true); + return rc; } int fsl_ckout_manage( fsl_cx * const f, fsl_ckout_manage_opt * const opt_ ){ int rc = 0; CoAddState cas = CoAddState_empty; @@ -6362,17 +6202,14 @@ opt_ from a callback. */; cas.absBuf = fsl__cx_scratchpad(f); cas.coRelBuf = fsl__cx_scratchpad(f); rc = fsl_file_canonical_name(opt.filename, cas.absBuf, false); if(!rc){ - char const * const zAbs = fsl_buffer_cstr(cas.absBuf); - if(!fsl_is_top_of_ckout(zAbs) || fsl__is_ckout_dir(f, zAbs)){ - cas.f = f; - cas.opt = &opt; - rc = co_add_one(&cas, false); - opt_->counts = opt.counts; - } + cas.f = f; + cas.opt = &opt; + rc = co_add_one(&cas, false); + opt_->counts = opt.counts; } fsl__cx_scratchpad_yield(f, cas.absBuf); fsl__cx_scratchpad_yield(f, cas.coRelBuf); return rc; } @@ -6419,18 +6256,10 @@ assert(rc); rc = fsl_cx_uplift_db_error2(f, db, rc); goto end; } -/** Initialized-with-defaults fsl_ckout_unmanage_state structure, intended for - const-copy initialization. */ -#define fsl_ckout_unmanage_state_empty_m {NULL,NULL,NULL} -/** Initialized-with-defaults fsl_ckout_unmanage_state structure, intended for - non-const copy initialization. */ -static const fsl_ckout_unmanage_state fsl_ckout_unmanage_state_empty -= fsl_ckout_unmanage_state_empty_m; - int fsl_ckout_unmanage(fsl_cx * const f, fsl_ckout_unmanage_opt const * opt){ int rc; fsl_db * const db = fsl_needs_ckout(f); fsl_buffer * fname = 0; fsl_id_t const vid = f->ckout.rid; @@ -6509,20 +6338,13 @@ if(rc) goto dberr; } }/*opt->filename*/ if(q.stmt){ - fsl_ckout_unmanage_state ust = fsl_ckout_unmanage_state_empty; - ust.opt = opt; - ust.f = f; while(FSL_RC_STEP_ROW==fsl_stmt_step(&q)){ - rc = fsl_stmt_get_text(&q, 0, &ust.filename, NULL); - if(rc){ - rc = fsl_cx_uplift_db_error2(f, db, rc); - goto end; - } - rc = opt->callback(&ust); + char const * fn = fsl_stmt_g_text(&q, 0, NULL); + rc = opt->callback(fn, opt->callbackState); if(rc) goto end; } fsl_stmt_finalize(&q); } /* Remove rm'd ADDed-but-not-yet-committed entries... */ @@ -6553,21 +6375,21 @@ int fsl_ckout_changes_scan(fsl_cx * const f){ return fsl_vfile_changes_scan(f, -1, 0); } -int fsl__ckout_install_schema(fsl_cx * const f, bool dropIfExists){ +int fsl_ckout_install_schema(fsl_cx * const f, bool dropIfExists){ char const * tNames[] = { "vvar", "vfile", "vmerge", 0 }; int rc; fsl_db * const db = fsl_needs_ckout(f); if(!db) return f->error.code; if(dropIfExists){ char const * t; int i; - char const * dbName = fsl_db_role_name(FSL_DBROLE_CKOUT); + char const * dbName = fsl_db_role_label(FSL_DBROLE_CKOUT); for(i=0; 0!=(t = tNames[i]); ++i){ rc = fsl_db_exec(db, "DROP TABLE IF EXISTS %s.%s /*%s()*/", dbName, t, __func__); if(rc) break; } @@ -6594,27 +6416,18 @@ "OR coalesce(origname != pathname, 0) " "/*%s()*/", __func__) || fsl_db_exists(db,"SELECT 1 FROM vmerge /*%s()*/", __func__); } -int fsl__ckout_clear_merge_state( fsl_cx * const f, bool fullWipe ){ +int fsl__ckout_clear_merge_state( fsl_cx *f ){ + fsl_db * const d = fsl_needs_ckout(f); int rc; - if(fullWipe){ - rc = fsl_cx_exec(f,"DELETE FROM vmerge /*%s()*/", __func__); + if(d){ + rc = fsl_db_exec(d,"DELETE FROM vmerge /*%s()*/", __func__); + rc = fsl_cx_uplift_db_error2(f, d, rc); }else{ - rc = fsl_cx_exec_multi(f, - "DELETE FROM vmerge WHERE id IN(" - "SELECT vm.id FROM vmerge vm, vfile vf " - "WHERE vm.id=vf.id AND vf.chnged=0" - ");" - "DELETE FROM vmerge WHERE NOT EXISTS(" - "SELECT 1 FROM vmerge WHERE id>0" - ") AND NOT EXISTS (" - "SELECT 1 FROM vfile WHERE chnged>1" - ");" - "/*%s()*/", __func__ ); - + rc = FSL_RC_NOT_A_CKOUT; } return rc; } int fsl_ckout_clear_db(fsl_cx *f){ @@ -6626,20 +6439,23 @@ "DELETE FROM vvar WHERE name IN" "('checkout','checkout-hash') " "/*%s()*/", __func__); } +fsl_db * fsl_cx_db_for_role(fsl_cx *, fsl_dbrole_e) + /* defined in cx.c */; + /** Updates f->ckout.dir and dirLen based on the current state of f->ckout.db. Returns 0 on success, FSL_RC_OOM on allocation error, some other code if canonicalization of the name fails (e.g. filesystem error or cwd cannot be resolved). */ static int fsl_update_ckout_dir(fsl_cx *f){ int rc; fsl_buffer ckDir = fsl_buffer_empty; - fsl_db * dbC = fsl__cx_db_for_role(f, FSL_DBROLE_CKOUT); + fsl_db * dbC = fsl_cx_db_for_role(f, FSL_DBROLE_CKOUT); assert(dbC->filename); assert(*dbC->filename); rc = fsl_file_canonical_name(dbC->filename, &ckDir, false); if(rc) return rc; char * zCanon = fsl_buffer_take(&ckDir); @@ -6659,21 +6475,28 @@ } return rc; } -int fsl_repo_open_ckout(fsl_cx * const f, const fsl_repo_open_ckout_opt *opt){ +int fsl_repo_open_ckout(fsl_cx *f, const fsl_repo_open_ckout_opt *opt){ fsl_db *dbC = 0; fsl_buffer *cwd = 0; int rc = 0; - bool didChdir = false; + if(!opt) return FSL_RC_MISUSE; else if(!fsl_needs_repo(f)){ return f->error.code; }else if(fsl_cx_db_ckout(f)){ return fsl_cx_err_set(f, FSL_RC_MISUSE, "A checkout is already attached."); + } + if(opt->targetDir && *opt->targetDir){ + if(fsl_chdir(opt->targetDir)){ + return fsl_cx_err_set(f, FSL_RC_NOT_FOUND, + "Directory not found or inaccessible: %s", + opt->targetDir); + } } cwd = fsl__cx_scratchpad(f); assert(!cwd->used); if((rc = fsl_cx_getcwd(f, cwd))){ assert(!cwd->used); @@ -6680,19 +6503,10 @@ fsl__cx_scratchpad_yield(f, cwd); return fsl_cx_err_set(f, rc, "Error %d [%s]: unable to " "determine current directory.", rc, fsl_rc_cstr(rc)); } - if(opt->targetDir && *opt->targetDir){ - if(fsl_chdir(opt->targetDir)){ - fsl__cx_scratchpad_yield(f, cwd); - return fsl_cx_err_set(f, FSL_RC_NOT_FOUND, - "Directory not found or inaccessible: %s", - opt->targetDir); - } - didChdir = true; - } /** AS OF HERE: do not use 'return'. Use goto end so that we can chdir() back to our original cwd! */ if(!fsl_dir_is_empty("."/*we've already chdir'd if @@ -6730,41 +6544,45 @@ */ assert(!fsl_cx_db_ckout(f)); const char * dbName = opt->ckoutDbFile ? opt->ckoutDbFile : fsl_preferred_ckout_db_name(); fsl_cx_err_reset(f); - rc = fsl__cx_attach_role(f, dbName, FSL_DBROLE_CKOUT, true); + int fsl_cx_attach_role(fsl_cx * const , const char *, fsl_dbrole_e) + /* defined in cx.c */; + rc = fsl_cx_attach_role(f, dbName, FSL_DBROLE_CKOUT); if(rc) goto end; fsl_db * const theDbC = fsl_cx_db_ckout(f); - dbC = fsl__cx_db_for_role(f, FSL_DBROLE_CKOUT); + dbC = fsl_cx_db_for_role(f, FSL_DBROLE_CKOUT); + assert(theDbC != dbC && "Not anymore."); + assert(theDbC == f->dbMain); + assert(!f->error.code); assert(dbC->name); assert(dbC->filename); - rc = fsl__ckout_install_schema(f, opt->dbOverwritePolicy); + rc = fsl_ckout_install_schema(f, opt->dbOverwritePolicy); if(!rc){ rc = fsl_db_exec(theDbC,"INSERT OR IGNORE INTO " "%s.vvar (name,value) " "VALUES('checkout',0)," "('checkout-hash',null)", dbC->name); } if(rc) rc = fsl_cx_uplift_db_error(f, theDbC); end: - if(didChdir){ - assert(opt->targetDir && *opt->targetDir); - assert(cwd->used /* is this true in the root dir? */); + if(opt->targetDir && *opt->targetDir && cwd->used){ fsl_chdir(fsl_buffer_cstr(cwd)) /* Ignoring error because we have no recovery strategy! */; } fsl__cx_scratchpad_yield(f, cwd); if(!rc){ - fsl_db * const dbR = fsl__cx_db_for_role(f, FSL_DBROLE_REPO); + fsl_db * const dbR = fsl_cx_db_for_role(f, FSL_DBROLE_REPO); assert(dbR); assert(dbR->filename && *dbR->filename); rc = fsl_config_set_text(f, FSL_CONFDB_CKOUT, "repository", dbR->filename); } if(!rc) rc = fsl_update_ckout_dir(f); + fsl_buffer_clear(cwd); return rc; } int fsl__is_locally_modified(fsl_cx * const f, const char * zFilename, @@ -6998,11 +6816,11 @@ fsl_ckup_state coState = fsl_ckup_state_empty; fsl_time_t mtime = 0; fsl_fstat fst = fsl_fstat_empty; fsl_ckup_localmod_e modType = FSL_RECO_MOD_UNKNOWN; bool loadedContent = false; - fsl_buffer * const content = &f->cache.fileContent; + fsl_buffer * content = &f->fileContent; assert(0==content->used && "Internal Misuse of fsl_cx::fileContent buffer."); //assert(xs->content); assert(xs->fCard->uuid && "We shouldn't be getting deletions " "via delta manifests."); @@ -7345,11 +7163,11 @@ fsl_size_t nFn = 0; char const * fn = fsl_stmt_g_text(&q, 0, &nFn); absPath->used = ckdirLen; rc = fsl_buffer_append(absPath, fn, nFn); if(rc) break; - fsl__ckout_rm_empty_dirs(f, absPath) + fsl_ckout_rm_empty_dirs(f, absPath) /* To see this in action, use (f-co tip) to check out the tip of a repo, then use (f-co rid:1) to back up to the initial empty checkin. It "should" leave you with a directory devoid of anything but .fslckout and any non-SCM'd content. */; @@ -7461,11 +7279,11 @@ rc = fsl_ckout_manifest_write(f, -1, -1, -1, NULL); end: if(!rc){ rc = fsl_vfile_unload_except(f, cOpt->checkinRid); - if(!rc) rc = fsl__ckout_clear_merge_state(f, true); + if(!rc) rc = fsl__ckout_clear_merge_state(f); } /* TODO: if "repo-cksum" config db setting is set, confirm R-card of cOpt->checkinRid against on-disk contents. */ @@ -7535,11 +7353,12 @@ ** The record.fn field is used to match files against each other. The ** FV table contains one row for each each unique filename in ** in the current checkout, the pivot, and the version being merged. */ rc = fsl_db_exec_multi(dbC, - "CREATE TEMP TABLE IF NOT EXISTS fv(" + "DROP TABLE IF EXISTS fv;" + "CREATE TEMP TABLE fv(" " fn TEXT %s PRIMARY KEY," /* The filename relative to root */ " idv INTEGER," /* VFILE entry for current version */ " idt INTEGER," /* VFILE entry for target version */ " chnged BOOLEAN," /* True if current version has been edited */ " islinkv BOOLEAN," /* True if current file is a link */ @@ -7547,12 +7366,11 @@ " ridv INTEGER," /* Record ID for current version */ " ridt INTEGER," /* Record ID for target */ " isexe BOOLEAN," /* Does target have execute permission? */ " deleted BOOLEAN DEFAULT 0,"/* File marked by "rm" to become unmanaged */ " fnt TEXT %s" /* Filename of same file on target version */ - ") /*%s()*/; " - "DELETE FROM fv;", + ") /*%s()*/;", collation, collation, __func__ ); if(rc) goto dberr; /* Add files found in the current version */ rc = fsl_db_exec_multi(dbC, @@ -8133,34 +7951,34 @@ }else if(!fsl_str_bool(z)){ z = ""; } for(;*z;++z){ switch(*z){ - case 'r': *m |= FSL_MANIFEST_MAIN; break; - case 'u': *m |= FSL_MANIFEST_UUID; break; - case 't': *m |= FSL_MANIFEST_TAGS; break; + case 'r': *m |= 0x001; break; + case 'u': *m |= 0x010; break; + case 't': *m |= 0x100; break; default: break; } } fsl_free(str); } f->cache.manifestSetting = (short)*m; } -int fsl_ckout_manifest_write(fsl_cx * const f, int manifest, int manifestUuid, +int fsl_ckout_manifest_write(fsl_cx *f, int manifest, int manifestUuid, int manifestTags, - int * const wrote){ + int * wrote){ fsl_db * const db = fsl_needs_ckout(f); if(!db) return FSL_RC_NOT_A_CKOUT; else if(!f->ckout.rid){ return fsl_cx_err_set(f, FSL_RC_RANGE, "Checkout RID is 0, so it has no manifest."); } int W = 0; int rc = 0; - fsl_buffer * const b = fsl__cx_scratchpad(f); - fsl_buffer * const content = &f->cache.fileContent; + fsl_buffer * b = fsl__cx_scratchpad(f); + fsl_buffer * content = &f->fileContent; char * str = 0; fsl_time_t const mtime = f->ckout.mtime>0 ? fsl_julian_to_unix(f->ckout.mtime) : 0; fsl_buffer_reuse(content); @@ -8376,20 +8194,20 @@ end: fsl__cx_scratchpad_yield(f, fn); return rc; } -bool fsl_is_rooted_in_ckout(fsl_cx * const f, char const * const zAbsPath){ +bool fsl_is_rooted_in_ckout(fsl_cx *f, char const *zAbsPath){ return f->ckout.dir ? 0==fsl_strncmp(zAbsPath, f->ckout.dir, f->ckout.dirLen) /* ^^^ fossil(1) uses stricmp() there, but that's a bug. However, NOT using stricmp() on case-insensitive filesystems is arguably also a bug. */ : false; } -int fsl_is_rooted_in_ckout2(fsl_cx * const f, char const * const zAbsPath){ +int fsl_is_rooted_in_ckout2(fsl_cx *f, char const *zAbsPath){ int rc = 0; if(!fsl_is_rooted_in_ckout(f, zAbsPath)){ rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Path is not rooted " "in the current checkout: %s", zAbsPath); @@ -8423,53 +8241,62 @@ /** Queues the directory part of the given filename into temp table fx_revert_rmdir for an eventual rmdir() attempt on it in fsl_revert_rmdir_fini(). */ -static int fsl_revert_rmdir_queue(fsl_cx * const f, fsl_db * const db, - fsl_stmt * const st, +static int fsl_revert_rmdir_queue(fsl_cx * f, fsl_db * db, fsl_stmt * st, char const * zFilename){ int rc = 0; if( !st->stmt ){ - rc = fsl_cx_exec(f, "CREATE TEMP TABLE IF NOT EXISTS " + rc = fsl_db_exec(db, "CREATE TEMP TABLE IF NOT EXISTS " "fx_revert_rmdir(n TEXT PRIMARY KEY) " "WITHOUT ROWID /* %s() */", __func__); - if(0==rc) rc = fsl_cx_prepare(f, st, "INSERT OR IGNORE INTO " - "fx_revert_rmdir(n) " - "VALUES(fsl_dirpart(?,0)) /* %s() */", - __func__); - } - if(0==rc){ - rc = fsl_stmt_bind_step(st, "s", zFilename); - if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc); - } - return rc; + if(rc) goto dberr; + rc = fsl_db_prepare(db, st, "INSERT OR IGNORE INTO " + "fx_revert_rmdir(n) " + "VALUES(fsl_dirpart(?,0)) /* %s() */", + __func__); + if(rc) goto dberr; + } + rc = fsl_stmt_bind_step(st, "s", zFilename); + if(rc) goto dberr; + end: + return rc; + dberr: + rc = fsl_cx_uplift_db_error2(f, db, rc); + goto end; } /** Attempts to rmdir all dirs queued by fsl_revert_rmdir_queue(). Silently ignores rmdir failure but will return non-0 for db errors. */ -static int fsl_revert_rmdir_fini(fsl_cx * const f){ +static int fsl_revert_rmdir_fini(fsl_cx * f, fsl_db * db){ int rc; fsl_stmt st = fsl_stmt_empty; fsl_buffer * const b = fsl__cx_scratchpad(f); - rc = fsl_cx_prepare(f, &st, + rc = fsl_db_prepare(db, &st, "SELECT fsl_ckout_dir()||n " "FROM fx_revert_rmdir " "ORDER BY length(n) DESC /* %s() */", __func__); - while(0==rc && FSL_RC_STEP_ROW == fsl_stmt_step(&st)){ + if(rc) goto dberr; + while(FSL_RC_STEP_ROW == fsl_stmt_step(&st)){ fsl_size_t nDir = 0; char const * zDir = fsl_stmt_g_text(&st, 0, &nDir); fsl_buffer_reuse(b); rc = fsl_buffer_append(b, zDir, (fsl_int_t)nDir); - if(0==rc) fsl__ckout_rm_empty_dirs(f, b); + if(rc) break; + fsl_ckout_rm_empty_dirs(f, b); } + end: fsl__cx_scratchpad_yield(f, b); fsl_stmt_finalize(&st); return rc; + dberr: + rc = fsl_cx_uplift_db_error2(f, db, rc); + goto end; } int fsl_ckout_revert( fsl_cx * const f, fsl_ckout_revert_opt const * opt ){ /** @@ -8508,12 +8335,12 @@ /* Special case: handle "." from ckout root intuitively */ fsl_buffer_reuse(fname); assert(0==*zNorm); } } - rc = fsl_cx_transaction_begin(f); - if(rc) goto end; + rc = fsl_db_transaction_begin(db); + if(rc) goto dberr; inTrans = true; if(opt->scanForChanges){ rc = fsl_vfile_changes_scan(f, 0, 0); if(rc) goto end; } @@ -8548,14 +8375,18 @@ " OR coalesce(origname,pathname)" " <>pathname" ")", -1); } assert(!rc); - rc = fsl_cx_prepare(f, &q, "%b /* %s() */", sql, __func__); + rc = fsl_db_prepare(db, &q, "%b /* %s() */", sql, __func__); fsl__cx_scratchpad_yield(f, sql); sql = 0; - if(rc) goto end; + if(rc) goto dberr; + if((!zNorm || !*zNorm) && !opt->vfileIds){ + rc = fsl__ckout_clear_merge_state(f); + if(rc) goto end; + } while((FSL_RC_STEP_ROW==fsl_stmt_step(&q))){ fsl_id_t const id = fsl_stmt_g_id(&q, 0); fsl_id_t const rid = fsl_stmt_g_id(&q, 1); int32_t const deleted = fsl_stmt_g_int32(&q, 2); char const * const zName = fsl_stmt_g_text(&q, 3, NULL); @@ -8562,13 +8393,13 @@ char const * const zNameOrig = fsl_stmt_g_text(&q, 4, NULL); bool const renamed = zNameOrig ? !!fsl_strcmp(zName, zNameOrig) : false; fsl_ckout_revert_e changeType = FSL_REVERT_NONE; if(!rid){ // Added but not yet checked in. - rc = fsl_cx_exec(f, "DELETE FROM vfile WHERE id=%" FSL_ID_T_PFMT, + rc = fsl_db_exec(db, "DELETE FROM vfile WHERE id=%" FSL_ID_T_PFMT, id); - if(rc) goto end; + if(rc) goto dberr; changeType = FSL_REVERT_UNMANAGE; }else{ int wasWritten = 0; if(renamed){ if((rc=fsl_mkdir_for_file(zNameOrig, true))){ @@ -8593,16 +8424,16 @@ /* Ignore any errors: this operation is an optimization, not a requirement. Worse case, the entry with the old name is left in the filesystem. */ } if(!vfUpdate.stmt){ - rc = fsl_cx_prepare(f, &vfUpdate, + rc = fsl_db_prepare(db, &vfUpdate, "UPDATE vfile SET chnged=0, deleted=0, " "pathname=coalesce(origname,pathname), " "origname=NULL " "WHERE id=?1 /*%s()*/", __func__); - if(rc) goto end; + if(rc) goto dberr; } rc = fsl_stmt_bind_step(&vfUpdate, "R", id) /* Has to be done before fsl__vfile_to_ckout() because that function writes to vfile.pathname. */; if(rc) goto dberr; @@ -8632,22 +8463,19 @@ if(sql) fsl__cx_scratchpad_yield(f, sql); fsl_stmt_finalize(&q); fsl_stmt_finalize(&vfUpdate); if(qRmdir.stmt){ fsl_stmt_finalize(&qRmdir); - if(!rc) rc = fsl_revert_rmdir_fini(f); + if(!rc) rc = fsl_revert_rmdir_fini(f, db); fsl_db_exec(db, "DROP TABLE IF EXISTS fx_revert_rmdir /* %s() */", __func__); } if(opt->vfileIds){ fsl_db_exec_multi(db, "DROP TABLE IF EXISTS fx_revert_id " "/* %s() */", __func__) /* Ignoring result code */; } - if(0==rc){ - rc = fsl__ckout_clear_merge_state(f, false); - } if(inTrans){ int const rc2 = fsl_db_transaction_end(db, !!rc); if(!rc) rc = rc2; } return rc; @@ -8720,11 +8548,11 @@ int rc = 0; fsl_id_t fid = 0; fsl_fstat fst = fsl_fstat_empty; if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT; - if(0>=vid){ + if(0<=vid){ fsl_ckout_version_info(f, &vid, NULL); } fid = fsl_repo_filename_fnid(f, fc->name); if(fid<=0){ rc = fsl_cx_err_get(f, NULL, NULL); @@ -8750,36 +8578,13 @@ } return rc; } -char const ** fsl_ckout_dbnames(void){ - static char const *dbNames[] = {".fslckout", "_FOSSIL_", NULL}; - return dbNames; -} - -char const * fsl_is_top_of_ckout(char const *zDirName){ - // counterpart of fossil(1)'s vfile_top_of_checkout() - enum {BufLen = 2048}; - char nameBuf[BufLen]; - char * z = &nameBuf[0]; - fsl_size_t sz = fsl_strlcpy(z, zDirName, BufLen); - if(sz>=(fsl_size_t)BufLen - 11/*_FOSSIL_/.fslckout suffix*/) return NULL; - char const **dbNames = fsl_ckout_dbnames(); - char const * dbName; - z[sz++] = '/'; - z[sz] = 0; - for( int i = 0; NULL!=(dbName=dbNames[i]); ++i){ - fsl_strlcpy(z + sz , dbName, (fsl_size_t)BufLen - sz); - if(fsl_file_size(z)>=1024) return dbName; - } - return NULL; -} - #undef MARKER -/* end of file ./src/checkout.c */ -/* start of file ./src/cli.c */ +/* end of file checkout.c */ +/* start of file cli.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -8788,19 +8593,12 @@ SPDX-ArtifactOfProjectName: Libfossil SPDX-FileType: Code Heavily indebted to the Fossil SCM project (https://fossil-scm.org). */ + #include /* for strchr() */ -#if !defined(ORG_FOSSIL_SCM_FSL_CORE_H_INCLUDED) -/* When not in the amalgamation build, force assert() to always work... */ -# if defined(NDEBUG) -# undef NDEBUG -# define DEBUG 1 -# endif -#endif -#include /* for the benefit of test apps */ /* Only for debugging */ #include #define MARKER(pfexp) \ do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ @@ -8873,11 +8671,15 @@ FCLI_V3(("Trying to open repo db file [%s]...\n", fcli.transient.repoDbArg)); rc = fsl_repo_open( f, fcli.transient.repoDbArg ); } else if(fcli.clientFlags.checkoutDir){ fsl_buffer dir = fsl_buffer_empty; - char const * dirName = fcli.clientFlags.checkoutDir; + char const * dirName; + rc = fsl_file_canonical_name(fcli.clientFlags.checkoutDir, + &dir, 0); + assert(!rc); + dirName = (char const *)fsl_buffer_cstr(&dir); FCLI_V3(("Trying to open checkout from [%s]...\n", dirName)); rc = fsl_ckout_open_dir(f, dirName, true); FCLI_V3(("checkout open rc=%s\n", fsl_rc_cstr(rc))); @@ -8941,11 +8743,11 @@ } FCliFree = { fsl_list_empty_m }; static void fcli_shutdown(void){ - fsl_cx * const f = fcli.f; + fsl_cx * f = fcli.f; int rc = 0; fsl_error_clear(&fcli.err); fsl_free(fcli.argv)/*contents are in the FCliFree list*/; @@ -8958,11 +8760,11 @@ if(1 && fsl_cx_db_ckout(f)){ /* For testing/demo only: this is implicit when we call fsl_cx_finalize(). */ - rc = fsl_close_scm_dbs(f); + rc = fsl_ckout_close(f); FCLI_V3(("Closed checkout/repo db(s). rc=%s\n", fsl_rc_cstr(rc))); //assert(0==rc); } } fsl_list_clear(&FCliFree.list, fsl_list_v_fsl_free, 0); @@ -9092,20 +8894,20 @@ f_out("\n"); } } if(showGlobal){ if(!showApp){ - f_out("Invoke --help three times (or --help -V -V) to list " + f_out("Invoke --help three times to list " "both the framework- and app-level options.\n"); }else{ f_out("Invoke --help once to list only the " "app-level flags.\n"); } }else{ - f_out("Invoke --help twice (or --help -V) to list the " - "framework-level options. Use --help three times " - "to list both framework- and app-level options.\n"); + f_out("Invoke --help twice to list the framework-level " + "options. Use --help three times to list both " + "framework- and app-level options.\n"); } f_out("\nFlags which require values may be passed as " "--flag=value or --flag value.\n\n"); } @@ -9566,12 +9368,17 @@ } } return rc; } -static int check_help_invoked(void){ - int rc = 0; +static int fcli_setup2(int argc, char const * const * argv, + const fcli_cliflag * flags){ + int rc; + FCliHelpState.flags = flags; + rc = fcli_setup_common1(false, argc, argv); + if(rc) return rc; + assert(!fcli__error->code); if(fcli.transient.helpRequested){ /* Do this last so that we can get the default user name and such for display in the help text. */ fcli_help(); rc = FCLI_RC_HELP; @@ -9579,23 +9386,11 @@ f_out("libfossil version: %s\nCheckin: %s\nCheckin timestamp: %s\n", fsl_library_version(), FSL_LIB_VERSION_HASH, FSL_LIB_VERSION_TIMESTAMP); rc = FCLI_RC_HELP; - } - return rc; -} - -static int fcli_setup2(int argc, char const * const * argv, - const fcli_cliflag * flags){ - int rc; - FCliHelpState.flags = flags; - rc = fcli_setup_common1(false, argc, argv); - if(rc) return rc; - assert(!fcli__error->code); - rc = check_help_invoked(); - if(!rc){ + }else{ rc = fcli_process_flags(flags); if(rc) assert(fcli__error->msg.used); if(!rc){ rc = fcli_setup_common2(); } @@ -9606,17 +9401,22 @@ int fcli_setup_v2(int argc, char const * const * argv, fcli_cliflag const * const cliFlags, fcli_help_info const * const helpInfo ){ if(NULL!=cliFlags) fcli.cliFlags = cliFlags; if(NULL!=helpInfo) fcli.appHelp = helpInfo; - if(cliFlags || fcli.cliFlags){ - return fcli_setup2(argc, argv, cliFlags ? cliFlags : fcli.cliFlags); + if(fcli.cliFlags){ + return fcli_setup2(argc, argv, fcli.cliFlags); } int rc = fcli_setup_common1(true, argc, argv); if(!rc){ - rc = check_help_invoked(); - if(!rc){ + //f_out("fcli.transient.helpRequested=%d\n",fcli.transient.helpRequested); + if(fcli.transient.helpRequested){ + /* Do this last so that we can get the default user name and such + for display in the help text. */ + fcli_help(); + rc = FCLI_RC_HELP; + }else{ if( fcli_flag2(NULL, "no-checkout", NULL) ){ fcli.clientFlags.checkoutDir = NULL; } fcli_flag2(NULL,"user", &fcli.transient.userArg); fcli.config.traceSql = fcli_flag2(NULL,"trace-sql", NULL); @@ -9626,11 +9426,11 @@ } return rc; } int fcli_setup(int argc, char const * const * argv ){ - return fcli_setup_v2(argc, argv, fcli.cliFlags, fcli.appHelp); + return fcli_setup_v2(argc, argv, NULL, NULL); } int fcli_err_report2(bool clear, char const * file, int line){ int errRc = 0; char const * msg = NULL; @@ -9842,15 +9642,14 @@ f_out("%s%s", alias, *(strchr(alias, 0) + 1) ? ", " : ")\n"); alias = strchr(alias, 0) + 1; } } -void * fcli_fax(void * mem){ +void fcli_fax(void * mem){ if(mem){ fsl_list_append( &FCliFree.list, mem ); } - return mem; } int fcli_ckout_show_info(bool useUtc){ fsl_cx * const f = fcli_cx(); int rc = 0; @@ -9872,11 +9671,11 @@ f_out("%*s %s\n", lblWidth, "repository-db:", fsl_cx_db_file_repo(f, NULL)); f_out("%*s %s\n", lblWidth, "checkout-root:", fsl_cx_ckout_dir_name(f, NULL)); - rc = fsl_cx_prepare(f, &st, "SELECT " + rc = fsl_db_prepare(dbR, &st, "SELECT " /*0*/"datetime(event.mtime%s) AS timestampString, " /*1*/"coalesce(euser, user) AS user, " /*2*/"(SELECT group_concat(substr(tagname,5), ', ') FROM tag, tagxref " "WHERE tagname GLOB 'sym-*' AND tag.tagid=tagxref.tagid " "AND tagxref.rid=blob.rid AND tagxref.tagtype>0) as tags, " @@ -9888,15 +9687,16 @@ "AND blob.rid=%"FSL_ID_T_PFMT" " "AND blob.rid=event.objid " "ORDER BY event.mtime DESC", useUtc ? "" : ", 'localtime'", rid); - if(rc) goto end; + if(rc) goto dberr; if( FSL_RC_STEP_ROW != fsl_stmt_step(&st)){ /* fcli_err_set(FSL_RC_ERROR, "Event data for checkout not found."); */ f_out("\nNo 'event' data found. This is only normal for an empty repo.\n"); goto end; + } f_out("%*s %s %s %s (RID %"FSL_ID_T_PFMT")\n", lblWidth, "checkout-version:", fsl_stmt_g_text(&st, 4, NULL), @@ -9905,60 +9705,36 @@ rid ); { /* list parent(s) */ fsl_stmt stP = fsl_stmt_empty; - rc = fsl_cx_prepare(f, &stP, "SELECT " + rc = fsl_db_prepare(dbR, &stP, "SELECT " "uuid, pid, isprim " "FROM plink JOIN blob ON pid=rid " "WHERE cid=%"FSL_ID_T_PFMT" " "ORDER BY isprim DESC, mtime DESC /*sort*/", rid); - if(rc) goto end; + if(rc) goto dberr; while( FSL_RC_STEP_ROW == fsl_stmt_step(&stP) ){ char const * zLabel = fsl_stmt_g_int32(&stP,2) ? "parent:" : "merged-from:"; f_out("%*s %s\n", lblWidth, zLabel, fsl_stmt_g_text(&stP, 0, NULL)); } fsl_stmt_finalize(&stP); } - { - /* list merge parent(s) */ - fsl_stmt stP = fsl_stmt_empty; - rc = fsl_cx_prepare(f, &stP, "SELECT " - "mhash, id FROm vmerge WHERE id<=0"); - if(rc) goto end; - while( FSL_RC_STEP_ROW == fsl_stmt_step(&stP) ){ - char const * zClass; - int32_t const id = fsl_stmt_g_int32(&stP,1); - switch(id){ - case FSL_MERGE_TYPE_INTEGRATE: zClass = "integrate-merge:"; break; - case FSL_MERGE_TYPE_BACKOUT: zClass = "backout-merge:"; break; - case FSL_MERGE_TYPE_CHERRYPICK: zClass = "cherrypick-merge:"; break; - case FSL_MERGE_TYPE_NORMAL: zClass = "merged-with:"; break; - default: - fsl__fatal(FSL_RC_RANGE, - "Unexpected value %"PRIi32" in vmerge.id",id); - break; - } - f_out("%*s %s\n", lblWidth, zClass, - fsl_stmt_g_text(&stP, 0, NULL)); - } - fsl_stmt_finalize(&stP); - } { /* list children */ fsl_stmt stC = fsl_stmt_empty; - rc = fsl_cx_prepare(f, &stC, "SELECT " + rc = fsl_db_prepare(dbR, &stC, "SELECT " "uuid, cid, isprim " "FROM plink JOIN blob ON cid=rid " "WHERE pid=%"FSL_ID_T_PFMT" " "ORDER BY isprim DESC, mtime DESC /*sort*/", rid); - if(rc) goto end; + if(rc) goto dberr; while( FSL_RC_STEP_ROW == fsl_stmt_step(&stC) ){ char const * zLabel = fsl_stmt_g_int32(&stC,2) ? "child:" : "merged-into:"; f_out("%*s %s\n", lblWidth, zLabel, fsl_stmt_g_text(&stC, 0, NULL)); @@ -9974,10 +9750,14 @@ fsl_stmt_g_text(&st, 2, NULL)); f_out("%*s %s\n", lblWidth, "comment:", fsl_stmt_g_text(&st, 3, NULL)); + dberr: + if(rc){ + fsl_cx_uplift_db_error(f, dbR); + } end: fsl_stmt_finalize(&st); return rc; } @@ -10041,12 +9821,11 @@ fcli_err_set(FSL_RC_NOT_A_REPO, "No repository db is opened."); return NULL; } -int fcli_args_to_vfile_ids(fsl_id_bag * const tgt, - fsl_id_t vid, +int fcli_args_to_vfile_ids(fsl_id_bag *tgt, fsl_id_t vid, bool relativeToCwd, bool changedFilesOnly){ if(!fcli.argc){ return fcli_err_set(FSL_RC_MISUSE, "No file/dir name arguments provided."); @@ -10085,11 +9864,11 @@ } } return zEnd; } -void fcli_diff_colors(fsl_dibu_opt * const tgt, fcli_diff_colors_e theme){ +void fcli_diff_colors(fsl_diff_opt * const tgt, fcli_diff_colors_e theme){ char const * zIns = 0; char const * zEdit = 0; char const * zDel = 0; char const * zReset = 0; switch(theme){ @@ -10140,12 +9919,12 @@ #undef FCLI_V3 #undef fcli_empty_m #undef fcli__error #undef MARKER #undef FCLI_USE_SIGACTION -/* end of file ./src/cli.c */ -/* start of file ./src/content.c */ +/* end of file cli.c */ +/* start of file content.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -10168,50 +9947,53 @@ do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ printf pfexp; \ } while(0) -fsl_int_t fsl_content_size( fsl_cx * const f, fsl_id_t blobRid ){ - if(blobRid<=0) return -3; - else if(!fsl_needs_repo(f)) return -4; +fsl_int_t fsl_content_size( fsl_cx * f, fsl_id_t blobRid ){ + fsl_db * dbR = f ? fsl_cx_db_repo(f) : NULL; + if(!f) return -3; + else if(blobRid<=0) return -4; + else if(!dbR) return -5; else{ - int rc = 0; + int rc; fsl_int_t rv = -2; - fsl_stmt * const q = &f->cache.stmt.contentSize; - if(!q->stmt){ - rc = fsl_cx_prepare(f, q, - "SELECT size FROM blob WHERE rid=?1 " - "/*%s()*/",__func__); - if(rc) return -6; - } - rc = fsl_stmt_bind_step(q, "R", blobRid); - if(FSL_RC_STEP_ROW==rc){ - rv = (fsl_int_t)fsl_stmt_g_int64(q, 0); - } - fsl_stmt_reset(q); + fsl_stmt * q = NULL; + rc = fsl_db_prepare_cached(dbR, &q, + "SELECT size FROM blob " + "WHERE rid=? " + "/*%s()*/",__func__); + if(!rc){ + rc = fsl_stmt_bind_id(q, 1, blobRid); + if(!rc){ + if(FSL_RC_STEP_ROW==fsl_stmt_step(q)){ + rv = (fsl_int_t)fsl_stmt_g_int64(q, 0); + } + } + fsl_stmt_cached_yield(q); + } return rv; } } -static bool fsl_content_is_available(fsl_cx * const f, fsl_id_t rid){ +bool fsl_content_is_available(fsl_cx * f, fsl_id_t rid){ fsl_id_t srcid = 0; int rc = 0, depth = 0 /* Limit delta recursion depth */; while( depth++ < 100000 ){ if( fsl_id_bag_contains(&f->cache.blobContent.missing, rid) ){ return false; }else if( fsl_id_bag_contains(&f->cache.blobContent.available, rid) ){ return true; }else if( fsl_content_size(f, rid)<0 ){ fsl_id_bag_insert(&f->cache.blobContent.missing, rid) - /* ignore possible OOM error - not fatal */; + /* ignore possible OOM error */; return false; } rc = fsl_delta_src_id(f, rid, &srcid); if(rc) break; else if( 0==srcid ){ - fsl_id_bag_insert(&f->cache.blobContent.available, rid) - /* ignore possible OOM error - not fatal */; + fsl_id_bag_insert(&f->cache.blobContent.available, rid); return true; } rid = srcid; } if(0==rc){ @@ -10220,66 +10002,55 @@ fsl__fatal(FSL_RC_RANGE,"delta-loop in repository"); } return false; } + int fsl_content_blob( fsl_cx * const f, fsl_id_t blobRid, fsl_buffer * const tgt ){ - fsl_db * const dbR = fsl_needs_repo(f); - if(!dbR) return FSL_RC_NOT_A_REPO; - else if(blobRid<=0){ - return fsl_cx_err_set(f, FSL_RC_RANGE, - "Invalid RID for %s().", __func__); - } - int rc = 0; - fsl_stmt * const q = &f->cache.stmt.contentBlob; - if(!q->stmt){ - rc = fsl_db_prepare( dbR, q, - "SELECT content, size FROM blob " - "WHERE rid=?1" - "/*%s()*/",__func__); - if(rc) goto end; - } - rc = fsl_stmt_bind_id(q, 1, blobRid); - if(!rc && (FSL_RC_STEP_ROW==(rc=fsl_stmt_step(q)))){ - void const * mem = NULL; - fsl_size_t memLen = 0; - int64_t const sz = fsl_stmt_g_int64(q, 1); - if(sz<0){ - rc = fsl_cx_err_set(f, FSL_RC_PHANTOM, - "Cannot fetch content for phantom " - "blob #%"FSL_ID_T_PFMT".", - blobRid); - } - else if(sz){ - rc = fsl_stmt_get_blob(q, 0, &mem, &memLen); - if(rc){ - rc = fsl_cx_err_set(f, rc, - "Error fetching blob content for " - "blob #%"FSL_ID_T_PFMT".", blobRid); - }else{ - fsl_buffer bb = fsl_buffer_empty; - assert(memLen>0); - fsl_buffer_external(&bb, mem, memLen); - rc = fsl_buffer_uncompress(&bb, tgt); - } - }else{ - rc = 0; - fsl_buffer_reuse(tgt); - } - } - else if(FSL_RC_STEP_DONE==rc){ - rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, - "No blob found for rid %"FSL_ID_T_PFMT".", - blobRid); - } - end: - fsl_stmt_reset(q); - if(rc && !f->error.code && dbR->error.code){ - rc = fsl_cx_uplift_db_error2(f, dbR, rc); - } - return rc; + fsl_db * const dbR = fsl_cx_db_repo(f); + if(blobRid<=0) return FSL_RC_RANGE; + else if(!dbR) return FSL_RC_NOT_A_REPO; + else{ + int rc; + fsl_stmt * q = NULL; + rc = fsl_db_prepare_cached( dbR, &q, + "SELECT content, size FROM blob " + "WHERE rid=?" + "/*%s()*/",__func__); + if(!rc){ + rc = fsl_stmt_bind_id(q, 1, blobRid); + if(!rc && (FSL_RC_STEP_ROW==(rc=fsl_stmt_step(q)))){ + void const * mem = NULL; + fsl_size_t memLen = 0; + if(fsl_stmt_g_int64(q, 1)<0){ + rc = fsl_cx_err_set(f, FSL_RC_PHANTOM, + "Cannot fetch content for phantom " + "blob #%"FSL_ID_T_PFMT".", + blobRid); + }else{ + tgt->used = 0; + fsl_stmt_get_blob(q, 0, &mem, &memLen); + if(mem && memLen){ + rc = fsl_buffer_append(tgt, mem, memLen); + if(!rc && fsl_buffer_is_compressed(tgt)){ + rc = fsl_buffer_uncompress(tgt, tgt); + } + } + } + }else if(FSL_RC_STEP_DONE==rc){ + rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, + "No blob found for rid %"FSL_ID_T_PFMT".", + blobRid); + } + fsl_stmt_cached_yield(q); + } + if(rc && !f->error.code && dbR->error.code){ + fsl_cx_uplift_db_error(f, dbR); + } + return rc; + } } bool fsl_content_is_private(fsl_cx * const f, fsl_id_t rid){ fsl_stmt * s1 = NULL; @@ -10315,14 +10086,16 @@ else{ int rc; bool gotIt = 0; fsl_id_t nextRid; fsl__bccache * const ac = &f->cache.blobContent; + fsl_buffer_reuse(tgt); if(fsl_id_bag_contains(&ac->missing, rid)){ /* Early out if we know the content is not available */ return FSL_RC_NOT_FOUND; } + /* Look for the artifact in the cache first */ if(0!=(FSL_CX_F_BLOB_CACHE & f->flags) && fsl_id_bag_contains(&ac->inCache, rid) ){ fsl_size_t i; fsl__bccache_line * line; @@ -10334,11 +10107,10 @@ line->age = ac->nextAge++; return rc; } } } - fsl_buffer_reuse(tgt); ++ac->metrics.misses; nextRid = 0; rc = fsl_delta_src_id(f, rid, &nextRid); /* MARKER(("rc=%d, nextRid=%"FSL_ID_T_PFMT"\n", rc, nextRid)); */ if(rc) return rc; @@ -10347,48 +10119,42 @@ rc = fsl_content_blob(f, rid, tgt); gotIt = 0==rc; }else{ /* Looks like a delta, so let's expand it... */ fsl_int_t n /* number of used entries in 'a' */; + fsl_int_t nAlloc = 10 /* number it items allocated in 'a' */; + fsl_id_t * a = NULL /* array of rids we expand */; fsl_int_t mx; - fsl_id_t * a = NULL; - //fsl_buffer D = fsl_buffer_empty; - fsl_buffer * const delta = &f->cache.deltaContent; + fsl_buffer delta = fsl_buffer_empty; fsl_buffer next = fsl_buffer_empty /* delta-applied content */ ; assert(nextRid>0); - unsigned int nAlloc = 20; - a = (fsl_id_t*)fsl_malloc(sizeof(fsl_id_t) * nAlloc); - if(!a){ - rc = FSL_RC_OOM; - goto end_delta; - } + a = fsl_malloc( sizeof(a[0]) * nAlloc ); + if(!a) return FSL_RC_OOM; a[0] = rid; a[1] = nextRid; n = 1; while( !fsl_id_bag_contains(&ac->inCache, nextRid) - && 0==(rc=fsl_delta_src_id(f, nextRid, &nextRid)) + && !fsl_delta_src_id(f, nextRid, &nextRid) && (nextRid>0)){ /* Figure out how big n needs to be... */ ++n; - if( n >= (fsl_int_t)nAlloc ){ + if( n >= nAlloc ){ /* Expand 'a' */ void * remem; if( n > fsl_db_g_int64(db, 0, "SELECT max(rid) FROM blob")){ rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Infinite loop in delta table."); goto end_delta; } - unsigned int const nAlloc2 = nAlloc * 2; - remem = fsl_realloc(a, nAlloc2 * sizeof(fsl_id_t)); + nAlloc = nAlloc * 2; + remem = fsl_realloc(a, nAlloc*sizeof(a[0])); if(!remem){ rc = FSL_RC_OOM; goto end_delta; } a = (fsl_id_t*)remem; - nAlloc = nAlloc2; - /*MARKER(("deltaIds allocated = %u\n", nAlloc));*/ } a[n] = nextRid; } /** Recursively expand deltas to get the content... @@ -10396,24 +10162,35 @@ mx = n; rc = fsl_content_get( f, a[n], tgt ); /* MARKER(("Getting content for rid #%"FSL_ID_T_PFMT", rc=%d\n", a[n], rc)); */ --n; for( ; !rc && (n>=0); --n){ - rc = fsl_content_blob(f, a[n], delta); + rc = fsl_content_blob(f, a[n], &delta); /* MARKER(("Getting/applying delta rid #%"FSL_ID_T_PFMT", rc=%d\n", a[n], rc)); */ if(rc) goto end_delta; - if(!delta->used){ + if(!delta.used){ assert(!"Is this possible? The fossil tree has a similar " "condition but i naively don't believe it's necessary."); continue; } next = fsl_buffer_empty; - rc = fsl_buffer_delta_apply2(tgt, delta, &next, &f->error); - //assert(FSL_RC_RANGE!=rc); + rc = fsl_buffer_delta_apply2(tgt, &delta, &next, &f->error); if(rc) goto end_delta; #if 1 /* + In my (very simple) tests this cache costs us more than it + saves. TODO: re-test this once we can do a 'rebuild', or + something more intensive than processing a single + manifest's R-card. At that point we can set a f->flags bit + to enable or disable this block for per-use-case + optimization purposes. + + We also probably want to cache fsl_deck instances instead + of Manifest blobs (fsl_buffer) like fossil(1) does, + otherwise this cache really doesn't save us much + work/memory. + 2021-03-24: in a debug build, running: f-parseparty -t c -c -q (i.e.: parse and crosslink all checkin artifacts) @@ -10446,12 +10223,12 @@ fsl_buffer_clear(tgt); #endif *tgt = next; } end_delta: + fsl_buffer_clear(&delta); fsl_free(a); - fsl_buffer_reuse(delta); gotIt = 0==rc; } if(!rc){ rc = fsl_id_bag_insert(gotIt @@ -10478,39 +10255,41 @@ Mark artifact rid as being available now. Update f's cache to show that everything that was formerly unavailable because rid was missing is now available. Returns 0 on success. f must have an opened repo and rid must be valid. */ -static int fsl__content_mark_available(fsl_cx * const f, fsl_id_t rid){ +static int fsl_content_mark_available(fsl_cx * const f, fsl_id_t rid){ fsl_id_bag pending = fsl_id_bag_empty; int rc; fsl_stmt * st = NULL; fsl_db * db = fsl_cx_db_repo(f); assert(f); assert(db); assert(rid>0); if( fsl_id_bag_contains(&f->cache.blobContent.available, rid) ) return 0; rc = fsl_id_bag_insert(&pending, rid); + if(rc) goto end; while( 0==rc && (rid = fsl_id_bag_first(&pending))!=0 ){ fsl_id_bag_remove(&pending, rid); rc = fsl_id_bag_insert(&f->cache.blobContent.available, rid); - if(rc) break; + if(rc) goto end; fsl_id_bag_remove(&f->cache.blobContent.missing, rid); if(!st){ rc = fsl_db_prepare_cached(db, &st, "SELECT rid FROM delta " "WHERE srcid=?" "/*%s()*/",__func__); - if(rc) break; + if(rc) goto end; } rc = fsl_stmt_bind_id(st, 1, rid); while( !rc && (FSL_RC_STEP_ROW==fsl_stmt_step(st)) ){ fsl_id_t const nx = fsl_stmt_g_id(st,0); assert(nx>0); rc = fsl_id_bag_insert(&pending, nx); } } + end: if(st) fsl_stmt_cached_yield(st); fsl_id_bag_clear(&pending); return rc; } @@ -10812,11 +10591,11 @@ "WHERE rid=%"FSL_ID_T_PFMT, rid /* FIXME? use cached statement? */); if( !rc && (srcId==0 || 0==fsl__bccache_check_available(f, srcId)) ){ isDephantomize = true; - rc = fsl__content_mark_available(f, rid); + rc = fsl_content_mark_available(f, rid); } } fsl_stmt_cached_yield(s1); s1 = NULL; if(rc) goto end; @@ -10876,11 +10655,11 @@ (srcId==0 || (0==fsl__bccache_check_available(f,srcId)))){ /* TODO: document what this is for. TODO: figure out what that is. */ - rc = fsl__content_mark_available(f, rid); + rc = fsl_content_mark_available(f, rid); if(rc) goto end; } if( isDephantomize ){ rc = fsl_after_dephantomize(f, rid, false); if(rc) goto end; @@ -10940,12 +10719,12 @@ return 1==fsl_db_g_int32( db, 0, "SELECT 1 FROM shun WHERE uuid=%Q", zUuid); } -int fsl__content_new( fsl_cx * const f, fsl_uuid_cstr uuid, - bool isPrivate, fsl_id_t * const newId ){ +int fsl__content_new( fsl_cx * f, fsl_uuid_cstr uuid, bool isPrivate, + fsl_id_t * newId ){ fsl_id_t rid = 0; int rc; fsl_db * db = fsl_cx_db_repo(f); fsl_stmt * s1 = NULL, * s2 = NULL; int const uuidLen = uuid ? fsl_is_uuid(uuid) : 0; @@ -11020,38 +10799,46 @@ return rc; } int fsl__content_undeltify(fsl_cx * const f, fsl_id_t rid){ int rc; - fsl_db * const db = fsl_needs_repo(f); + fsl_db * db = f ? fsl_cx_db_repo(f) : NULL; fsl_id_t srcid = 0; fsl_buffer x = fsl_buffer_empty; fsl_stmt s = fsl_stmt_empty; - if(!db) return FSL_RC_NOT_A_REPO; + if(!f) return FSL_RC_MISUSE; + else if(!db) return FSL_RC_NOT_A_REPO; else if(rid<=0) return FSL_RC_RANGE; rc = fsl_db_transaction_begin(db); if(rc) return fsl_cx_uplift_db_error2(f, db, rc); /* Reminder: the original impl does not do this in a transaction, _possibly_ because it's only done from places where a transaction is active (that's unconfirmed). - Nested transactions are very cheap, though. */ + Nested transactions are very cheap, though. + */ rc = fsl_delta_src_id( f, rid, &srcid ); if(rc || srcid<=0) goto end; rc = fsl_content_get(f, rid, &x); if( rc || !x.used ) goto end; + /* TODO? use cached statements */ rc = fsl_db_prepare(db, &s, "UPDATE blob SET content=?," " size=%" FSL_SIZE_T_PFMT " WHERE rid=%" FSL_ID_T_PFMT, x.used, rid); if(rc) goto dberr; rc = fsl_buffer_compress(&x, &x); if(rc) goto end; - rc = fsl_stmt_bind_step(&s, "B", &x); + rc = fsl_stmt_bind_blob(&s, 1, x.mem, + (fsl_int_t)x.used, 0); if(rc) goto dberr; - rc = fsl_db_exec(db, "DELETE FROM delta WHERE rid=%"FSL_ID_T_PFMT, - rid); + rc = fsl_stmt_step(&s); + if(FSL_RC_STEP_DONE==rc) rc = 0; + else goto dberr; + rc = fsl_db_exec(db, "DELETE FROM delta " + "WHERE rid=%"FSL_ID_T_PFMT, + (fsl_id_t)rid); if(rc) goto dberr; #if 0 /* fossil does not do this, but that seems like an inconsistency. @@ -11085,15 +10872,16 @@ int fsl__content_deltify(fsl_cx * f, fsl_id_t rid, fsl_id_t srcid, bool force){ fsl_id_t s; fsl_buffer data = fsl_buffer_empty; fsl_buffer src = fsl_buffer_empty; - fsl_buffer * const delta = &f->cache.deltaContent; - fsl_db * const db = fsl_needs_repo(f); + fsl_buffer delta = fsl_buffer_empty; + fsl_db * db = f ? fsl_cx_db_repo(f) : NULL; int rc = 0; enum { MinSizeThreshold = 50 }; - if(rid<=0 || srcid<=0) return FSL_RC_RANGE; + if(!f) return FSL_RC_MISUSE; + else if(rid<=0 || srcid<=0) return FSL_RC_RANGE; else if(!db) return FSL_RC_NOT_A_REPO; else if( srcid==rid ) return 0; else if(!fsl_content_is_available(f, rid)){ return 0; } @@ -11135,27 +10923,28 @@ } if(rc) return rc; /* As of here, don't return on error. Use (goto end) instead, or be really careful, b/c buffers might need cleaning. */ rc = fsl_content_get(f, srcid, &src); - if(rc || (src.used < MinSizeThreshold) + if(rc + || (src.used < MinSizeThreshold) /* See API doc comments about minimum size to delta/undelta. */ ) goto end; rc = fsl_content_get(f, rid, &data); if(rc || (data.used < MinSizeThreshold)) goto end; - rc = fsl_buffer_delta_create(&src, &data, delta); - if( !rc && (delta->used <= (data.used * 3 / 4 /* 75% */))){ + rc = fsl_buffer_delta_create(&src, &data, &delta); + if( !rc && (delta.used <= (data.used * 3 / 4 /* 75% */))){ fsl_stmt * s1 = NULL; fsl_stmt * s2 = NULL; - rc = fsl_buffer_compress(delta, &data); + rc = fsl_buffer_compress(&delta, &delta); if(rc) goto end; rc = fsl_db_prepare_cached(db, &s1, "UPDATE blob SET content=? " "WHERE rid=?/*%s()*/",__func__); if(!rc){ fsl_stmt_bind_id(s1, 2, rid); - rc = fsl_stmt_bind_blob(s1, 1, data.mem, data.used, 0); + rc = fsl_stmt_bind_blob(s1, 1, delta.mem, delta.used, 0); if(!rc){ rc = fsl_db_prepare_cached(db, &s2, "REPLACE INTO delta(rid,srcid) " "VALUES(?,?)/*%s()*/",__func__); if(!rc){ @@ -11182,11 +10971,11 @@ if(rc && db->error.code && !f->error.code){ fsl_cx_uplift_db_error(f,db); } fsl_buffer_clear(&src); fsl_buffer_clear(&data); - fsl_buffer_reuse(delta); + fsl_buffer_clear(&delta); return rc; } /** Removes all entries from the repo's blob table which are listed in @@ -11200,12 +10989,11 @@ else if(!db) return FSL_RC_NOT_A_REPO; rc = fsl_db_transaction_begin(db); if(rc) return rc; rc = fsl_db_exec_multi(db, "CREATE TEMP TABLE IF NOT EXISTS " - "toshun(rid INTEGER PRIMARY KEY); " - "DELETE FROM toshun; " + "toshun(rid INTEGER PRIMARY KEY);" "INSERT INTO toshun SELECT rid FROM blob, shun " "WHERE blob.uuid=shun.uuid;" ); if(rc) goto end; /* Ensure that deltas generated from the to-be-shunned data @@ -11222,11 +11010,11 @@ fsl_stmt_finalize(&q); if(!rc){ rc = fsl_db_exec_multi(db, "DELETE FROM delta WHERE rid IN toshun;" "DELETE FROM blob WHERE rid IN toshun;" - "DELETE FROM toshun;" + "DROP TABLE toshun;" "DELETE FROM private " "WHERE NOT EXISTS " "(SELECT 1 FROM blob WHERE rid=private.rid);" ); } @@ -11251,12 +11039,12 @@ /** Load the record ID rid and up to N-1 closest ancestors into the "fsl_computed_ancestors" table. */ -static int fsl__compute_ancestors( fsl_db * const db, fsl_id_t rid, - int N, bool directOnly ){ +static int fsl_compute_ancestors( fsl_db * db, fsl_id_t rid, + int N, char directOnly ){ fsl_stmt st = fsl_stmt_empty; int rc = fsl_db_prepare(db, &st, "WITH RECURSIVE " " ancestor(rid, mtime) AS (" " SELECT ?, mtime " @@ -11271,19 +11059,23 @@ "INSERT INTO fsl_computed_ancestors" " SELECT rid FROM ancestor;", directOnly ? "AND plink.isPrim" : "" ); if(!rc){ - rc = fsl_stmt_bind_step(&st, "RRi", rid, rid, (int32_t)N); + fsl_stmt_bind_id(&st, 1, rid); + fsl_stmt_bind_id(&st, 2, rid); + fsl_stmt_bind_int32(&st, 3, (int32_t)N); + rc = fsl_stmt_step(&st); + if(FSL_RC_STEP_DONE==rc){ + rc = 0; + } } fsl_stmt_finalize(&st); return rc; } -int fsl_mtime_of_F_card(fsl_cx * const f, fsl_id_t vid, - fsl_card_F const * const fc, - fsl_time_t * const pMTime){ +int fsl_mtime_of_F_card(fsl_cx * f, fsl_id_t vid, fsl_card_F const * fc, fsl_time_t *pMTime){ if(!f || !fc) return FSL_RC_MISUSE; else if(vid<=0) return FSL_RC_RANGE; else if(!fc->uuid){ if(pMTime) *pMTime = 0; return 0; @@ -11296,15 +11088,14 @@ return fsl_mtime_of_manifest_file(f, vid, fid, pMTime); } } } -int fsl_mtime_of_manifest_file(fsl_cx * const f, fsl_id_t vid, fsl_id_t fid, - fsl_time_t * const pMTime){ - fsl_db * const db = fsl_needs_repo(f); +int fsl_mtime_of_manifest_file(fsl_cx * f, fsl_id_t vid, fsl_id_t fid, fsl_time_t *pMTime){ + fsl_db * db = fsl_needs_repo(f); fsl_stmt * q = NULL; - int rc = 0; + int rc; if(!db) return FSL_RC_NOT_A_REPO; if(fid<=0){ /* Only fetch the checkin time... */ int64_t i = -1; @@ -11326,16 +11117,15 @@ keep only the copy associated with f->cache.mtimeManifest around. For the general case, we will be feeding this function files from the same manifest. */ f->cache.mtimeManifest = vid; - rc = fsl_db_exec_multi(db, "CREATE TEMP TABLE IF NOT EXISTS " - "fsl_computed_ancestors" - "(x INTEGER PRIMARY KEY); " - "DELETE FROM fsl_computed_ancestors;"); + rc = fsl_db_exec_multi(db,"DROP TABLE IF EXISTS temp.fsl_computed_ancestors;" + "CREATE TEMP TABLE fsl_computed_ancestors" + "(x INTEGER PRIMARY KEY);"); if(!rc){ - rc = fsl__compute_ancestors(db, vid, 1000000, 1); + rc = fsl_compute_ancestors(db, vid, 1000000, 1); } if(rc){ fsl_cx_uplift_db_error(f, db); return rc; } @@ -11355,18 +11145,16 @@ }else{ assert(rc); if(FSL_RC_STEP_DONE==rc) rc = FSL_RC_NOT_FOUND; } fsl_stmt_cached_yield(q); - /* Reminder: DO NOT clean up fsl_computed ancestors here. Doing so - is not only costly later on but also breaks test code. */ } return rc; } int fsl_card_F_content( fsl_cx * f, fsl_card_F const * fc, - fsl_buffer * const dest ){ + fsl_buffer * dest ){ if(!f || !fc || !dest) return FSL_RC_MISUSE; else if(!fc->uuid){ return fsl_cx_err_set(f, FSL_RC_RANGE, "Cannot fetch content of a deleted file " "because it has no UUID."); @@ -11426,23 +11214,24 @@ char const * zName, fsl_id_t parentRid, fsl_id_t *rid, fsl_uuid_str * uuid ){ fsl_buffer * canon = 0; // canonicalized filename fsl_buffer * nbuf = 0; // filename buffer + fsl_buffer * fbuf = &f->fileContent; // file content buffer char const * fn; int rc; fsl_id_t fnid = 0; fsl_id_t rcRid = 0; fsl_db * db = f ? fsl_needs_repo(f) : NULL; char inTrans = 0; if(!zName || !*zName) return FSL_RC_MISUSE; else if(!f->ckout.dir) return FSL_RC_NOT_A_CKOUT; else if(!db) return FSL_RC_NOT_A_REPO; - fsl_buffer * const fbuf = fsl__cx_content_buffer(f); canon = fsl__cx_scratchpad(f); nbuf = fsl__cx_scratchpad(f); + assert(!fbuf->used && "Misuse of f->fileContent"); assert(f->ckout.dir); /* Normalize the name... i often regret having fsl_ckout_filename_check() return checkout-relative paths. */ @@ -11584,12 +11373,12 @@ fsl_stmt_finalize(&q); return rc; } #undef MARKER -/* end of file ./src/content.c */ -/* start of file ./src/config.c */ +/* end of file content.c */ +/* start of file config.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -12733,12 +12522,12 @@ #undef fsl__configs_get_x1 #undef fsl__configs_get_x2 #undef SELECT_FROM_CONFIG #undef MARKER #undef ARRAYLEN -/* end of file ./src/config.c */ -/* start of file ./src/cx.c */ +/* end of file config.c */ +/* start of file cx.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -12755,10 +12544,11 @@ #if !defined(FSL_ENABLE_SQLITE_REGEXP) # define FSL_ENABLE_SQLITE_REGEXP 0 #endif #if FSL_ENABLE_SQLITE_REGEXP #endif +#include "sqlite3.h" #include #if defined(_WIN32) # include # define F_OK 0 @@ -12767,14 +12557,13 @@ # include /* F_OK */ #endif #include #include -#include /* FILE class */ -#include /* Only for debugging */ +#include #define MARKER(pfexp) \ do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ printf pfexp; \ } while(0) @@ -12813,16 +12602,17 @@ Results are undefined if !f or f's memory has not been properly initialized. */ static void fsl__cx_reset( fsl_cx * const f, bool closeDatabases ); + int fsl_cx_init( fsl_cx ** tgt, fsl_cx_init_opt const * param ){ static fsl_cx_init_opt paramDefaults = fsl_cx_init_opt_default_m; int rc = 0; fsl_cx * f; - extern int fsl__cx_install_timeline_crosslinkers(fsl_cx * const f) + extern int fsl_cx_install_timeline_crosslinkers(fsl_cx * const f) /*in deck.c*/; if(!tgt) return FSL_RC_MISUSE; else if(!param){ if(!paramDefaults.output.state){ paramDefaults.output.state = stdout; @@ -12882,52 +12672,42 @@ } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); #endif - if(!rc) rc = fsl__cx_install_timeline_crosslinkers(f); + f->dbMem.f = f /* so that dbMem gets fsl_xxx() SQL funcs installed. */; + rc = fsl_db_open( &f->dbMem, "", 0 ); + if(!rc){ + /* Attempt to ensure that the TEMP tables/indexes use FILE storage. */ + rc = fsl_db_exec(&f->dbMem, "PRAGMA temp_store=FILE;"); + } if(!rc){ - f->cache.tempDirs = fsl_temp_dirs_get(); - if(!f->cache.tempDirs) rc = FSL_RC_OOM; + rc = fsl_cx_install_timeline_crosslinkers(f); + } + if(rc){ + if(f->dbMem.error.code){ + fsl_cx_uplift_db_error(f, &f->dbMem); + } + }else{ + f->dbMain = &f->dbMem; + f->dbMem.role = FSL_DBROLE_MAIN; } return rc; } -void fsl__cx_mcache_clear(fsl_cx * const f){ +static void fsl__cx_mcache_clear(fsl_cx * const f){ const unsigned cacheLen = (unsigned)(sizeof(fsl__mcache_empty.aAge) /sizeof(fsl__mcache_empty.aAge[0])); for(unsigned i = 0; i < cacheLen; ++i){ fsl_deck_finalize(&f->cache.mcache.decks[i]); } f->cache.mcache = fsl__mcache_empty; } -void fsl__cx_clear_repo_caches(fsl_cx * const f){ - fsl__bccache_reset(&f->cache.blobContent); - fsl__cx_mcache_clear(f); - fsl__cx_clear_mf_seen(f, false); - f->cache.allowSymlinks = - f->cache.caseInsensitive = - f->cache.seenDeltaManifest = - f->cache.manifestSetting = -1; -} - -static void fsl__cx_finalize_cached_stmt(fsl_cx * const f){ -#define STMT(X) fsl_stmt_finalize(&f->cache.stmt.X) - STMT(deltaSrcId); - STMT(uuidToRid); - STMT(uuidToRidGlob); - STMT(contentSize); - STMT(contentBlob); - STMT(nextEntry); -#undef STMT -} - static void fsl__cx_reset(fsl_cx * const f, bool closeDatabases){ fsl_checkin_discard(f); - fsl__cx_finalize_cached_stmt(f); #define SFREE(X) fsl_free(X); X = NULL if(closeDatabases){ fsl_cx_close_dbs(f); /* Reminder: f->dbMem is NOT closed here: it's an internal detail, @@ -12935,36 +12715,33 @@ but then we introduce a potenital error case (OOM) where we currently have none (thus the void return). 2021-11-09: it turns out we've had an error case all along here: if any cached statements are opened for one of the dbs, - that can prohibit its detachment. + that can prohibit its detachement. */ SFREE(f->ckout.dir); f->ckout.dirLen = 0; /* assert(NULL==f->dbMain); */ } SFREE(f->repo.user); - fsl__cx_ckout_clear(f); + SFREE(f->ckout.uuid); SFREE(f->cache.projectCode); - SFREE(f->ticket.titleColumn); - SFREE(f->ticket.statusColumn); #undef SFREE fsl_error_clear(&f->error); f->interrupted = 0; - fsl__card_J_list_free(&f->ticket.customFields, true); - fsl_buffer_clear(&f->cache.fileContent); - fsl_buffer_clear(&f->cache.deltaContent); + fsl__card_J_list_free(&f->ticket.customFields, 1); + fsl_buffer_clear(&f->fileContent); for(int i = 0; i < FSL_CX_NSCRATCH; ++i){ fsl_buffer_clear(&f->scratchpads.buf[i]); f->scratchpads.used[i] = false; } - fsl__cx_clear_repo_caches(f); fsl__bccache_clear(&f->cache.blobContent); - fsl__cx_clear_mf_seen(f, true); + fsl__cx_mcache_clear(f); fsl_id_bag_clear(&f->cache.leafCheck); fsl_id_bag_clear(&f->cache.toVerify); + fsl__cx_clear_mf_seen(f, true); assert(NULL==f->cache.mfSeen.list); if(f->xlinkers.list){ fsl_free(f->xlinkers.list); f->xlinkers = fsl_xlinker_list_empty; } @@ -12982,20 +12759,21 @@ if(freeMemory) fsl_id_bag_clear(&f->cache.mfSeen); else fsl_id_bag_reset(&f->cache.mfSeen); } void fsl_cx_finalize( fsl_cx * const f ){ - void const * const allocStamp = f ? f->allocStamp : NULL; + void const * allocStamp = f ? f->allocStamp : NULL; if(!f) return; + if(f->clientState.finalize.f){ f->clientState.finalize.f( f->clientState.finalize.state, f->clientState.state ); } f->clientState = fsl_state_empty; f->output = fsl_outputer_empty; - fsl_temp_dirs_free(f->cache.tempDirs); fsl__cx_reset(f, true); + fsl_db_close(&f->dbMem); *f = fsl_cx_empty; if(&fsl_cx_empty == allocStamp){ fsl_free(f); }else{ f->allocStamp = allocStamp; @@ -13018,10 +12796,11 @@ } void fsl_cx_err_reset(fsl_cx * const f){ //f->interrupted = 0; // No! ONLY modify this via fsl_cx_interrupt() fsl_error_reset(&f->error); + fsl_db_err_reset(&f->dbMem); fsl_db_err_reset(&f->repo.db); fsl_db_err_reset(&f->config.db); fsl_db_err_reset(&f->ckout.db); } @@ -13118,15 +12897,19 @@ } return rc; } fsl_db * fsl_cx_db_config( fsl_cx * const f ){ - return f->config.db.dbh ? &f->config.db : NULL; + if(!f) return NULL; + else if(f->dbMain && (FSL_DBROLE_CONFIG & f->dbMain->role)) return f->dbMain; + else if(f->config.db.dbh) return &f->config.db; + else return NULL; } fsl_db * fsl_cx_db_repo( fsl_cx * const f ){ - if(f->dbMain && (FSL_DBROLE_REPO & f->dbMain->role)) return f->dbMain; + if(!f) return NULL; + else if(f->dbMain && (FSL_DBROLE_REPO & f->dbMain->role)) return f->dbMain; else if(f->repo.db.dbh) return &f->repo.db; else return NULL; } fsl_db * fsl_needs_repo(fsl_cx * const f){ @@ -13146,108 +12929,75 @@ } return db; } fsl_db * fsl_cx_db_ckout( fsl_cx * const f ){ - if(f->dbMain && (FSL_DBROLE_CKOUT & f->dbMain->role)) return f->dbMain; + if(!f) return NULL; + else if(f->dbMain && (FSL_DBROLE_CKOUT & f->dbMain->role)) return f->dbMain; else if(f->ckout.db.dbh) return &f->ckout.db; else return NULL; } fsl_db * fsl_cx_db( fsl_cx * const f ){ - return f->dbMain; + return f ? f->dbMain : NULL; } +/** @internal -fsl_db * fsl__cx_db_for_role(fsl_cx * const f, fsl_dbrole_e r){ + Returns one of f->db{Config,Repo,Ckout,Mem} + or NULL. + + ACHTUNG and REMINDER TO SELF: the current (2021-03) design means + that none of these handles except for FSL_DBROLE_MAIN actually has + an sqlite3 db handle assigned to it. This returns a handle to the + "level of abstraction" we need to keep track of each db's name and + db-specific other state. + + e.g. passing a role of FSL_DBROLE_CKOUT this does NOT return + the same thing as fsl_cx_db_ckout(). +*/ +fsl_db * fsl_cx_db_for_role(fsl_cx * const f, fsl_dbrole_e r){ switch(r){ case FSL_DBROLE_CONFIG: return &f->config.db; case FSL_DBROLE_REPO: return &f->repo.db; case FSL_DBROLE_CKOUT: return &f->ckout.db; case FSL_DBROLE_MAIN: - return f->dbMain; + return &f->dbMem; case FSL_DBROLE_NONE: default: return NULL; } } /** - Returns the "counterpart" role for the given db role. -*/ -static fsl_dbrole_e fsl__dbrole_counterpart(fsl_dbrole_e r){ - switch(r){ - case FSL_DBROLE_REPO: return FSL_DBROLE_CKOUT; - case FSL_DBROLE_CKOUT: return FSL_DBROLE_REPO; - default: - fsl__fatal(FSL_RC_MISUSE, - "Serious internal API misuse uncovered by %s().", - __func__); - return FSL_DBROLE_NONE; - } -} - -/** - Detaches/closes the given db role from f->dbMain and removes the - role from f->dbMain->role. If r reflects the current primary db - and a secondary db is attached, the secondary gets detached. If r - corresponds to the secondary db, only that db is detached. If - f->dbMain is the given role then f->dbMain is set to NULL. -*/ -static int fsl__cx_detach_role(fsl_cx * const f, fsl_dbrole_e r){ - assert(FSL_DBROLE_CONFIG!=r && "Config db now has its own handle."); - assert(FSL_DBROLE_REPO==r || FSL_DBROLE_CKOUT==r); - if(NULL==f->dbMain){ - assert(!"Internal API misuse: don't try to detach when dbMain is NULL."); - return fsl_cx_err_set(f, FSL_RC_MISUSE, - "Cannot close/detach db: none opened."); - }else if(!(r & f->dbMain->role)){ + Detaches the given db role from f->dbMain and removes the role + from f->dbMain->role. +*/ +static int fsl_cx_detach_role(fsl_cx * const f, fsl_dbrole_e r){ + if(NULL==f->dbMain) return FSL_RC_MISUSE; + else if(!(r & f->dbMain->role)){ assert(!"Misuse: cannot detach unattached role."); - return fsl_cx_err_set(f, FSL_DBROLE_CKOUT==r - ? FSL_RC_NOT_A_CKOUT - : FSL_RC_NOT_A_REPO, - "Cannot close/detach unattached role: %s", - fsl_db_role_name(r)); - }else{ - fsl_db * const db = fsl__cx_db_for_role(f,r); - int rc = 0; - switch(r){ - case FSL_DBROLE_REPO: - fsl__cx_clear_repo_caches(f); - break; - case FSL_DBROLE_CKOUT: - fsl__cx_ckout_clear(f); - break; - default: - fsl__fatal(FSL_RC_ERROR, "Cannot happen. Really."); - } - fsl__cx_finalize_cached_stmt(f); - fsl__db_cached_clear_role(f->dbMain, r) + return FSL_RC_NOT_FOUND; + } + else{ + fsl_db * const db = fsl_cx_db_for_role(f,r); + int rc; + assert(db && "Internal API misuse."); + assert(f->dbMain != db); + rc = fsl__db_cached_clear_role(f->dbMain, r) /* Make sure that we destroy any cached statements which are - known to be tied to this db role. */; - if(db->dbh){ - /* This is our MAIN db. CLOSE it. If we still have a - secondary/counterpart db open, we'll detach it first. */ - fsl_dbrole_e const counterpart = fsl__dbrole_counterpart(r); - assert(f->dbMain == db); - if(db->role & counterpart){ - /* When closing the main db, detach the counterpart db first - (if it's attached). We'll ignore any result code here, for - sanity's sake. */ - assert(fsl__cx_db_for_role(f,counterpart)->filename && - "Inconsistent internal db handle state."); - fsl__cx_detach_role(f, counterpart); - } - fsl_db_close(db); - f->dbMain = NULL; - }else{ - /* This is our secondary db. DETACH it. */ - assert(f->dbMain != db); - rc = fsl_db_detach( f->dbMain, fsl_db_role_name(r) ); - //MARKER(("rc=%s %s %s\n", fsl_rc_cstr(rc), fsl_db_role_name(r), + known to be tied to this db role. This is primarily a kludge + for the global config db to avoid that closing it fails due + to a lock held by those statements. This is a special case + for the global db (as opposed to the repo/ckout dbs) because + exactly when that db is opened and close is not as tightly + controlled/funneled as the other dbs. */; + if(0==rc){ + rc = fsl_db_detach( f->dbMain, fsl_db_role_label(r) ); + //MARKER(("rc=%s %s %s\n", fsl_rc_cstr(rc), fsl_db_role_label(r), // fsl_buffer_cstr(&f->dbMain->error.msg))); if(rc){ fsl_cx_uplift_db_error(f, f->dbMain); }else{ f->dbMain->role &= ~r; @@ -13256,145 +13006,154 @@ } return rc; } } -int fsl__cx_attach_role(fsl_cx * const f, const char *zDbName, - fsl_dbrole_e r, bool createIfNotExists){ - char const * dbName = fsl_db_role_name(r); - fsl_db * const db = fsl__cx_db_for_role(f, r); + +/** @internal + + Attaches the given db file to f with the given role. This function "should" + be static but we need it in fsl_repo.c when creating a new repository. +*/ +int fsl_cx_attach_role(fsl_cx * const f, const char *zDbName, + fsl_dbrole_e r){ + char const * label = fsl_db_role_label(r); + fsl_db * const db = fsl_cx_db_for_role(f, r); + char ** nameDest = NULL; int rc; + if(!f->dbMain){ + fsl__fatal(FSL_RC_MISUSE,"Internal API misuse: f->dbMain has " + "not been set, so cannot attach role."); + return FSL_RC_MISUSE; + } + else if(r & f->dbMain->role){ + assert(!"Misuse: role is already attached."); + return fsl_cx_err_set(f, FSL_RC_MISUSE, + "Db role %s is already attached.", + label); + } +#if 0 + MARKER(("r=%s db=%p, ckout.db=%p\n", label, + (void*)db, (void*)&f->ckout.db)); + MARKER(("r=%s db=%p, repo.db=%p\n", label, + (void*)db, (void*)&f->repo.db)); + MARKER(("r=%s db=%p, dbMain=%p\n", label, + (void*)db, (void*)f->dbMain)); +#endif assert(db); - assert(!db->dbh && "Internal API misuse: don't call this when db is connected."); - assert(!db->filename && "Don't re-attach!"); - assert(!db->name && "Don't re-attach!"); - assert(dbName); - assert(f->dbMain != db && "Don't re-attach the main db!"); + assert(label); + assert(f->dbMain != db); + assert(!db->filename); + assert(!db->name); + nameDest = &db->filename; switch(r){ + case FSL_DBROLE_CONFIG: case FSL_DBROLE_REPO: case FSL_DBROLE_CKOUT: break; - case FSL_DBROLE_CONFIG: case FSL_DBROLE_MAIN: case FSL_DBROLE_NONE: default: assert(!"cannot happen/not legal"); - fsl__fatal(FSL_RC_RANGE, "Serious internal API misuse via %s().", - __func__); return FSL_RC_RANGE; } - db->f = f; - db->name = fsl_strdup(dbName); + *nameDest = fsl_strdup(zDbName); + db->name = *nameDest ? fsl_strdup(label) : NULL; if(!db->name){ rc = FSL_RC_OOM; - goto end; - } - if(!f->dbMain){ - // This is our first/main db. OPEN it. - rc = fsl_db_open( db, zDbName, createIfNotExists - ? FSL_OPEN_F_RWC - : FSL_OPEN_F_RW ); - if(rc){ - rc = fsl_cx_uplift_db_error2(f, db, rc); - fsl_db_close(db); - goto end; - } - int const sqrc = sqlite3_db_config(db->dbh, - SQLITE_DBCONFIG_MAINDBNAME, - dbName); - if(sqrc){ - rc = fsl__db_errcode(&f->config.db, sqrc); - fsl_cx_uplift_db_error2(f, db, rc); - fsl_db_close(db); - }else{ - rc = fsl__cx_init_db(f, db); - db->role |= r; - assert(db == f->dbMain)/*even on failure*/; - /* Should we fsl__cx_detach_role() here? */ - } - }else{ - // This is our secondary db. ATTACH it. - assert(db != f->dbMain); - db->filename = fsl_strdup(zDbName); - if(!db->filename){ - rc = FSL_RC_OOM; - }else{ - bool createdIt = false; - if(createIfNotExists - && 0!=fsl_file_access( zDbName, F_OK )){ - FILE * const cf = fsl_fopen(zDbName, "w"); - if(!cf){ - rc = fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_IO), - "Error creating new db file [%s].", - zDbName); - goto end; - } - fsl_fclose(cf); - createdIt = true; - } - rc = fsl_db_attach(f->dbMain, zDbName, dbName); - if(rc){ - fsl_cx_uplift_db_error(f, f->dbMain); - fsl_db_close(db)/*cleans up strings*/; - db->f = NULL; - if(createdIt) fsl_file_unlink(zDbName); - }else{ - /*MARKER(("Attached %p role %d %s %s\n", - (void const *)db, r, db->name, db->filename));*/ - f->dbMain->role |= r; - } - } - } - end: + /* Design note: we do the strdup() before the ATTACH because if + the attach succeeds and strdup fails, detaching the db will + almost certainly fail because it must allocate for its prepared + statement and other internals. We would end up having to leave + the db attached and returning a failure, which could lead to a + memory leak (or worse) downstream. + */ + }else{ + /*MARKER(("Attached %p role %d %s %s\n", + (void const *)db, r, db->name, db->filename));*/ + rc = fsl_db_attach(f->dbMain, zDbName, label); + if(rc){ + fsl_cx_uplift_db_error(f, f->dbMain); + }else{ + //MARKER(("Attached db %p %s from %s\n", + // (void*)db, label, db->filename)); + f->dbMain->role |= r; + } + } return rc; } int fsl_config_close( fsl_cx * const f ){ - if(fsl_db_transaction_level(&f->config.db)){ - return fsl_cx_err_set(f, FSL_RC_MISUSE, - "Cannot close config db with an " - "opened transaction."); - } - fsl_db_close(&f->config.db); - return 0; -} - -int fsl_close_scm_dbs(fsl_cx * const f){ - if(fsl_cx_transaction_level(f)){ - /* TODO???: force a full rollback and close it */ - //if(f->repo.db.dbh) fsl_db_rollback_force(&f->repo.db); - //if(f->ckout.db.dbh) fsl_db_rollback_force(&f->ckout.db); - return fsl_cx_err_set(f, FSL_RC_MISUSE, - "Cannot close repo or checkout with an " - "opened transaction."); - }else if(!f->dbMain){ - // Make sure that all string resources are cleaned up... - fsl_db_close(&f->repo.db); - fsl_db_close(&f->ckout.db); - return 0; - }else{ - fsl_db * const dbR = &f->repo.db; - return fsl__cx_detach_role(f, f->dbMain == dbR - ? FSL_DBROLE_REPO - : FSL_DBROLE_CKOUT) - /* Will also close the counterpart db. */; - } + int rc = 0; + fsl_db * const db = &f->config.db; + if(f->dbMain && (FSL_DBROLE_CONFIG & f->dbMain->role)){ + /* Config db is ATTACHed. */ + rc = fsl_cx_detach_role(f, FSL_DBROLE_CONFIG); + }else{ + fsl_db_close(db); + } + return rc; } int fsl_repo_close( fsl_cx * const f ){ - return fsl_close_scm_dbs(f); + if(fsl_cx_transaction_level(f)){ + return fsl_cx_err_set(f, FSL_RC_MISUSE, + "Cannot close repo with an opened transaction."); + }else{ + int rc = 0; + fsl_db * const db = &f->repo.db; + if(f->dbMain && (FSL_DBROLE_REPO & f->dbMain->role)){ + /* Repo db is ATTACHed. */ + if(FSL_DBROLE_CKOUT & f->dbMain->role){ + rc = fsl_cx_err_set(f, FSL_RC_MISUSE, + "Cannot close repo while checkout is " + "opened."); + }else{ + assert(f->dbMain!=db); + rc = fsl_cx_detach_role(f, FSL_DBROLE_REPO); + } + }else{ + fsl_db_close(db); + } + assert(!db->dbh); + return rc; + } } int fsl_ckout_close( fsl_cx * const f ){ - return fsl_close_scm_dbs(f); + if(fsl_cx_transaction_level(f)){ + return fsl_cx_err_set(f, FSL_RC_MISUSE, + "Cannot close checkout with opened transaction."); + }else{ + int rc = 0; + fsl_db * const db = &f->ckout.db; + if(f->dbMain && (FSL_DBROLE_CKOUT & f->dbMain->role)){ + /* Checkout db is ATTACHed. */ + rc = fsl_cx_detach_role(f, FSL_DBROLE_CKOUT); + fsl_repo_close(f) + /* Because the repo is implicitly opened, we "should" + implicitly close it. This is debatable but "probably almost + always" desired. i can't currently envisage a reasonable + use-case which requires closing the checkout but keeping + the repo opened. The repo can always be re-opened by + itself. */; + }else{ + fsl_db_close(db); + } + fsl_free(f->ckout.uuid); + f->ckout.uuid = NULL; + f->ckout.rid = 0; + assert(!db->dbh); + return rc; + } } /** If zDbName is a valid checkout database file, open it and return 0. If it is not a valid local database file, return a non-0 code. */ -static int fsl__cx_ckout_open_db(fsl_cx * f, const char *zDbName){ +static int fsl_cx_ckout_open_db(fsl_cx * f, const char *zDbName){ /* char *zVFileDef; */ int rc; fsl_int_t const lsize = fsl_file_size(zDbName); if( -1 == lsize ){ return FSL_RC_NOT_FOUND /* might be FSL_RC_ACCESS? */; @@ -13403,11 +13162,11 @@ return fsl_cx_err_set(f, FSL_RC_RANGE, "File's size is not correct for a " "checkout db: %s", zDbName); } - rc = fsl__cx_attach_role(f, zDbName, FSL_DBROLE_CKOUT, false); + rc = fsl_cx_attach_role(f, zDbName, FSL_DBROLE_CKOUT); return rc; } int fsl_cx_execv( fsl_cx * const f, char const * sql, va_list args ){ @@ -13490,11 +13249,11 @@ static int fsl_config_file_reset(fsl_cx * const f, char const * dbName){ fsl_db DB = fsl_db_empty; fsl_db * db = &DB; int rc = 0; bool isAttached = false; - const char * zPrefix = fsl_db_role_name(FSL_DBROLE_CONFIG); + const char * zPrefix = fsl_db_role_label(FSL_DBROLE_CONFIG); if(-1 != fsl_file_size(dbName)){ rc = fsl_file_unlink(dbName); if(rc){ return fsl_cx_err_set(f, rc, "Error %s while removing old config file (%s)", @@ -13503,11 +13262,11 @@ } /** Hoop-jumping: because the schema file has a cfg. prefix for the table(s), and we cannot assign an arbitrary name to an open()'d db, we first open the db (making the the "main" db), then - ATTACH it to itself to provide the fsl_db_role_name() alias. + ATTACH it to itself to provide the fsl_db_role_label() alias. */ rc = fsl_db_open(db, dbName, FSL_OPEN_F_RWC); if(rc) goto end; rc = fsl_db_attach(db, dbName, zPrefix); if(rc) goto end; @@ -13587,12 +13346,11 @@ int rc = 0; const char * zDbName = 0; char * zPrefName = 0; if(fsl_cx_db_config(f)){ if(NULL==openDbName || 0==*openDbName) return 0/*nothing to do*/; - fsl_config_close(f); - assert(!f->config.db.dbh); + else fsl_config_close(f); } if(openDbName && *openDbName){ zDbName = openDbName; }else{ rc = fsl_config_global_preferred_name(&zPrefName); @@ -13617,24 +13375,11 @@ "must be writeable.", zDbName); goto end; } #endif assert(NULL==fsl_cx_db_config(f)); - rc = fsl_db_open(&f->config.db, zDbName, - FSL_OPEN_F_RW | (f->cxConfig.traceSql - ? FSL_OPEN_F_TRACE_SQL - : 0)); - if(0==rc){ - int const sqrc = sqlite3_db_config(f->config.db.dbh, - SQLITE_DBCONFIG_MAINDBNAME, - fsl_db_role_name(FSL_DBROLE_CONFIG)); - if(sqrc) rc = fsl__db_errcode(&f->config.db, sqrc); - } - if(rc){ - rc = fsl_cx_uplift_db_error2(f, &f->config.db, rc); - fsl_db_close(&f->config.db); - } + rc = fsl_cx_attach_role(f, zDbName, FSL_DBROLE_CONFIG); end: fsl_free(zPrefName); return rc; } @@ -13724,52 +13469,10 @@ default: p = FSL_HPOLICY_AUTO; break; } f->cxConfig.hashPolicy = p; } -#if 0 -/** - Return true if the schema is out-of-date. db must be an opened - repo db. - */ -static bool fsl__db_repo_schema_is_outofdate(fsl_db *db){ - return fsl_db_exists(db, "SELECT 1 FROM config " - "WHERE name='aux-schema' " - "AND value<>'%s'", - FSL_AUX_SCHEMA); -} - -/* - Returns 0 if db appears to have a current repository schema, 1 if - it appears to have an out of date schema, and -1 if it appears to - not be a repository. -*/ -int fsl__db_repo_verify_schema(fsl_db * const db){ - if(fsl__db_repo_schema_is_outofdate(db)) return 1; - else return fsl_db_exists(db, - "SELECT 1 FROM config " - "WHERE name='project-code'") - ? 0 : -1; -} -int fsl_repo_schema_validate(fsl_cx * const f, fsl_db * const db){ - int rc = 0; - int const check = fsl__db_repo_verify_schema(db); - if(0 != check){ - rc = (check<0) - ? fsl_cx_err_set(f, FSL_RC_NOT_A_REPO, - "DB file [%s] does not appear to be " - "a repository.", db->filename) - : fsl_cx_err_set(f, FSL_RC_REPO_NEEDS_REBUILD, - "DB file [%s] appears to be a fossil " - "repsitory, but is out-of-date and needs " - "a rebuild.", - db->filename); - } - return rc; -} -#endif - int fsl_repo_open( fsl_cx * const f, char const * repoDbFile /* , bool readOnlyCurrentlyIgnored */ ){ if(fsl_cx_db_repo(f)){ return fsl_cx_err_set(f, FSL_RC_ACCESS, "Context already has an opened repository."); @@ -13778,19 +13481,21 @@ if(0!=fsl_file_access( repoDbFile, F_OK )){ rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "Repository db [%s] not found or cannot be read.", repoDbFile); }else{ - rc = fsl__cx_attach_role(f, repoDbFile, FSL_DBROLE_REPO, false); + rc = fsl_cx_attach_role(f, repoDbFile, FSL_DBROLE_REPO); if(!rc && !(FSL_CX_F_IS_OPENING_CKOUT & f->flags)){ rc = fsl_cx_after_open(f); } if(!rc){ fsl_db * const db = fsl_cx_db_repo(f); fsl_cx_username_from_repo(f); - fsl_cx_allows_symlinks(f, true); - fsl_cx_is_case_sensitive(f, true); + f->cache.allowSymlinks = + fsl_config_get_bool(f, FSL_CONFDB_REPO, + false, + "allow-symlinks"); f->cache.seenDeltaManifest = fsl_config_get_int32(f, FSL_CONFDB_REPO, -1, "seen-delta-manifest"); fsl_cx_fetch_hash_policy(f); if(f->cxConfig.hashPolicy==FSL_HPOLICY_AUTO){ @@ -13859,24 +13564,20 @@ "WHERE objid=%" FSL_ID_T_PFMT, f->ckout.rid) : 0.0; } -void fsl__cx_ckout_clear( fsl_cx * const f ){ - fsl_free(f->ckout.uuid); - f->ckout.rid = -1; - f->ckout.uuid = NULL; - f->ckout.mtime = 0.0; -} - int fsl__ckout_version_fetch( fsl_cx * const f ){ fsl_id_t rid = 0; int rc = 0; fsl_db * dbC = fsl_cx_db_ckout(f); fsl_db * dbR = dbC ? fsl_needs_repo(f) : NULL; assert(!dbC || (dbC && dbR)); - fsl__cx_ckout_clear(f); + fsl_free(f->ckout.uuid); + f->ckout.rid = -1; + f->ckout.uuid = NULL; + f->ckout.mtime = 0.0; if(!dbC){ return 0; } fsl_cx_err_reset(f); rid = fsl_config_get_id(f, FSL_CONFDB_CKOUT, -1, "checkout"); @@ -13986,10 +13687,11 @@ fsl_int_t dLen = 0, i; enum { DbCount = 2 }; const char aDbName[DbCount][10] = { "_FOSSIL_", ".fslckout" }; fsl_buffer Buf = fsl_buffer_empty; fsl_buffer * buf = &Buf; + buf->used = 0; if(dirName){ dLen = fsl_strlen(dirName); if(0==dLen) return FSL_RC_RANGE; rc = fsl_buffer_reserve( buf, (fsl_size_t)(dLen + 10) ); if(!rc) rc = fsl_buffer_append( buf, dirName, dLen ); @@ -14072,11 +13774,11 @@ } fsl_buffer_clear(buf); return FSL_RC_NOT_FOUND; } -int fsl_cx_getcwd(fsl_cx * const f, fsl_buffer * const pOut){ +int fsl_cx_getcwd(fsl_cx * f, fsl_buffer * pOut){ char cwd[FILENAME_MAX] = {0}; fsl_size_t cwdLen = 0; int rc = fsl_getcwd(cwd, (fsl_size_t)sizeof(cwd), &cwdLen); if(rc){ return fsl_cx_err_set(f, rc, @@ -14086,40 +13788,38 @@ return rc ? fsl_cx_err_set(f, rc/*must be an OOM*/, NULL) : 0; } -int fsl_ckout_open_dir( fsl_cx * const f, char const * dirName, +int fsl_ckout_open_dir( fsl_cx * f, char const * dirName, bool checkParentDirs ){ int rc; - fsl_buffer * const buf = fsl__cx_scratchpad(f); - fsl_buffer * const bufD = fsl__cx_scratchpad(f); + fsl_buffer Buf = fsl_buffer_empty; + fsl_buffer * buf = &Buf; char const * zName; if(fsl_cx_db_ckout(f)){ - rc = fsl_cx_err_set( f, FSL_RC_ACCESS, - "A checkout is already opened. " - "Close it before opening another."); - goto end; - }else if(!dirName){ - dirName = "."; - } - rc = fsl_file_canonical_name( dirName, bufD, false ); - if(rc) goto end; - dirName = fsl_buffer_cstr(bufD); + return fsl_cx_err_set( f, FSL_RC_ACCESS, + "A checkout is already opened. " + "Close it before opening another."); + } rc = fsl_ckout_db_search(dirName, checkParentDirs, buf); if(rc){ if(FSL_RC_NOT_FOUND==rc){ rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "Could not find checkout under [%s].", dirName ? dirName : "."); } - goto end; + fsl_buffer_clear(buf); + return rc; } assert(buf->used>1 /* "/" */); zName = fsl_buffer_cstr(buf); - rc = fsl__cx_ckout_open_db(f, zName); - if(0==rc){ + rc = fsl_cx_ckout_open_db(f, zName); + if(rc){ + fsl_buffer_clear(buf); + return rc; + }else{ /* Checkout db is now opened. Fiddle some internal bits... */ unsigned char * end = buf->mem+buf->used-1; /* Find dir part */ @@ -14140,39 +13840,34 @@ if(!rc) rc = fsl_cx_after_open(f); if(rc){ /* Is this sane? Is not doing it sane? */ fsl_ckout_close(f); } + return rc; } - end: - fsl__cx_scratchpad_yield(f, buf); - fsl__cx_scratchpad_yield(f, bufD); - return rc; } char const * fsl_cx_db_file_for_role(fsl_cx const * f, fsl_dbrole_e r, fsl_size_t * len){ - fsl_db const * db = fsl__cx_db_for_role((fsl_cx*)f, r); + fsl_db const * db = fsl_cx_db_for_role((fsl_cx*)f, r); char const * rc = db ? db->filename : NULL; if(len) *len = fsl_strlen(rc); return rc; } char const * fsl_cx_db_name_for_role(fsl_cx const * f, fsl_dbrole_e r, fsl_size_t * len){ if(FSL_DBROLE_MAIN == r){ - if(f->dbMain){ - if(len) *len=4; - return "main"; - }else{ - return NULL; - } - }else{ - fsl_db const * db = fsl__cx_db_for_role((fsl_cx*)f, r); + /* special case to be removed when f->dbMem bits are + finished. */ + if(len) *len=4; + return "main"; + }else{ + fsl_db const * db = fsl_cx_db_for_role((fsl_cx*)f, r); char const * rc = db ? db->name : NULL; if(len) *len = rc ? fsl_strlen(rc) : 0; return rc; } } @@ -14378,68 +14073,68 @@ int fsl_cx_stat(fsl_cx * const f, bool relativeToCwd, char const * zName, fsl_fstat * const tgt){ return fsl_cx_stat2(f, relativeToCwd, zName, tgt, NULL, false); } -bool fsl_cx_allows_symlinks(fsl_cx * const f, bool forceRecheck){ - if(forceRecheck || f->cache.allowSymlinks<0){ - f->cache.allowSymlinks = fsl_config_get_bool(f, FSL_CONFDB_REPO, - false, "allow-symlinks"); - } - return f->cache.allowSymlinks>0; -} - -void fsl_cx_case_sensitive_set(fsl_cx * const f, bool caseSensitive){ - f->cache.caseInsensitive = caseSensitive ? 0 : 1; -} - -bool fsl_cx_is_case_sensitive(fsl_cx * const f, bool forceRecheck){ - if(forceRecheck || f->cache.caseInsensitive<0){ - f->cache.caseInsensitive = - fsl_config_get_bool(f, FSL_CONFDB_REPO, - true, "case-sensitive") ? 0 : 1; - } - return f->cache.caseInsensitive <= 0; + +void fsl_cx_case_sensitive_set(fsl_cx * f, bool caseSensitive){ + f->cache.caseInsensitive = caseSensitive; +} + +bool fsl_cx_is_case_sensitive(fsl_cx const * f){ + return !f->cache.caseInsensitive; } char const * fsl_cx_filename_collation(fsl_cx const * f){ - return f->cache.caseInsensitive>0 ? "COLLATE nocase" : ""; + return f->cache.caseInsensitive ? "COLLATE nocase" : ""; } -fsl_buffer * fsl__cx_content_buffer(fsl_cx * const f){ - if(f->cache.fileContent.used){ - fsl__fatal(FSL_RC_MISUSE, - "Called %s() while the content buffer has bytes in use."); - } - return &f->cache.fileContent; -} void fsl__cx_content_buffer_yield(fsl_cx * const f){ - enum { MaxSize = 1024 * 1024 * 10 }; + enum { MaxSize = 1024 * 1024 * 2 }; assert(f); - if(f->cache.fileContent.capacity>MaxSize){ - fsl_buffer_resize(&f->cache.fileContent, MaxSize); - assert(f->cache.fileContent.capacity<=MaxSize+1); + if(f->fileContent.capacity>MaxSize){ + fsl_buffer_resize(&f->fileContent, MaxSize); + assert(f->fileContent.capacity<=MaxSize+1); } - fsl_buffer_reuse(&f->cache.fileContent); + fsl_buffer_reuse(&f->fileContent); } fsl_error const * fsl_cx_err_get_e(fsl_cx const * f){ - return &f->error; + return f ? &f->error : NULL; } int fsl_cx_close_dbs( fsl_cx * const f ){ - if(fsl_cx_transaction_level(f) - || (f->config.db.dbh && fsl_db_transaction_level(&f->config.db))){ - /* Is this really necessary? Should we instead - force rollback(s) and close the dbs? */ + if(fsl_cx_transaction_level(f)){ + /* Is this really necessary? */ return fsl_cx_err_set(f, FSL_RC_MISUSE, "Cannot close the databases when a " "transaction is pending."); } - fsl_config_close(f); - return fsl_close_scm_dbs(f); + if(NULL==f->dbMain) return 0; + int rc = 0, rc1; + rc = fsl__db_cached_clear_role(f->dbMain, 0); + if(rc) return fsl_cx_uplift_db_error(f, f->dbMain); + rc1 = fsl_ckout_close(f); + if(rc1) rc = rc1; + rc1 = fsl_repo_close(f); + if(rc1) rc = rc1; + rc1 = fsl_config_close(f); + if(rc1) rc = rc1; + /* Forcibly reset the role and db strings for this case, even + if closing ostensibly fails. */ + f->dbMain->role = FSL_DBROLE_MAIN; + fsl__db_clear_strings(&f->repo.db, true); + fsl__db_clear_strings(&f->ckout.db, true); + fsl__db_clear_strings(&f->config.db, true); + assert(!f->repo.db.dbh); + assert(!f->ckout.db.dbh); + assert(!f->config.db.dbh); + assert(!f->repo.db.filename); + assert(!f->ckout.db.filename); + assert(!f->config.db.filename); + return rc; } char const * fsl_cx_glob_matches( fsl_cx * const f, int gtype, char const * str ){ int i, count = 0; @@ -14493,11 +14188,11 @@ int fsl_cx_hash_filename( fsl_cx * f, bool useAlternate, const char * zFilename, fsl_buffer * pOut){ /* FIXME: reimplement this to stream the content in bite-sized chunks. That requires duplicating most of fsl_buffer_fill_from() and fsl_cx_hash_buffer(). */ - fsl_buffer * const content = &f->cache.fileContent; + fsl_buffer * content = &f->fileContent; int rc; assert(!content->used && "Internal recursive misuse of fsl_cx::fileContent"); fsl_buffer_reuse(content); rc = fsl_buffer_fill_from_filename(content, zFilename); if(!rc){ @@ -14601,11 +14296,11 @@ "seen-delta-manifest", 1); } return rc; } -int fsl_reserved_fn_check(fsl_cx * const f, const char *zPath, +int fsl_reserved_fn_check(fsl_cx *f, const char *zPath, fsl_int_t nPath, bool relativeToCwd){ static const int errRc = FSL_RC_RANGE; int rc = 0; char const * z1 = 0; if(nPath<0) nPath = (fsl_int_t)fsl_strlen(zPath); @@ -14620,12 +14315,12 @@ return fsl_cx_err_set(f, errRc, "Filename is a Windows reserved name: %.*s", (int)nPath, zPath); } if((z1 = fsl_cx_db_file_for_role(f, FSL_DBROLE_REPO, NULL))){ - fsl_buffer * const c1 = fsl__cx_scratchpad(f); - fsl_buffer * const c2 = fsl__cx_scratchpad(f); + fsl_buffer * c1 = fsl__cx_scratchpad(f); + fsl_buffer * c2 = fsl__cx_scratchpad(f); rc = fsl_file_canonical_name2(relativeToCwd ? NULL : f->ckout.dir/*NULL is okay*/, z1, c1, false); if(!rc) rc = fsl_file_canonical_name2(relativeToCwd ? NULL : f->ckout.dir, zPath, c2, false); //MARKER(("\nzPath=%s\nc1=%s\nc2=%s\n", zPath, @@ -14638,13 +14333,11 @@ fsl__cx_scratchpad_yield(f, c1); fsl__cx_scratchpad_yield(f, c2); if(rc) return rc; } assert(!rc); - while(true){ - /* Check the name against the repo's "manifest" setting and reject - any filenames which that setting implies. */ + while(f->ckout.dir || relativeToCwd){ int manifestSetting = 0; fsl_ckout_manifest_setting(f, &manifestSetting); if(!manifestSetting) break; typedef struct { short flag; @@ -14654,11 +14347,11 @@ {FSL_MANIFEST_MAIN, "manifest"}, {FSL_MANIFEST_UUID, "manifest.uuid"}, {FSL_MANIFEST_TAGS, "manifest.tags"}, {0,0} }; - fsl_buffer * const c1 = fsl__cx_scratchpad(f); + fsl_buffer * c1 = fsl__cx_scratchpad(f); if(f->ckout.dir){ rc = fsl_ckout_filename_check(f, relativeToCwd, zPath, c1); }else{ rc = fsl_file_canonical_name2("", zPath, c1, false); } @@ -14732,11 +14425,11 @@ } /** @internal - Don't use this. Use fsl__ckout_rm_empty_dirs() instead. + Don't use this. Use fsl_cx_rm_empty_dirs() instead. Attempts to remove empty directories from under a checkout, starting with tgtDir and working upwards until it either cannot remove one or it reaches the top of the checkout dir. @@ -14755,21 +14448,20 @@ have coRoot as its initial prefix. There are any number of valid reasons removal of a directory might fail, and this routine stops at the first one which does. */ -static unsigned fsl__rm_empty_dirs(char const * const coRoot, - fsl_int_t rootLen, - fsl_buffer const * const tgtDir){ - if(rootLen<0) rootLen = (fsl_int_t)fsl_strlen(coRoot); +static unsigned fsl_rm_empty_dirs(char const *coRoot, fsl_int_t rootLen, + fsl_buffer * tgtDir){ + if(rootLen<0) rootLen = fsl_strlen(coRoot); char const * zAbs = fsl_buffer_cstr(tgtDir); char const * zCoDirPart = zAbs + rootLen; char * zEnd = fsl_buffer_str(tgtDir) + tgtDir->used - 1; unsigned rc = 0; assert(coRoot); if(0!=memcmp(coRoot, zAbs, (size_t)rootLen)){ - assert(!"Misuse of fsl__rm_empty_dirs()"); + assert(!"Misuse of fsl_rm_empty_dirs()"); return 0; } if(fsl_rmdir(zAbs)) return rc; ++rc; /** Now walk up each dir in the path and try to remove each, @@ -14785,34 +14477,38 @@ } } return rc; } -unsigned int fsl__ckout_rm_empty_dirs(fsl_cx * const f, - fsl_buffer const * const tgtDir){ +unsigned int fsl_ckout_rm_empty_dirs(fsl_cx * const f, fsl_buffer * const tgtDir){ int rc = f->ckout.dir ? 0 : FSL_RC_NOT_A_CKOUT; if(!rc){ - rc = fsl__rm_empty_dirs(f->ckout.dir, f->ckout.dirLen, tgtDir); + rc = fsl_rm_empty_dirs(f->ckout.dir, f->ckout.dirLen, tgtDir); } return rc; } -int fsl__ckout_rm_empty_dirs_for_file(fsl_cx * const f, char const *zAbsPath){ +int fsl_ckout_rm_empty_dirs_for_file(fsl_cx * const f, char const *zAbsPath){ if(!fsl_is_rooted_in_ckout(f, zAbsPath)){ assert(!"Internal API misuse!"); return FSL_RC_MISUSE; }else{ fsl_buffer * const p = fsl__cx_scratchpad(f); fsl_int_t const nAbs = (fsl_int_t)fsl_strlen(zAbsPath); int const rc = fsl_file_dirpart(zAbsPath, nAbs, p, false); - if(!rc) fsl__rm_empty_dirs(f->ckout.dir, f->ckout.dirLen, p); + if(!rc) fsl_rm_empty_dirs(f->ckout.dir, f->ckout.dirLen, p); fsl__cx_scratchpad_yield(f,p); return rc; } } -int fsl_ckout_fingerprint_check(fsl_cx * const f){ +bool fsl_repo_forbids_delta_manifests(fsl_cx * f){ + return fsl_config_get_bool(f, FSL_CONFDB_REPO, false, + "forbid-delta-manifests"); +} + +int fsl_ckout_fingerprint_check(fsl_cx * f){ fsl_db * const db = fsl_cx_db_ckout(f); if(!db) return 0; int rc = 0; char const * zCkout = 0; char * zRepo = 0; @@ -14900,12 +14596,12 @@ } #endif #undef MARKER #undef FSL_CX_NSCRATCH -/* end of file ./src/cx.c */ -/* start of file ./src/db.c */ +/* end of file cx.c */ +/* start of file db.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -14945,62 +14641,48 @@ if(obj) fsl_stmt_finalize( (fsl_stmt*)obj ); return 0; } #endif - -int fsl__db_errcode(fsl_db * const db, int sqliteCode){ - int rc = 0; - if(!sqliteCode) sqliteCode = sqlite3_errcode(db->dbh); - switch(sqliteCode & 0xff){ - case SQLITE_ROW: - case SQLITE_DONE: - case SQLITE_OK: rc = 0; break; - case SQLITE_NOMEM: rc = FSL_RC_OOM; break; - case SQLITE_INTERRUPT: rc = FSL_RC_INTERRUPTED; break; - case SQLITE_TOOBIG: - case SQLITE_FULL: - case SQLITE_NOLFS: - case SQLITE_RANGE: rc = FSL_RC_RANGE; break; - case SQLITE_NOTFOUND: rc = FSL_RC_NOT_FOUND; break; - case SQLITE_PERM: - case SQLITE_AUTH: - case SQLITE_LOCKED: - case SQLITE_READONLY: rc = FSL_RC_ACCESS; break; - case SQLITE_CORRUPT: rc = FSL_RC_CONSISTENCY; break; - case SQLITE_CANTOPEN: - case SQLITE_IOERR: - rc = FSL_RC_IO; break; - default: - //MARKER(("sqlite3_errcode()=0x%04x\n", rc)); - rc = FSL_RC_DB; break; - } - return rc - ? fsl_error_set(&db->error, rc, - "sqlite3 error #%d: %s", - sqliteCode, sqlite3_errmsg(db->dbh)) - : (fsl_error_reset(&db->error), 0); -} - void fsl__db_clear_strings(fsl_db * const db, bool alsoErrorState ){ fsl_free(db->filename); db->filename = NULL; fsl_free(db->name); db->name = NULL; if(alsoErrorState) fsl_error_clear(&db->error); } int fsl_db_err_get( fsl_db const * const db, char const ** msg, fsl_size_t * len ){ - return fsl_error_get(&db->error, msg, len); + return db + ? fsl_error_get(&db->error, msg, len) + : FSL_RC_MISUSE; } fsl_db * fsl_stmt_db( fsl_stmt * const stmt ){ - return stmt->db; + return stmt ? stmt->db : NULL; +} + +/** + Resets db->error state based on the given code and the current + error string from the db driver. Returns FSL_RC_DB on success, + some other non-0 value on error (most likely FSL_RC_OOM while + allocating the error string - that's the only other error case as + long as db is opened). Results are undefined if !db or db is not + opened. + */ +static int fsl_err_from_db( fsl_db * const db, int dbCode ){ + assert(db && db->dbh); + db->error.msg.used =0 ; + return fsl_error_set(&db->error, FSL_RC_DB, + "Db error #%d: %s", + dbCode, sqlite3_errmsg(db->dbh)); } char const * fsl_stmt_sql( fsl_stmt * const stmt, fsl_size_t * const len ){ - return fsl_buffer_cstr2(&stmt->sql, len); + return stmt + ? fsl_buffer_cstr2(&stmt->sql, len) + : NULL; } char const * fsl_db_filename(fsl_db const * db, fsl_size_t * len){ if(len && db->filename) *len = fsl_strlen(db->filename); return db->filename; @@ -15046,13 +14728,13 @@ } return rc; } void fsl_db_close( fsl_db * const db ){ - void const * const allocStamp = db->allocStamp; + if(!db) return; + void const * allocStamp = db->allocStamp; fsl_cx * const f = db->f; - if(!db->dbh) return; fsl_db_stmt_cache_clear(db); if(db->f && db->f->dbMain==db){ /* Horrible, horrible dependency, and only necessary if the fsl_cx API gets sloppy or repo/checkout/config DBs are @@ -15067,13 +14749,13 @@ if(0!=db->openStatementCount){ MARKER(("WARNING: %d open statement(s) left on db [%s].\n", (int)db->openStatementCount, db->filename)); } if(db->dbh){ - sqlite3_close_v2(db->dbh); - /* Ignore results in the style of "destructors - may not throw.". */ + sqlite3_close(db->dbh); + /* ignoring results in the style of "destructors may not + throw". */ } fsl__db_clear_strings(db, true); fsl_db_cleanup_beforeCommit(db); fsl_buffer_clear(&db->cachePrepBuf); *db = fsl_db_empty; @@ -15109,11 +14791,11 @@ } /** Returns the db name for the given role. */ -const char * fsl_db_role_name(fsl_dbrole_e r){ +const char * fsl_db_role_label(fsl_dbrole_e r){ switch(r){ case FSL_DBROLE_CONFIG: return "cfg"; case FSL_DBROLE_REPO: return "repo"; @@ -15123,10 +14805,11 @@ return "main"; case FSL_DBROLE_TEMP: return "temp"; case FSL_DBROLE_NONE: default: + assert(!"cannot happen/not legal"); return NULL; } } char * fsl_db_julian_to_iso8601( fsl_db * const db, double j, @@ -15354,11 +15037,11 @@ } end: return rc; } -int fsl_db_prepare_cached( fsl_db * const db, fsl_stmt ** st, char const * sql, ... ){ +int fsl_db_prepare_cached( fsl_db * db, fsl_stmt ** st, char const * sql, ... ){ int rc; va_list args; va_start(args,sql); rc = fsl_db_preparev_cached( db, st, sql, args ); va_end(args); @@ -15407,11 +15090,11 @@ int fsl_stmt_finalize( fsl_stmt * const stmt ){ if(!stmt) return FSL_RC_MISUSE; else{ void const * allocStamp = stmt->allocStamp; - fsl_db * const db = stmt->db; + fsl_db * db = stmt->db; if(db){ if(stmt->sql.mem){ /* ^^^ b/c that buffer is set at the same time that openStatementCount is incremented. */ @@ -15488,11 +15171,11 @@ } return rc; } int fsl_stmt_step( fsl_stmt * const stmt ){ - if(!stmt->stmt) return FSL_RC_MISUSE; + if(!stmt || !stmt->stmt) return FSL_RC_MISUSE; else{ int const rc = sqlite3_step(stmt->stmt); assert(stmt->db); switch( rc ){ case SQLITE_ROW: @@ -15499,18 +15182,20 @@ ++stmt->rowCount; return FSL_RC_STEP_ROW; case SQLITE_DONE: return FSL_RC_STEP_DONE; default: - return fsl__db_errcode(stmt->db, rc); + return fsl_error_set(&stmt->db->error, FSL_RC_STEP_ERROR, + "sqlite3_step(): sqlite error #%d: %s", + rc, sqlite3_errmsg(stmt->db->dbh)); } } } -int fsl_db_eachv( fsl_db * const db, fsl_stmt_each_f callback, +int fsl_db_eachv( fsl_db * db, fsl_stmt_each_f callback, void * callbackState, char const * sql, va_list args ){ - if(!db->dbh || !callback || !sql) return FSL_RC_MISUSE; + if(!db || !db->dbh || !callback || !sql) return FSL_RC_MISUSE; else if(!*sql) return FSL_RC_RANGE; else{ fsl_stmt st = fsl_stmt_empty; int rc; rc = fsl_db_preparev( db, &st, sql, args ); @@ -15520,36 +15205,36 @@ } return rc; } } -int fsl_db_each( fsl_db * const db, fsl_stmt_each_f callback, +int fsl_db_each( fsl_db * db, fsl_stmt_each_f callback, void * callbackState, char const * sql, ... ){ int rc; va_list args; va_start(args,sql); rc = fsl_db_eachv( db, callback, callbackState, sql, args ); va_end(args); return rc; } -int fsl_stmt_each( fsl_stmt * const stmt, fsl_stmt_each_f callback, +int fsl_stmt_each( fsl_stmt * stmt, fsl_stmt_each_f callback, void * callbackState ){ - if(!callback) return FSL_RC_MISUSE; + if(!stmt || !callback) return FSL_RC_MISUSE; else{ int strc; int rc = 0; - bool doBreak = false; + char doBreak = 0; while( !doBreak && (FSL_RC_STEP_ROW == (strc=fsl_stmt_step(stmt)))){ rc = callback( stmt, callbackState ); switch(rc){ case 0: continue; case FSL_RC_BREAK: rc = 0; /* fall through */ default: - doBreak = true; + doBreak = 1; break; } } return rc ? rc @@ -15564,11 +15249,11 @@ else{ int const rc = sqlite3_reset(stmt->stmt); if(resetRowCounter) stmt->rowCount = 0; assert(stmt->db); return rc - ? fsl__db_errcode(stmt->db, rc) + ? fsl_err_from_db(stmt->db, rc) : 0; } } int fsl_stmt_reset( fsl_stmt * const stmt ){ @@ -15717,49 +15402,49 @@ #define BIND_PARAM_CHECK2 BIND_PARAM_CHECK \ if(ndx<1 || ndx>stmt->paramCount) return FSL_RC_RANGE; else int fsl_stmt_bind_null( fsl_stmt * const stmt, int ndx ){ BIND_PARAM_CHECK2 { int const rc = sqlite3_bind_null( stmt->stmt, ndx ); - return rc ? fsl__db_errcode(stmt->db, rc) : 0; + return rc ? fsl_err_from_db(stmt->db, rc) : 0; } } int fsl_stmt_bind_int32( fsl_stmt * const stmt, int ndx, int32_t v ){ BIND_PARAM_CHECK2 { int const rc = sqlite3_bind_int( stmt->stmt, ndx, (int)v ); - return rc ? fsl__db_errcode(stmt->db, rc) : 0; + return rc ? fsl_err_from_db(stmt->db, rc) : 0; } } int fsl_stmt_bind_int64( fsl_stmt * const stmt, int ndx, int64_t v ){ BIND_PARAM_CHECK2 { int const rc = sqlite3_bind_int64( stmt->stmt, ndx, (sqlite3_int64)v ); - return rc ? fsl__db_errcode(stmt->db, rc) : 0; + return rc ? fsl_err_from_db(stmt->db, rc) : 0; } } int fsl_stmt_bind_id( fsl_stmt * const stmt, int ndx, fsl_id_t v ){ BIND_PARAM_CHECK2 { int const rc = sqlite3_bind_int64( stmt->stmt, ndx, (sqlite3_int64)v ); - return rc ? fsl__db_errcode(stmt->db, rc) : 0; + return rc ? fsl_err_from_db(stmt->db, rc) : 0; } } int fsl_stmt_bind_double( fsl_stmt * const stmt, int ndx, double v ){ BIND_PARAM_CHECK2 { int const rc = sqlite3_bind_double( stmt->stmt, ndx, (double)v ); - return rc ? fsl__db_errcode(stmt->db, rc) : 0; + return rc ? fsl_err_from_db(stmt->db, rc) : 0; } } int fsl_stmt_bind_blob( fsl_stmt * const stmt, int ndx, void const * src, fsl_size_t len, bool makeCopy ){ BIND_PARAM_CHECK2 { int rc; rc = sqlite3_bind_blob( stmt->stmt, ndx, src, (int)len, makeCopy ? SQLITE_TRANSIENT : SQLITE_STATIC ); - return rc ? fsl__db_errcode(stmt->db, rc) : 0; + return rc ? fsl_err_from_db(stmt->db, rc) : 0; } } int fsl_stmt_bind_text( fsl_stmt * const stmt, int ndx, char const * src, fsl_int_t len, bool makeCopy ){ @@ -15766,11 +15451,11 @@ BIND_PARAM_CHECK { int rc; if(len<0) len = fsl_strlen((char const *)src); rc = sqlite3_bind_text( stmt->stmt, ndx, src, len, makeCopy ? SQLITE_TRANSIENT : SQLITE_STATIC ); - return rc ? fsl__db_errcode(stmt->db, rc) : 0; + return rc ? fsl_err_from_db(stmt->db, rc) : 0; } } int fsl_stmt_bind_null_name( fsl_stmt * const stmt, char const * param ){ BIND_PARAM_CHECK{ @@ -15888,11 +15573,11 @@ if(out) *out = (char const *)t; if(outLen){ int const x = sqlite3_column_bytes(stmt->stmt, ndx); *outLen = (x>0) ? (fsl_size_t)x : 0; } - return t ? 0 : fsl__db_errcode(stmt->db, 0); + return 0; } } int fsl_stmt_get_blob( fsl_stmt * const stmt, int ndx, void const **out, fsl_size_t * outLen ){ @@ -15906,11 +15591,11 @@ else{ int sz = sqlite3_column_bytes(stmt->stmt, ndx); *outLen = (sz>=0) ? (fsl_size_t)sz : 0; } } - return t ? 0 : fsl__db_errcode(stmt->db, 0); + return 0; } } #undef GET_CHECK @@ -15942,35 +15627,426 @@ return rv; } /** - This sqlite3_trace_v2() callback outputs tracing info using - fsl_fprintf((FILE*)c,...). Defaults to stdout if c is NULL. -*/ -static int fsl__db_sq3TraceV2(unsigned t,void*c,void*p,void*x){ - static unsigned int counter = 0; - if(c ||p){/*unused*/} - switch(t){ - case SQLITE_TRACE_STMT:{ - char const * zSql = (char const *)x; - char * zExp = zSql - ? sqlite3_expanded_sql((sqlite3_stmt*)p) - : NULL; - fsl_fprintf(c ? (FILE*)c : stdout, - "SQL TRACE #%u: %s\n", - ++counter, - zExp ? zExp : - (zSql ? zSql : "(NO SQL?)")); - sqlite3_free(zExp); - break; - } - default: - break; - } - return 0; -} + This function outputs tracing info using fsl_fprintf((FILE*)zFILE,...). + Defaults to stdout if zFILE is 0. + */ +static void fsl_db_sql_trace(void *zFILE, const char *zSql){ + int const n = fsl_strlen(zSql); + static int counter = 0; + /* FIXME: in v1 this uses fossil_trace(), but don't have + that functionality here yet. */ + fsl_fprintf(zFILE ? (FILE*)zFILE : stdout, + "SQL TRACE #%d: %s%s\n", ++counter, + zSql, (n>0 && zSql[n-1]==';') ? "" : ";"); +} + +/* + SQL function for debugging. + + The print() function writes its arguments to fsl_output() + if the bound fsl_cx->cxConfig.sqlPrint flag is true. +*/ +static void fsl_db_sql_print( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); + assert(f); + if( f->cxConfig.sqlPrint ){ + int i; + for(i=0; ickout.dir && f->ckout.dirLen){ + sqlite3_result_text(context, f->ckout.dir, + (int)f->ckout.dirLen + - (includeSlash ? 0 : 1), + SQLITE_TRANSIENT); + }else{ + sqlite3_result_null(context); + } +} + + +/** + SQL Function to return the check-in time for a file. + Requires (vid,fid) RID arguments, as described for + fsl_mtime_of_manifest_file(). + */ +static void fsl_db_checkin_mtime_udf( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); + fsl_time_t mtime = 0; + int rc; + fsl_id_t vid, fid; + assert(f); + vid = (fsl_id_t)sqlite3_value_int(argv[0]); + fid = (fsl_id_t)sqlite3_value_int(argv[1]); + rc = fsl_mtime_of_manifest_file(f, vid, fid, &mtime); + if( rc==0 ){ + sqlite3_result_int64(context, mtime); + }else{ + sqlite3_result_error(context, "fsl_mtime_of_manifest_file() failed", -1); + } +} + + +static void fsl_db_content_udf( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); + fsl_id_t rid = 0; + char const * arg; + int rc; + fsl_buffer b = fsl_buffer_empty; + assert(f); + if(1 != argc){ + sqlite3_result_error(context, "Expecting one argument", -1); + return; + } + if(SQLITE_INTEGER==sqlite3_value_type(argv[0])){ + rid = (fsl_id_t)sqlite3_value_int64(argv[0]); + arg = NULL; + }else{ + arg = (const char*)sqlite3_value_text(argv[0]); + if(!arg){ + sqlite3_result_error(context, "Invalid argument", -1); + return; + } + rc = fsl_sym_to_rid(f, arg, FSL_SATYPE_CHECKIN, &rid); + if(rc) goto cx_err; + else if(!rid){ + sqlite3_result_error(context, "No blob found", -1); + return; + } + } + rc = fsl_content_get(f, rid, &b); + if(rc) goto cx_err; + /* Curiously, i'm seeing no difference in allocation counts here... */ + sqlite3_result_blob(context, b.mem, (int)b.used, fsl_free); + b = fsl_buffer_empty; + return; + cx_err: + fsl_buffer_clear(&b); + assert(f->error.msg.used); + if(FSL_RC_OOM==rc){ + sqlite3_result_error_nomem(context); + }else{ + assert(f->error.msg.used); + sqlite3_result_error(context, (char const *)f->error.msg.mem, + (int)f->error.msg.used); + } +} + +static void fsl_db_sym2rid_udf( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); + char const * arg; + assert(f); + if(1 != argc){ + sqlite3_result_error(context, "Expecting one argument", -1); + return; + } + arg = (const char*)sqlite3_value_text(argv[0]); + if(!arg){ + sqlite3_result_error(context, "Expecting a STRING argument", -1); + }else{ + fsl_id_t rid = 0; + int const rc = fsl_sym_to_rid(f, arg, FSL_SATYPE_CHECKIN, &rid); + if(rc){ + if(FSL_RC_OOM==rc){ + sqlite3_result_error_nomem(context); + }else{ + assert(f->error.msg.used); + sqlite3_result_error(context, (char const *)f->error.msg.mem, + (int)f->error.msg.used); + } + fsl_cx_err_reset(f) + /* This is arguable but keeps this error from poluting + down-stream code (seen it happen in unit tests). The irony + is, it's very possible/likely that the error will propagate + back up into f->error at some point. + */; + }else{ + assert(rid>0); + sqlite3_result_int64(context, rid); + } + } +} + +static void fsl_db_dirpart_udf( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + char const * arg; + int rc; + fsl_buffer b = fsl_buffer_empty; + int fSlash = 0; + if(argc<1 || argc>2){ + sqlite3_result_error(context, + "Expecting (string) or (string,bool) arguments", + -1); + return; + } + arg = (const char*)sqlite3_value_text(argv[0]); + if(!arg){ + sqlite3_result_error(context, "Invalid argument", -1); + return; + } + if(argc>1){ + fSlash = sqlite3_value_int(argv[1]); + } + rc = fsl_file_dirpart(arg, -1, &b, fSlash ? 1 : 0); + if(!rc){ + if(b.used && *b.mem){ +#if 0 + sqlite3_result_text(context, (char const *)b.mem, + (int)b.used, SQLITE_TRANSIENT); +#else + sqlite3_result_text(context, (char const *)b.mem, + (int)b.used, fsl_free); + b = fsl_buffer_empty /* we passed ^^^^^ on ownership of b.mem */; +#endif + }else{ + sqlite3_result_null(context); + } + }else{ + if(FSL_RC_OOM==rc){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_result_error(context, "fsl_dirpart() failed!", -1); + } + } + fsl_buffer_clear(&b); +} + + +/* + Implement the user() SQL function. user() takes no arguments and + returns the user ID of the current user. +*/ +static void fsl_db_user_udf( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); + assert(f); + if(f->repo.user){ + sqlite3_result_text(context, f->repo.user, -1, SQLITE_STATIC); + }else{ + sqlite3_result_null(context); + } +} + +/** + SQL function: + + fsl_is_enqueued(vfile.id) + fsl_if_enqueued(vfile.id, X, Y) + + On the commit command, when filenames are specified (in order to do + a partial commit) the vfile.id values for the named files are + loaded into the fsl_cx state. This function looks at that state to + see if a file is named in that list. + + In the first form (1 argument) return TRUE if either no files are + named (meaning that all changes are to be committed) or if id is + found in the list. + + In the second form (3 arguments) return argument X if true and Y if + false unless Y is NULL, in which case always return X. +*/ +static void fsl_db_selected_for_checkin_udf( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int rc = 0; + fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); + fsl_id_bag * bag = &f->ckin.selectedIds; + assert(argc==1 || argc==3); + if( bag->entryCount ){ + fsl_id_t const iId = (fsl_id_t)sqlite3_value_int64(argv[0]); + rc = iId ? (fsl_id_bag_contains(bag, iId) ? 1 : 0) : 0; + }else{ + rc = 1; + } + if(1==argc){ + sqlite3_result_int(context, rc); + }else{ + assert(3 == argc); + assert( rc==0 || rc==1 ); + if( sqlite3_value_type(argv[2-rc])==SQLITE_NULL ) rc = 1-rc; + sqlite3_result_value(context, argv[2-rc]); + } +} + +/** + fsl_match_vfile_or_dir(p1,p2) + + A helper for resolving expressions like: + + WHERE pathname='X' C OR + (pathname>'X/' C AND pathname<'X0' C) + + i.e. is 'X' a match for the LHS or is it a directory prefix of + LHS? + + C = empty or COLLATE NOCASE, depending on the case-sensitivity + setting of the fsl_cx instance associated with + sqlite3_user_data(context). p1 is typically vfile.pathname or + vfile.origname, and p2 is the string being compared against that. + + Resolves to NULL if either argument is NULL, 0 if the comparison + shown above is false, 1 if the comparison is an exact match, or 2 + if p2 is a directory prefix part of p1. +*/ +static void fsl_db_match_vfile_or_dir( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); + char const * p1; + char const * p2; + fsl_buffer * b = 0; + int rc = 0; + assert(f); + if(2 != argc){ + sqlite3_result_error(context, "Expecting two arguments", -1); + return; + } + p1 = (const char*)sqlite3_value_text(argv[0]); + p2 = (const char*)sqlite3_value_text(argv[1]); + if(!p1 || !p2){ + sqlite3_result_null(context); + return; + } + int (*cmp)(char const *, char const *) = + f->cache.caseInsensitive ? fsl_stricmp : fsl_strcmp; + if(0==cmp(p1, p2)){ + sqlite3_result_int(context, 1); + return; + } + b = fsl__cx_scratchpad(f); + rc = fsl_buffer_appendf(b, "%s/", p2); + if(rc) goto oom; + else if(cmp(p1, fsl_buffer_cstr(b))>0){ + b->mem[b->used-1] = '0'; + if(cmp(p1, fsl_buffer_cstr(b))<0) + rc = 2; + } + assert(0==rc || 2==rc); + sqlite3_result_int(context, rc); + end: + fsl__cx_scratchpad_yield(f, b); + return; + oom: + sqlite3_result_error_nomem(context); + goto end; +} + +/** + F(glob-list-name, filename) + + Returns 1 if the 2nd argument matches any glob in the fossil glob + list named by the first argument. The first argument must be a name + resolvable via fsl_glob_name_to_category() or an error is + triggered. The second value is intended to be a string, but NULL is + accepted (but never matches anything). + + If no match is found, 0 is returned. An empty glob list never matches + anything. +*/ +static void fsl_db_cx_glob_udf( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + fsl_cx * const f = (fsl_cx*)sqlite3_user_data(context); + fsl_list * li = NULL; + fsl_glob_category_e globType; + char const * p1; + char const * p2; + p2 = (const char*)sqlite3_value_text(argv[1])/*value to check*/; + if(NULL==p2 || 0==p2[0]){ + sqlite3_result_int(context, 0); + return; + } + p1 = (const char*)sqlite3_value_text(argv[0])/*glob set name*/; + globType = fsl_glob_name_to_category(p1); + if(FSL_GLOBS_INVALID==globType){ + char buf[100] = {0}; + buf[sizeof(buf)-1] = 0; + fsl_snprintf(buf, (fsl_size_t)sizeof(buf)-1, + "Unknown glob pattern name: %#.*s", + 50, p1 ? p1 : "NULL"); + sqlite3_result_error(context, buf, -1); + return; + } + fsl_cx_glob_list(f, globType, &li, false); + assert(li); + sqlite3_result_int(context, fsl_glob_list_matches(li, p2) ? 1 : 0); +} + fsl_db * fsl_db_malloc(){ fsl_db * rc = (fsl_db *)fsl_malloc(sizeof(fsl_db)); if(rc){ *rc = fsl_db_empty; @@ -15986,32 +16062,64 @@ rc->allocStamp = &fsl_stmt_empty; } return rc; } + +/** + Return true if the schema is out-of-date. db must be an opened + repo db. + */ +static char fsl_db_repo_schema_is_outofdate(fsl_db *db){ + return fsl_db_exists(db, "SELECT 1 FROM config " + "WHERE name='aux-schema' " + "AND value<>'%s'", + FSL_AUX_SCHEMA); +} + +/* + Returns 0 if db appears to have a current repository schema, 1 if + it appears to have an out of date schema, and -1 if it appears to + not be a repository. +*/ +int fsl__db_repo_verify_schema(fsl_db * db){ + if(fsl_db_repo_schema_is_outofdate(db)) return 1; + else return fsl_db_exists(db, + "SELECT 1 FROM config " + "WHERE name='project-code'") + ? 0 : -1; +} + /** Callback for use with sqlite3_commit_hook(). The argument must be a (fsl_db*). This function returns 0 only if it surmises that fsl_db_transaction_end() triggered the COMMIT. On error it might assert() or abort() the application, so this really is just a sanity check for something which "must not happen." */ static int fsl_db_verify_begin_was_not_called(void * db_fsl){ - fsl_db * const db = (fsl_db *)db_fsl; +#if 0 + return 0; +#else + /* i cannot explain why, but the ptr i'm getting here is most definately + not a proper fsl_db. */ + fsl_db * db = (fsl_db *)db_fsl; assert(db && "What else could it be?"); assert(db->dbh && "Else we can't have been called by sqlite3, could we have?"); if(db->beginCount>0){ fsl__fatal(FSL_RC_MISUSE,"SQL: COMMIT was called from " "outside of fsl_db_transaction_end() while a " "fsl_db_transaction_begin()-started transaction " "is pending."); return 2; } - return 0; + /* we have no context: sqlite3_result_error(context, "fsl_mtime_of_manifest_file() failed", -1); */ + else return 0; +#endif } -int fsl_db_open( fsl_db * const db, char const * dbFile, +int fsl_db_open( fsl_db * db, char const * dbFile, int openFlags ){ int rc; fsl_dbh_t * dbh = NULL; int isMem = 0; if(!db || !dbFile) return FSL_RC_MISUSE; @@ -16022,20 +16130,24 @@ return fsl_error_set(&db->error, FSL_RC_NOT_FOUND, "DB file not found: %s", dbFile); } else{ int sOpenFlags = 0; - if(FSL_OPEN_F_RO & openFlags){ - sOpenFlags |= SQLITE_OPEN_READONLY; + if(isMem){ + sOpenFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; }else{ - if(FSL_OPEN_F_RW & openFlags){ - sOpenFlags |= SQLITE_OPEN_READWRITE; + if(FSL_OPEN_F_RO & openFlags){ + sOpenFlags |= SQLITE_OPEN_READONLY; + }else{ + if(FSL_OPEN_F_RW & openFlags){ + sOpenFlags |= SQLITE_OPEN_READWRITE; + } + if(FSL_OPEN_F_CREATE & openFlags){ + sOpenFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; + } + if(!sOpenFlags) sOpenFlags = SQLITE_OPEN_READONLY; } - if(FSL_OPEN_F_CREATE & openFlags){ - sOpenFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; - } - if(!sOpenFlags) sOpenFlags = SQLITE_OPEN_READONLY; } rc = sqlite3_open_v2( dbFile, &dbh, sOpenFlags, NULL ); if(rc){ if(dbh){ /* By some complete coincidence, FSL_RC_DB==SQLITE_CANTOPEN. */ @@ -16073,15 +16185,107 @@ rc = FSL_RC_OOM; goto end; } } db->dbh = dbh; - sqlite3_extended_result_codes(dbh, 1); - sqlite3_commit_hook(dbh, fsl_db_verify_begin_was_not_called, db); - if(FSL_OPEN_F_TRACE_SQL & openFlags){ + if(FSL_OPEN_F_SCHEMA_VALIDATE & openFlags){ + int check; + check = fsl__db_repo_verify_schema(db); + if(0 != check){ + rc = (check<0) + ? fsl_error_set(&db->error, FSL_RC_NOT_A_REPO, + "DB file [%s] does not appear to be " + "a repository.", dbFile) + : fsl_error_set(&db->error, FSL_RC_REPO_NEEDS_REBUILD, + "DB file [%s] appears to be a fossil " + "repsitory, but is out-of-date and needs " + "a rebuild.", + dbFile); + assert(rc == db->error.code); + goto end; + } + } + + if( (openFlags & FSL_OPEN_F_TRACE_SQL) + || (db->f && db->f->cxConfig.traceSql) ){ fsl_db_sqltrace_enable(db, stdout); } + + if(db->f){ + /* + Plug in fsl_cx-specific functionality to this one. + + TODO: move this into the fsl_cx code. Its placement here is + largely historical. + */ + fsl_cx * f = db->f; + /* This all comes from db.c:db_open()... */ + /* FIXME: check result codes here. */ + sqlite3_commit_hook(dbh, fsl_db_verify_begin_was_not_called, db); + sqlite3_busy_timeout(dbh, 5000 /* historical value */); + sqlite3_wal_autocheckpoint(dbh, 1); /* Set to checkpoint frequently */ + sqlite3_exec(dbh, "PRAGMA foreign_keys=OFF;", 0, 0, 0); + sqlite3_create_function(dbh, "now", 0, SQLITE_ANY, 0, + fsl_db_now_udf, 0, 0); + sqlite3_create_function(dbh, "fsl_ci_mtime", 2, + SQLITE_ANY | SQLITE_DETERMINISTIC, f, + fsl_db_checkin_mtime_udf, 0, 0); + sqlite3_create_function(dbh, "fsl_user", 0, + SQLITE_ANY | SQLITE_DETERMINISTIC, f, + fsl_db_user_udf, 0, 0); + sqlite3_create_function(dbh, "fsl_print", -1, + SQLITE_UTF8 + /* not strictly SQLITE_DETERMINISTIC + because it produces output */, + f, fsl_db_sql_print,0,0); + sqlite3_create_function(dbh, "fsl_content", 1, + SQLITE_ANY | SQLITE_DETERMINISTIC, f, + fsl_db_content_udf, 0, 0); + sqlite3_create_function(dbh, "fsl_sym2rid", 1, + SQLITE_ANY | SQLITE_DETERMINISTIC, f, + fsl_db_sym2rid_udf, 0, 0); + sqlite3_create_function(dbh, "fsl_dirpart", 1, + SQLITE_ANY | SQLITE_DETERMINISTIC, NULL, + fsl_db_dirpart_udf, 0, 0); + sqlite3_create_function(dbh, "fsl_dirpart", 2, + SQLITE_ANY | SQLITE_DETERMINISTIC, NULL, + fsl_db_dirpart_udf, 0, 0); + sqlite3_create_function(dbh, "fsl_j2u", 1, + SQLITE_ANY | SQLITE_DETERMINISTIC, NULL, + fsl_db_j2u_udf, 0, 0); + /* + fsl_i[sf]_selected() both require access to the f's list of + files being considered for commit. + */ + sqlite3_create_function(dbh, "fsl_is_enqueued", 1, SQLITE_UTF8, f, + fsl_db_selected_for_checkin_udf,0,0 ); + sqlite3_create_function(dbh, "fsl_if_enqueued", 3, SQLITE_UTF8, f, + fsl_db_selected_for_checkin_udf,0,0 ); + + sqlite3_create_function(dbh, "fsl_ckout_dir", -1, + SQLITE_ANY /* | SQLITE_DETERMINISTIC ? */, + f, fsl_db_cx_chkout_dir_udf,0,0 ); + sqlite3_create_function(dbh, "fsl_match_vfile_or_dir", 2, + SQLITE_ANY | SQLITE_DETERMINISTIC, + f, fsl_db_match_vfile_or_dir,0,0 ); + sqlite3_create_function(dbh, "fsl_glob", 2, + SQLITE_UTF8 | SQLITE_DETERMINISTIC, + /* noting that ^^^^^ it's only deterministic + for a given statement execution IF no SQL + triggers an effect which forces the globs to + reload. That "shouldn't ever happen." */ + f, fsl_db_cx_glob_udf, 0, 0 ); + +#if 0 + /* functions registered in v1 by db.c:db_open(). */ + /* porting cgi() requires access to the HTTP/CGI + layer. i.e. this belongs downstream. */ + sqlite3_create_function(dbh, "cgi", 1, SQLITE_ANY, 0, db_sql_cgi, 0, 0); + sqlite3_create_function(dbh, "cgi", 2, SQLITE_ANY, 0, db_sql_cgi, 0, 0); + re_add_sql_func(db) /* Requires the regex bits. */; +#endif + }/*if(db->f)*/ } end: if(rc){ #if 1 /* This is arguable... */ @@ -16098,23 +16302,12 @@ assert(db->dbh); } return rc; } - -static int fsl__db_err_not_opened(fsl_db * const db){ - return fsl_error_set(&db->error, FSL_RC_MISUSE, - "DB is not opened."); -} -static int fsl__db_err_sql_empty(fsl_db * const db){ - return fsl_error_set(&db->error, FSL_RC_MISUSE, - "Empty SQL is not permitted."); - } - int fsl_db_exec_multiv( fsl_db * const db, const char * sql, va_list args){ - if(!db->dbh) return fsl__db_err_not_opened(db); - else if(!sql || !*sql) return fsl__db_err_sql_empty(db); + if(!db || !db->dbh || !sql) return FSL_RC_MISUSE; else{ fsl_buffer buf = fsl_buffer_empty; int rc = 0; char const * z; char const * zEnd = NULL; @@ -16126,17 +16319,17 @@ z = fsl_buffer_cstr(&buf); while( (SQLITE_OK==rc) && *z ){ fsl_stmt_t * pStmt = NULL; rc = sqlite3_prepare_v2(db->dbh, z, buf.used, &pStmt, &zEnd); if( SQLITE_OK != rc ){ - rc = fsl__db_errcode(db, rc); + rc = fsl_err_from_db(db, rc); break; } if(pStmt){ while( SQLITE_ROW == sqlite3_step(pStmt) ){} rc = sqlite3_finalize(pStmt); - if(rc) rc = fsl__db_errcode(db, rc); + if(rc) rc = fsl_err_from_db(db, rc); } buf.used -= (zEnd-z); z = zEnd; } fsl_buffer_reserve(&buf, 0); @@ -16143,12 +16336,11 @@ return rc; } } int fsl_db_exec_multi( fsl_db * const db, const char * sql, ...){ - if(!db->dbh) return fsl__db_err_not_opened(db); - else if(!sql || !*sql) return fsl__db_err_sql_empty(db); + if(!db || !db->dbh || !sql) return FSL_RC_MISUSE; else{ int rc; va_list args; va_start(args,sql); rc = fsl_db_exec_multiv( db, sql, args ); @@ -16156,34 +16348,27 @@ return rc; } } int fsl_db_execv( fsl_db * const db, const char * sql, va_list args){ - if(!db->dbh) return fsl__db_err_not_opened(db); - else if(!sql || !*sql) return fsl__db_err_sql_empty(db); + if(!db || !db->dbh || !sql) return FSL_RC_MISUSE; else{ fsl_stmt st = fsl_stmt_empty; int rc = 0; rc = fsl_db_preparev( db, &st, sql, args ); - if(0==rc){ - //while(FSL_RC_STEP_ROW == (rc=fsl_stmt_step(&st))){} - //^^^ why did we historically do this instead of: - rc = fsl_stmt_step( &st ); - fsl_stmt_finalize(&st); - } - switch(rc){ - case FSL_RC_STEP_DONE: - case FSL_RC_STEP_ROW: rc = 0; break; - default: break; - } - return rc; + if(rc) return rc; + /* rc = fsl_stmt_step( &st ); */ + while(FSL_RC_STEP_ROW == (rc=fsl_stmt_step(&st))){} + fsl_stmt_finalize(&st); + return (FSL_RC_STEP_ERROR==rc) + ? FSL_RC_DB + : 0; } } int fsl_db_exec( fsl_db * const db, const char * sql, ...){ - if(!db->dbh) return fsl__db_err_not_opened(db); - else if(!sql || !*sql) return fsl__db_err_sql_empty(db); + if(!db || !db->dbh || !sql) return FSL_RC_MISUSE; else{ int rc; va_list args; va_start(args,sql); rc = fsl_db_execv( db, sql, args ); @@ -16191,17 +16376,17 @@ return rc; } } int fsl_db_changes_recent(fsl_db * const db){ - return db->dbh + return (db && db->dbh) ? sqlite3_changes(db->dbh) : 0; } int fsl_db_changes_total(fsl_db * const db){ - return db->dbh + return (db && db->dbh) ? sqlite3_total_changes(db->dbh) : 0; } /** @@ -16229,25 +16414,24 @@ int fsl_db_transaction_level(fsl_db * const db){ return db->doRollback ? -db->beginCount : db->beginCount; } int fsl_db_transaction_commit(fsl_db * const db){ - return db->dbh + return (db && db->dbh) ? fsl_db_transaction_end(db, 0) : FSL_RC_MISUSE; } int fsl_db_transaction_rollback(fsl_db * const db){ - return db->dbh + return (db && db->dbh) ? fsl_db_transaction_end(db, 1) : FSL_RC_MISUSE; } int fsl_db_rollback_force( fsl_db * const db ){ - if(!db->dbh){ - return fsl__db_err_not_opened(db); - }else{ + if(!db || !db->dbh) return FSL_RC_MISUSE; + else{ int rc; db->beginCount = 0; fsl_db_cleanup_beforeCommit(db); rc = fsl_db_exec(db, "ROLLBACK"); fsl_db_reset_change_count(db); @@ -16255,13 +16439,12 @@ } } int fsl_db_transaction_end(fsl_db * const db, bool doRollback){ int rc = 0; - if(!db->dbh){ - return fsl__db_err_not_opened(db); - }else if (db->beginCount<=0){ + if(!db || !db->dbh) return FSL_RC_MISUSE; + else if (db->beginCount<=0){ return fsl_error_set(&db->error, FSL_RC_RANGE, "No transaction is active."); } if(doRollback) ++db->doRollback /* ACHTUNG: note that db->dbRollback is set before @@ -16270,61 +16453,37 @@ transaction's stack. */; if(--db->beginCount > 0) return 0; assert(0==db->beginCount && "The commit-hook check relies on this."); assert(db->doRollback>=0); - int const changeCount = - sqlite3_total_changes(db->dbh) - db->priorChanges; - if(0==db->doRollback){ - if(changeCount>0){ - /* Execute before-commit hooks and leaf checks */ - fsl_size_t x = 0; - for( ; !rc && (x < db->beforeCommit.used); ++x ){ - char const * sql = (char const *)db->beforeCommit.list[x]; - /* MARKER(("Running before-commit code: [%s]\n", sql)); */ - if(sql) rc = fsl_db_exec_multi( db, "%s", sql ); - } - if(!rc && db->f && (FSL_DBROLE_REPO & db->role)){ - /* - i don't like this one bit - this is low-level SCM - functionality in an otherwise generic routine. Maybe we need - fsl_cx_transaction_begin/end() instead. - - Much later: we have that routine now but will need to replace - all relevant calls to fsl_db_transaction_begin()/end() with - those routines before we can consider moving this there. - */ - rc = fsl__repo_leafdo_pending_checks(db->f); - if(!rc && db->f->cache.toVerify.used){ - rc = fsl__repo_verify_at_commit(db->f); - }else{ - fsl_repo_verify_cancel(db->f); - } - } - db->doRollback = rc ? 1 : 0; - } - } - if(db->doRollback && db->f && changeCount>0){ - /** - If a rollback is underway (from a transaction in which data was - written), certain fsl_cx caches might be referring to record - IDs which were injected as part of the being-rolled-back - transaction. The only(?) reasonably sane way to deal with that - is to flush all relevant caches. It is unfortunate that this - bit is in the db class, as opposed to the fsl_cx class, but we - currently have no hook which would allow us to trigger this - from that class. - */ -#if 1 - fsl__bccache_reset(&db->f->cache.blobContent); - fsl__cx_mcache_clear(db->f); -#else - /* This one resets all of ^^^ plus certain repo-side config - settings, but it's not yet clear whether that they will be - reloaded when needed. */ - fsl__cx_clear_repo_caches(d->f); -#endif + if((0==db->doRollback) + && (db->priorChanges < sqlite3_total_changes(db->dbh))){ + /* Execute before-commit hooks and leaf checks */ + fsl_size_t x = 0; + for( ; !rc && (x < db->beforeCommit.used); ++x ){ + char const * sql = (char const *)db->beforeCommit.list[x]; + /* MARKER(("Running before-commit code: [%s]\n", sql)); */ + if(sql) rc = fsl_db_exec_multi( db, "%s", sql ); + } + if(!rc && db->f && (FSL_DBROLE_REPO & db->role)){ + /* + i don't like this one bit - this is low-level SCM + functionality in an otherwise generic routine. Maybe we need + fsl_cx_transaction_begin/end() instead. + + Much later: we have that routine now but will need to replace + all relevant calls to fsl_db_transaction_begin()/end() with + those routines before we can consider moving this there. + */ + rc = fsl__repo_leafdo_pending_checks(db->f); + if(!rc && db->f->cache.toVerify.used){ + rc = fsl__repo_verify_at_commit(db->f); + }else{ + fsl_repo_verify_cancel(db->f); + } + } + db->doRollback = rc ? 1 : 0; } fsl_db_cleanup_beforeCommit(db); fsl_db_reset_change_count(db); rc = fsl_db_exec(db, db->doRollback ? "ROLLBACK" : "COMMIT"); db->doRollback = 0; @@ -16395,11 +16554,11 @@ rc = fsl_db_get_int32v(db, rv, sql, args); va_end(args); return rc; } -int fsl_db_get_int64v( fsl_db * const db, int64_t * rv, +int fsl_db_get_int64v( fsl_db * db, int64_t * rv, char const * sql, va_list args){ if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE; else{ fsl_stmt st = fsl_stmt_empty; int rc = 0; @@ -16420,11 +16579,11 @@ fsl_stmt_finalize(&st); return rc; } } -int fsl_db_get_int64( fsl_db * const db, int64_t * rv, +int fsl_db_get_int64( fsl_db * db, int64_t * rv, char const * sql, ... ){ int rc; va_list args; va_start(args,sql); rc = fsl_db_get_int64v(db, rv, sql, args); @@ -16431,11 +16590,11 @@ va_end(args); return rc; } -int fsl_db_get_idv( fsl_db * const db, fsl_id_t * rv, +int fsl_db_get_idv( fsl_db * db, fsl_id_t * rv, char const * sql, va_list args){ if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE; else{ fsl_stmt st = fsl_stmt_empty; int rc = 0; @@ -16448,18 +16607,19 @@ /* Fall through */ case FSL_RC_STEP_DONE: rc = 0; break; default: + assert(FSL_RC_STEP_ERROR==rc); break; } fsl_stmt_finalize(&st); return rc; } } -int fsl_db_get_id( fsl_db * const db, fsl_id_t * rv, +int fsl_db_get_id( fsl_db * db, fsl_id_t * rv, char const * sql, ... ){ int rc; va_list args; va_start(args,sql); rc = fsl_db_get_idv(db, rv, sql, args); @@ -16466,11 +16626,11 @@ va_end(args); return rc; } -int fsl_db_get_sizev( fsl_db * const db, fsl_size_t * rv, +int fsl_db_get_sizev( fsl_db * db, fsl_size_t * rv, char const * sql, va_list args){ if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE; else{ fsl_stmt st = fsl_stmt_empty; int rc = 0; @@ -16498,11 +16658,11 @@ fsl_stmt_finalize(&st); return rc; } } -int fsl_db_get_size( fsl_db * const db, fsl_size_t * rv, +int fsl_db_get_size( fsl_db * db, fsl_size_t * rv, char const * sql, ... ){ int rc; va_list args; va_start(args,sql); rc = fsl_db_get_sizev(db, rv, sql, args); @@ -16509,11 +16669,11 @@ va_end(args); return rc; } -int fsl_db_get_doublev( fsl_db * const db, double * rv, +int fsl_db_get_doublev( fsl_db * db, double * rv, char const * sql, va_list args){ if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE; else{ fsl_stmt st = fsl_stmt_empty; int rc = 0; @@ -16534,11 +16694,11 @@ fsl_stmt_finalize(&st); return rc; } } -int fsl_db_get_double( fsl_db * const db, double * rv, +int fsl_db_get_double( fsl_db * db, double * rv, char const * sql, ... ){ int rc; va_list args; va_start(args,sql); @@ -16546,11 +16706,11 @@ va_end(args); return rc; } -int fsl_db_get_textv( fsl_db * const db, char ** rv, +int fsl_db_get_textv( fsl_db * db, char ** rv, fsl_size_t *rvLen, char const * sql, va_list args){ if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE; else{ fsl_stmt st = fsl_stmt_empty; @@ -16589,11 +16749,11 @@ fsl_stmt_finalize(&st); return rc; } } -int fsl_db_get_text( fsl_db * const db, char ** rv, +int fsl_db_get_text( fsl_db * db, char ** rv, fsl_size_t * rvLen, char const * sql, ... ){ int rc; va_list args; va_start(args,sql); @@ -16600,11 +16760,11 @@ rc = fsl_db_get_textv(db, rv, rvLen, sql, args); va_end(args); return rc; } -int fsl_db_get_blobv( fsl_db * const db, void ** rv, +int fsl_db_get_blobv( fsl_db * db, void ** rv, fsl_size_t *rvLen, char const * sql, va_list args){ if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE; else{ fsl_stmt st = fsl_stmt_empty; @@ -16641,11 +16801,11 @@ fsl_stmt_finalize(&st); return rc; } } -int fsl_db_get_blob( fsl_db * const db, void ** rv, +int fsl_db_get_blob( fsl_db * db, void ** rv, fsl_size_t * rvLen, char const * sql, ... ){ int rc; va_list args; va_start(args,sql); @@ -16652,12 +16812,12 @@ rc = fsl_db_get_blobv(db, rv, rvLen, sql, args); va_end(args); return rc; } -int fsl_db_get_bufferv( fsl_db * const db, fsl_buffer * const b, - bool asBlob, char const * sql, +int fsl_db_get_bufferv( fsl_db * db, fsl_buffer * b, + char asBlob, char const * sql, va_list args){ if(!db || !db->dbh || !b || !sql || !*sql) return FSL_RC_MISUSE; else{ fsl_stmt st = fsl_stmt_empty; int rc = 0; @@ -16668,32 +16828,29 @@ case FSL_RC_STEP_ROW:{ void const * str = asBlob ? sqlite3_column_blob(st.stmt, 0) : (void const *)sqlite3_column_text(st.stmt, 0); int const len = sqlite3_column_bytes(st.stmt,0); - if(len && !str){ - rc = FSL_RC_OOM; - }else{ - rc = 0; - b->used = 0; - rc = fsl_buffer_append( b, str, len ); - } + rc = 0; + b->used = 0; + rc = fsl_buffer_append( b, str, len ); break; } case FSL_RC_STEP_DONE: rc = 0; break; default: + assert(FSL_RC_STEP_ERROR==rc); break; } fsl_stmt_finalize(&st); return rc; } } -int fsl_db_get_buffer( fsl_db * const db, fsl_buffer * const b, - bool asBlob, +int fsl_db_get_buffer( fsl_db * db, fsl_buffer * b, + char asBlob, char const * sql, ... ){ int rc; va_list args; va_start(args,sql); rc = fsl_db_get_bufferv(db, b, asBlob, sql, args); @@ -16709,11 +16866,11 @@ fsl_db_get_int32v(db, &rv, sql, args); va_end(args); return rv; } -int64_t fsl_db_g_int64( fsl_db * const db, int64_t dflt, +int64_t fsl_db_g_int64( fsl_db * db, int64_t dflt, char const * sql, ... ){ int64_t rv = dflt; va_list args; va_start(args,sql); @@ -16720,11 +16877,11 @@ fsl_db_get_int64v(db, &rv, sql, args); va_end(args); return rv; } -fsl_id_t fsl_db_g_id( fsl_db * const db, fsl_id_t dflt, +fsl_id_t fsl_db_g_id( fsl_db * db, fsl_id_t dflt, char const * sql, ... ){ fsl_id_t rv = dflt; va_list args; va_start(args,sql); @@ -16731,11 +16888,11 @@ fsl_db_get_idv(db, &rv, sql, args); va_end(args); return rv; } -fsl_size_t fsl_db_g_size( fsl_db * const db, fsl_size_t dflt, +fsl_size_t fsl_db_g_size( fsl_db * db, fsl_size_t dflt, char const * sql, ... ){ fsl_size_t rv = dflt; va_list args; va_start(args,sql); @@ -16742,11 +16899,11 @@ fsl_db_get_sizev(db, &rv, sql, args); va_end(args); return rv; } -double fsl_db_g_double( fsl_db * const db, double dflt, +double fsl_db_g_double( fsl_db * db, double dflt, char const * sql, ... ){ double rv = dflt; va_list args; va_start(args,sql); @@ -16753,11 +16910,11 @@ fsl_db_get_doublev(db, &rv, sql, args); va_end(args); return rv; } -char * fsl_db_g_text( fsl_db * const db, fsl_size_t * len, +char * fsl_db_g_text( fsl_db * db, fsl_size_t * len, char const * sql, ... ){ char * rv = NULL; va_list args; va_start(args,sql); @@ -16764,11 +16921,11 @@ fsl_db_get_textv(db, &rv, len, sql, args); va_end(args); return rv; } -void * fsl_db_g_blob( fsl_db * const db, fsl_size_t * len, +void * fsl_db_g_blob( fsl_db * db, fsl_size_t * len, char const * sql, ... ){ void * rv = NULL; va_list args; va_start(args,sql); @@ -16775,21 +16932,21 @@ fsl_db_get_blob(db, &rv, len, sql, args); va_end(args); return rv; } -double fsl_db_julian_now(fsl_db * const db){ +double fsl_db_julian_now(fsl_db * db){ double rc = -1.0; if(db && db->dbh){ /* TODO? use cached statement? So far not used often enough to justify it. */ fsl_db_get_double( db, &rc, "SELECT julianday('now')"); } return rc; } -double fsl_db_string_to_julian(fsl_db * const db, char const * str){ +double fsl_db_string_to_julian(fsl_db * db, char const * str){ double rc = -1.0; if(db && db->dbh){ /* TODO? use cached statement? So far not used often enough to justify it. */ fsl_db_get_double( db, &rc, "SELECT julianday(%Q)",str); @@ -16823,11 +16980,11 @@ bool fsl_db_table_exists(fsl_db * const db, fsl_dbrole_e whichDb, const char *zTable ){ - const char *zDb = fsl_db_role_name( whichDb ); + const char *zDb = fsl_db_role_label( whichDb ); int rc = db->dbh ? sqlite3_table_column_metadata(db->dbh, zDb, zTable, 0, 0, 0, 0, 0, 0) : !SQLITE_OK; return rc==SQLITE_OK ? true : false; @@ -16850,12 +17007,12 @@ } fsl_stmt_finalize(&q); return rv; } -char * fsl_db_random_hex(fsl_db * const db, fsl_size_t n){ - if(!db->dbh || !n) return NULL; +char * fsl_db_random_hex(fsl_db * db, fsl_size_t n){ + if(!db || !n) return NULL; else{ fsl_size_t rvLen = 0; char * rv = fsl_db_g_text(db, &rvLen, "SELECT lower(hex(" "randomblob(%"FSL_SIZE_T_PFMT")))", @@ -16867,14 +17024,13 @@ return rv; } } -int fsl_db_select_slistv( fsl_db * const db, fsl_list * const tgt, +int fsl_db_select_slistv( fsl_db * db, fsl_list * tgt, char const * fmt, va_list args ){ - if(!db->dbh) return fsl__db_err_not_opened(db); - else if(!fmt || !*fmt) return fsl__db_err_sql_empty(db); + if(!db || !tgt || !fmt) return FSL_RC_MISUSE; else if(!*fmt) return FSL_RC_RANGE; else{ int rc; fsl_stmt st = fsl_stmt_empty; fsl_size_t nlen; @@ -16894,11 +17050,11 @@ fsl_stmt_finalize(&st); return rc; } } -int fsl_db_select_slist( fsl_db * const db, fsl_list * const tgt, +int fsl_db_select_slist( fsl_db * const db, fsl_list * tgt, char const * fmt, ... ){ int rc; va_list va; va_start (va,fmt); rc = fsl_db_select_slistv(db, tgt, fmt, va); @@ -16905,13 +17061,12 @@ va_end(va); return rc; } void fsl_db_sqltrace_enable( fsl_db * const db, FILE * outStream ){ - if(db->dbh){ - sqlite3_trace_v2(db->dbh, SQLITE_TRACE_STMT, - fsl__db_sq3TraceV2, outStream); + if(db && db->dbh){ + sqlite3_trace(db->dbh, fsl_db_sql_trace, outStream); } } int fsl_db_init( fsl_error * err, char const * zFilename, @@ -16975,25 +17130,28 @@ return 0; } #undef MARKER -/* end of file ./src/db.c */ -/* start of file ./src/deck.c */ +/* end of file db.c */ +/* start of file deck.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* - Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt - - SPDX-License-Identifier: BSD-2-Clause-FreeBSD - SPDX-FileCopyrightText: 2021 The Libfossil Authors - SPDX-ArtifactOfProjectName: Libfossil - SPDX-FileType: Code - - Heavily indebted to the Fossil SCM project (https://fossil-scm.org). -*/ -/* + Copyright 2013-2021 Stephan Beal (https://wanderinghorse.net). + + + + This program is free software; you can redistribute it and/or + modify it under the terms of the Simplified BSD License (also + known as the "2-Clause License" or "FreeBSD License".) + + This program is distributed in the hope that it will be useful, + but without any warranty; without even the implied warranty of + merchantability or fitness for a particular purpose. + + ***************************************************************************** This file houses the manifest/control-artifact-related APIs. */ #include #include /* qsort() */ #include /* memcmp() */ @@ -17018,16 +17176,15 @@ /** Transfers the contents of d into f->cache.mcache. If d is dynamically allocated then it is also freed. In any case, after calling this the caller must behave as if the deck had been passed - to fsl_deck_finalize() and (if it is unknown whether d is stack - allocated) also freed. + to fsl_deck_finalize(). If manifest caching is disabled for f, d is immediately finalized. */ -static void fsl__cx_mcache_insert(fsl_cx * const f, fsl_deck * d){ +static void fsl__cx_mcache_insert(fsl_cx *f, fsl_deck * d){ if(!(f->flags & FSL_CX_F_MANIFEST_CACHE)){ fsl_deck_finalize(d); return; } static const unsigned cacheLen = @@ -17059,11 +17216,11 @@ if(&fsl_deck_empty == mc->decks[i].allocStamp){ /* d was fsl_deck_malloc()'d so we need to free it, but cannot send it through fsl_deck_finalize() because that would try to clean up the memory we just transferred ownership of to mc->decks[i]. So... */ - mc->decks[i].allocStamp = NULL; + mc->decks[i].allocStamp = 0; fsl_free(d); } d = pBaseline; } } @@ -17444,15 +17601,11 @@ } static void fsl_deck_clean_U(fsl_deck * const m){ fsl_deck_clean_string(m, &m->U); } static void fsl_deck_clean_W(fsl_deck * const m){ - if(m->W.capacity/*dynamically-allocated buffer*/){ - CBUF(W); - }else{/*empty or external buffer pointing into to m->content.mem*/ - m->W = fsl_buffer_empty; - } + CBUF(W); } void fsl_deck_clean2(fsl_deck * const m, fsl_buffer * const xferBuf){ if(!m) return; fsl_deck_clean_version(m); @@ -17747,11 +17900,11 @@ /** If fsl_card_is_legal(d->type, card), returns true, else updates d->f->error with a description of the constraint violation and returns 0. */ -static bool fsl_deck_check_type( fsl_deck * const d, char card ){ +static bool fsl_deck_check_type( fsl_deck * d, char card ){ if(fsl_card_is_legal(d->type, card)) return true; else{ fsl_cx_err_set(d->f, FSL_RC_TYPE, "Card type '%c' is not allowed " "in artifacts of type %s.", @@ -17890,11 +18043,11 @@ if(uuid && mf->H) return FSL_RC_SYNTAX; int const uLen = uuid ? fsl_is_uuid(uuid) : 0; return fsl_deck_sethex_impl(mf, uuid, 'I', uLen, &mf->I); } -int fsl_deck_J_add( fsl_deck * const mf, bool isAppend, +int fsl_deck_J_add( fsl_deck * const mf, char isAppend, char const * field, char const * value){ if(!field) return FSL_RC_MISUSE; else if(!*field) return FSL_RC_SYNTAX; else if(!fsl_deck_check_type(mf,'J')) return mf->f->error.code; else{ @@ -17908,22 +18061,14 @@ } } int fsl_deck_K_set( fsl_deck * const mf, fsl_uuid_cstr uuid){ - if(uuid){ - int const uLen = fsl_is_uuid(uuid); - return uLen - ? fsl_deck_sethex_impl(mf, uuid, 'K', uLen, &mf->K) - : FSL_RC_SYNTAX; - }else{ - char buf[FSL_STRLEN_SHA1+1]; - unsigned char rnd[FSL_STRLEN_SHA1/20]; - fsl_randomness(FSL_STRLEN_SHA1/2, rnd); - fsl_sha1_digest_to_base16(rnd, buf); - return fsl_deck_sethex_impl(mf, buf, 'K', FSL_STRLEN_SHA1, &mf->K); - } + int const uLen = fsl_is_uuid(uuid); + return uLen + ? fsl_deck_sethex_impl(mf, uuid, 'K', uLen, &mf->K) + : FSL_RC_SYNTAX; } int fsl_deck_L_set( fsl_deck * const mf, char const * v, fsl_int_t n){ return mf ? fsl_deck_set_string(mf, 'L', &mf->L, v, n) @@ -18087,11 +18232,11 @@ /* fall through and set hash */ }else{ int rc = 0; fsl_card_F const * fc; fsl_id_t fileRid; - fsl_buffer * const buf = &f->cache.fileContent; + fsl_buffer * const buf = &f->fileContent; unsigned char digest[16]; fsl_md5_cx md5 = fsl_md5_cx_empty; enum { NumBufSize = 40 }; char numBuf[NumBufSize] = {0}; assert(!buf->used && "Misuse of f->fileContent buffer."); @@ -18245,11 +18390,11 @@ if(z[len] <= 32) return false; } return len>0; } -int fsl_deck_branch_set( fsl_deck * const d, char const * branchName ){ +int fsl_deck_branch_set( fsl_deck * d, char const * branchName ){ if(!fsl_is_valid_branchname(branchName)){ return fsl_cx_err_set(d->f, FSL_RC_RANGE, "Branch name contains " "invalid characters."); } int rc= fsl_deck_T_add(d, FSL_TAGTYPE_PROPAGATING, NULL, @@ -18401,11 +18546,11 @@ } return rc; } } -int fsl_deck_F_foreach( fsl_deck * const d, fsl_card_F_visitor_f cb, void * const visitorState ){ +int fsl_deck_F_foreach( fsl_deck * d, fsl_card_F_visitor_f cb, void * visitorState ){ if(!cb) return FSL_RC_MISUSE; else{ fsl_card_F const * fc; int rc = fsl_deck_F_rewind(d); while( !rc && !(rc=fsl_deck_F_next(d, &fc)) && fc) { @@ -18500,11 +18645,11 @@ /** Internal helper for fsl_deck_output(). Appends formatted output to os->out() via fsl_output_f_mf(). Returns os->rc (0 on success). */ -static int fsl_deck_append( fsl_deck_out_state * const os, +static int fsl_deck_append( fsl_deck_out_state * os, char const * fmt, ... ){ fsl_int_t rc; va_list args; assert(os); assert(fmt && *fmt); @@ -18518,11 +18663,11 @@ /** Fossilizes (inp, inp+len] bytes to os->scratch, overwriting any existing contents. Updates and returns os->rc. */ -static int fsl_deck_fossilize( fsl_deck_out_state * const os, +static int fsl_deck_fossilize( fsl_deck_out_state * os, unsigned char const * inp, fsl_int_t len){ fsl_buffer_reuse(os->scratch); return os->rc = len ? fsl_bytes_fossilize(inp, len, os->scratch) @@ -18531,11 +18676,11 @@ /** Confirms that the given card letter is valid for od->d->type, and updates os->rc and os->error if it's not. Returns true if it's valid. */ -static bool fsl_deck_out_tcheck(fsl_deck_out_state * const os, char letter){ +static bool fsl_deck_out_tcheck(fsl_deck_out_state * os, char letter){ if(!fsl_card_is_legal(os->d->type, letter)){ os->rc = fsl_error_set(&os->error, FSL_RC_TYPE, "%c-card is not valid for deck type %s.", letter, fsl_satype_cstr(os->d->type)); } @@ -18542,11 +18687,11 @@ return os->rc ? false : true; } /* Appends a UUID-valued card to os from os->d->{{card}} if the given UUID is not NULL, else this is a no-op. */ -static int fsl_deck_out_uuid( fsl_deck_out_state * const os, char card, fsl_uuid_str uuid ){ +static int fsl_deck_out_uuid( fsl_deck_out_state * os, char card, fsl_uuid_str uuid ){ if(uuid && fsl_deck_out_tcheck(os, card)){ if(!fsl_is_uuid(uuid)){ os->rc = fsl_error_set(&os->error, FSL_RC_RANGE, "Malformed UUID in %c card.", card); }else{ @@ -18555,17 +18700,17 @@ } return os->rc; } /* Appends the B card to os from os->d->B. */ -static int fsl_deck_out_B( fsl_deck_out_state * const os ){ +static int fsl_deck_out_B( fsl_deck_out_state * os ){ return fsl_deck_out_uuid(os, 'B', os->d->B.uuid); } /* Appends the A card to os from os->d->A. */ -static int fsl_deck_out_A( fsl_deck_out_state * const os ){ +static int fsl_deck_out_A( fsl_deck_out_state * os ){ if(os->d->A.name && fsl_deck_out_tcheck(os, 'A')){ if(!os->d->A.name || !*os->d->A.name){ os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX, "A-card is missing its name property"); @@ -18597,11 +18742,11 @@ Internal helper for outputing cards which are simple strings. str is the card to output (NULL values are ignored), letter is the card letter being output. If doFossilize is true then the output gets fossilize-formatted. */ -static int fsl_deck_out_letter_str( fsl_deck_out_state * const os, char letter, +static int fsl_deck_out_letter_str( fsl_deck_out_state * os, char letter, char const * str, char doFossilize ){ if(str && fsl_deck_out_tcheck(os, letter)){ if(doFossilize){ fsl_deck_fossilize(os, (unsigned char const *)str, -1); if(!os->rc){ @@ -18613,17 +18758,17 @@ } return os->rc; } /* Appends the C card to os from os->d->C. */ -static int fsl_deck_out_C( fsl_deck_out_state * const os ){ +static int fsl_deck_out_C( fsl_deck_out_state * os ){ return fsl_deck_out_letter_str( os, 'C', os->d->C, 1 ); } /* Appends the D card to os from os->d->D. */ -static int fsl_deck_out_D( fsl_deck_out_state * const os ){ +static int fsl_deck_out_D( fsl_deck_out_state * os ){ if((os->d->D > 0.0) && fsl_deck_out_tcheck(os, 'D')){ char ds[24]; if(!fsl_julian_to_iso8601(os->d->D, ds, 1)){ os->rc = fsl_error_set(&os->error, FSL_RC_RANGE, "D-card contains invalid " @@ -18634,11 +18779,11 @@ } return os->rc; } /* Appends the E card to os from os->d->E. */ -static int fsl_deck_out_E( fsl_deck_out_state * const os ){ +static int fsl_deck_out_E( fsl_deck_out_state * os ){ if(os->d->E.uuid && fsl_deck_out_tcheck(os, 'E')){ char ds[24]; char msPrecision = FSL_SATYPE_EVENT!=os->d->type /* The timestamps on Events historically have seconds precision, not ms. @@ -18658,25 +18803,25 @@ } return os->rc; } /* Appends the G card to os from os->d->G. */ -static int fsl_deck_out_G( fsl_deck_out_state * const os ){ +static int fsl_deck_out_G( fsl_deck_out_state * os ){ return fsl_deck_out_uuid(os, 'G', os->d->G); } /* Appends the H card to os from os->d->H. */ -static int fsl_deck_out_H( fsl_deck_out_state * const os ){ +static int fsl_deck_out_H( fsl_deck_out_state * os ){ if(os->d->H && os->d->I){ return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX, "Forum post may not have both H- and I-cards."); } return fsl_deck_out_letter_str( os, 'H', os->d->H, 1 ); } /* Appends the I card to os from os->d->I. */ -static int fsl_deck_out_I( fsl_deck_out_state * const os ){ +static int fsl_deck_out_I( fsl_deck_out_state * os ){ if(os->d->I && os->d->H){ return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX, "Forum post may not have both H- and I-cards."); } return fsl_deck_out_uuid(os, 'I', os->d->I); @@ -18744,21 +18889,21 @@ } if(!rc) fsl_output_f_mf(os, "\n", 1); return os->rc; } -static int fsl_deck_out_list_obj( fsl_deck_out_state * const os, +static int fsl_deck_out_list_obj( fsl_deck_out_state * os, char letter, fsl_list const * li, fsl_list_visitor_f visitor){ if(li->used && fsl_deck_out_tcheck(os, letter)){ os->rc = fsl_list_visit( li, 0, visitor, os ); } return os->rc; } -static int fsl_deck_out_F( fsl_deck_out_state * const os ){ +static int fsl_deck_out_F( fsl_deck_out_state * os ){ if(os->d->F.used && fsl_deck_out_tcheck(os, 'F')){ uint32_t i; for(i=0; !os->rc && i d->F.used; ++i){ os->rc = fsl_deck_out_F_one(os, F_at(&os->d->F, i)); } @@ -18795,11 +18940,11 @@ /** fsl_list_visitor_f() impl for outputing J cards. obj must be a (fsl_card_J *). */ static int fsl_list_v_mf_output_card_J(void * obj, void * visitorState ){ - fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState; + fsl_deck_out_state * os = (fsl_deck_out_state *)visitorState; fsl_card_J const * c = (fsl_card_J const *)obj; fsl_deck_fossilize( os, (unsigned char const *)c->field, -1 ); if(!os->rc){ fsl_deck_append(os, "J %s%b", c->append ? "+" : "", os->scratch); if(!os->rc){ @@ -18814,17 +18959,17 @@ } } return os->rc; } -static int fsl_deck_out_J( fsl_deck_out_state * const os ){ +static int fsl_deck_out_J( fsl_deck_out_state * os ){ return fsl_deck_out_list_obj(os, 'J', &os->d->J, fsl_list_v_mf_output_card_J); } /* Appends the K card to os from os->d->K. */ -static int fsl_deck_out_K( fsl_deck_out_state * const os ){ +static int fsl_deck_out_K( fsl_deck_out_state * os ){ if(os->d->K && fsl_deck_out_tcheck(os, 'K')){ if(!fsl_is_uuid(os->d->K)){ os->rc = fsl_error_set(&os->error, FSL_RC_RANGE, "Invalid UUID in K card."); } @@ -18835,26 +18980,26 @@ return os->rc; } /* Appends the L card to os from os->d->L. */ -static int fsl_deck_out_L( fsl_deck_out_state * const os ){ +static int fsl_deck_out_L( fsl_deck_out_state * os ){ return fsl_deck_out_letter_str(os, 'L', os->d->L, 1); } /* Appends the N card to os from os->d->N. */ -static int fsl_deck_out_N( fsl_deck_out_state * const os ){ +static int fsl_deck_out_N( fsl_deck_out_state * os ){ return fsl_deck_out_letter_str( os, 'N', os->d->N, 1 ); } /** fsl_list_visitor_f() impl for outputing P cards. obj must be a (fsl_deck_out_state *) and obj->counter must be set to 0 before running the visit iteration. */ static int fsl_list_v_mf_output_card_P(void * obj, void * visitorState ){ - fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState; + fsl_deck_out_state * os = (fsl_deck_out_state *)visitorState; char const * uuid = (char const *)obj; int const uLen = uuid ? fsl_is_uuid(uuid) : 0; if(!uLen){ os->rc = fsl_error_set(&os->error, FSL_RC_RANGE, "Invalid UUID in P card."); @@ -18867,11 +19012,11 @@ } return os->rc; } -static int fsl_deck_out_P( fsl_deck_out_state * const os ){ +static int fsl_deck_out_P( fsl_deck_out_state * os ){ if(!fsl_deck_out_tcheck(os, 'P')) return os->rc; else if(os->d->P.used){ os->counter = 0; os->rc = fsl_list_visit( &os->d->P, 0, fsl_list_v_mf_output_card_P, os ); assert(os->counter); @@ -18911,11 +19056,12 @@ if(!l) return r ? 1 : 0; else if(!r) return -1; else{ /* Lexical sorting must account for the +/- characters, and a '+' sorts before '-', which is why this next part may seem - backwards at first. */ + backwards at first. + */ assert(l->type); assert(r->type); if(l->type<0 && r->type>0) return 1; else if(l->type>0 && r->type<0) return -1; else return fsl_strcmp(l->target, r->target); @@ -18925,11 +19071,11 @@ /** fsl_list_visitor_f() impl for outputing Q cards. obj must be a (fsl_deck_out_state *). */ static int fsl_list_v_mf_output_card_Q(void * obj, void * visitorState ){ - fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState; + fsl_deck_out_state * os = (fsl_deck_out_state *)visitorState; fsl_card_Q const * cp = (fsl_card_Q const *)obj; char const prefix = (cp->type==FSL_CHERRYPICK_ADD) ? '+' : '-'; assert(cp->type); assert(cp->target); @@ -18957,19 +19103,19 @@ fsl_deck_append(os, "Q %c%s\n", prefix, cp->target); } return os->rc; } -static int fsl_deck_out_Q( fsl_deck_out_state * const os ){ +static int fsl_deck_out_Q( fsl_deck_out_state * os ){ return fsl_deck_out_list_obj(os, 'Q', &os->d->Q, fsl_list_v_mf_output_card_Q); } /** Appends the R card from os->d->R to os. */ -static int fsl_deck_out_R( fsl_deck_out_state * const os ){ +static int fsl_deck_out_R( fsl_deck_out_state * os ){ if(os->d->R && fsl_deck_out_tcheck(os, 'R')){ if((FSL_STRLEN_MD5!=fsl_strlen(os->d->R)) || !fsl_validate16(os->d->R, FSL_STRLEN_MD5)){ os->rc = fsl_error_set(&os->error, FSL_RC_RANGE, "Malformed MD5 in R-card."); @@ -18984,11 +19130,11 @@ /** fsl_list_visitor_f() impl for outputing T cards. obj must be a (fsl_deck_out_state *). */ static int fsl_list_v_mf_output_card_T(void * obj, void * visitorState ){ - fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState; + fsl_deck_out_state * os = (fsl_deck_out_state *)visitorState; fsl_card_T * t = (fsl_card_T *)obj; char prefix = 0; switch(os->d->type){ case FSL_SATYPE_TECHNOTE: if( t->uuid ){ @@ -19186,25 +19332,25 @@ return rc; } } /* Appends the T cards to os from os->d->T. */ -static int fsl_deck_out_T( fsl_deck_out_state * const os ){ +static int fsl_deck_out_T( fsl_deck_out_state * os ){ os->rc = fsl_deck_T_verify_order( os->d, &os->error); return os->rc ? os->rc : fsl_deck_out_list_obj(os, 'T', &os->d->T, fsl_list_v_mf_output_card_T); } /* Appends the U card to os from os->d->U. */ -static int fsl_deck_out_U( fsl_deck_out_state * const os ){ +static int fsl_deck_out_U( fsl_deck_out_state * os ){ return fsl_deck_out_letter_str(os, 'U', os->d->U, 1); } /* Appends the W card to os from os->d->W. */ -static int fsl_deck_out_W( fsl_deck_out_state * const os ){ +static int fsl_deck_out_W( fsl_deck_out_state * os ){ if(os->d->W.used && fsl_deck_out_tcheck(os, 'W')){ fsl_deck_append(os, "W %"FSL_SIZE_T_PFMT"\n%b\n", (fsl_size_t)os->d->W.used, &os->d->W ); } @@ -19211,11 +19357,11 @@ return os->rc; } /* Appends the Z card to os from os' accummulated md5 hash. */ -static int fsl_deck_out_Z( fsl_deck_out_state * const os ){ +static int fsl_deck_out_Z( fsl_deck_out_state * os ){ unsigned char digest[16]; char md5[FSL_STRLEN_MD5+1]; fsl_md5_final(&os->md5, digest); fsl_md5_digest_to_base16(digest, md5); assert(!md5[32]); @@ -19228,16 +19374,16 @@ char const * r = *((char const **)rhs); return fsl_strcmp(l,r); } static int fsl_list_v_mf_output_card_M(void * obj, void * visitorState ){ - fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState; + fsl_deck_out_state * os = (fsl_deck_out_state *)visitorState; char const * m = (char const *)obj; return fsl_deck_append(os, "M %s\n", m); } -static int fsl_deck_output_cluster( fsl_deck_out_state * const os ){ +static int fsl_deck_output_cluster( fsl_deck_out_state * os ){ if(!os->d->M.used){ os->rc = fsl_error_set(&os->error, FSL_RC_RANGE, "M-card list may not be empty."); }else{ fsl_deck_out_list_obj(os, 'M', &os->d->M, @@ -19249,20 +19395,20 @@ /* Helper for fsl_deck_output_CATYPE() */ #define DOUT(LETTER) rc = fsl_deck_out_##LETTER(os); \ if(rc || os->rc) return os->rc ? os->rc : rc -static int fsl_deck_output_control( fsl_deck_out_state * const os ){ +static int fsl_deck_output_control( fsl_deck_out_state * os ){ int rc; /* Reminder: cards must be output in strict lexical order. */ DOUT(D); DOUT(T); DOUT(U); return os->rc; } -static int fsl_deck_output_event( fsl_deck_out_state * const os ){ +static int fsl_deck_output_event( fsl_deck_out_state * os ){ int rc = 0; /* Reminder: cards must be output in strict lexical order. */ DOUT(C); DOUT(D); DOUT(E); @@ -19272,11 +19418,11 @@ DOUT(U); DOUT(W); return os->rc; } -static int fsl_deck_output_mf( fsl_deck_out_state * const os ){ +static int fsl_deck_output_mf( fsl_deck_out_state * os ){ int rc = 0; /* Reminder: cards must be output in strict lexical order. */ DOUT(B); DOUT(C); DOUT(D); @@ -19292,21 +19438,21 @@ DOUT(W); return os->rc; } -static int fsl_deck_output_ticket( fsl_deck_out_state * const os ){ +static int fsl_deck_output_ticket( fsl_deck_out_state * os ){ int rc; /* Reminder: cards must be output in strict lexical order. */ DOUT(D); DOUT(J); DOUT(K); DOUT(U); return os->rc; } -static int fsl_deck_output_wiki( fsl_deck_out_state * const os ){ +static int fsl_deck_output_wiki( fsl_deck_out_state * os ){ int rc; /* Reminder: cards must be output in strict lexical order. */ DOUT(C); DOUT(D); DOUT(L); @@ -19315,11 +19461,11 @@ DOUT(U); DOUT(W); return os->rc; } -static int fsl_deck_output_attachment( fsl_deck_out_state * const os ){ +static int fsl_deck_output_attachment( fsl_deck_out_state * os ){ int rc = 0; /* Reminder: cards must be output in strict lexical order. */ DOUT(A); DOUT(C); DOUT(D); @@ -19326,11 +19472,11 @@ DOUT(N); DOUT(U); return os->rc; } -static int fsl_deck_output_forumpost( fsl_deck_out_state * const os ){ +static int fsl_deck_output_forumpost( fsl_deck_out_state * os ){ int rc; /* Reminder: cards must be output in strict lexical order. */ DOUT(D); DOUT(G); DOUT(H); @@ -19345,11 +19491,11 @@ /** Only for testing/debugging purposes, as it allows constructs which are not semantically legal and are CERTAINLY not legal to stuff in the database. */ -static int fsl_deck_output_any( fsl_deck_out_state * const os ){ +static int fsl_deck_output_any( fsl_deck_out_state * os ){ int rc = 0; /* Reminder: cards must be output in strict lexical order. */ DOUT(B); DOUT(C); DOUT(D); @@ -19369,11 +19515,11 @@ } #undef DOUT -int fsl_deck_unshuffle( fsl_deck * const d, bool calculateRCard ){ +int fsl_deck_unshuffle( fsl_deck * d, bool calculateRCard ){ fsl_list * li; int rc = 0; if(!d || !d->f) return FSL_RC_MISUSE; fsl_cx_err_reset(d->f); #define SORT(CARD,CMP) li = &d->CARD; fsl_list_sort(li, CMP) @@ -19411,12 +19557,11 @@ } } return rc; } -int fsl_deck_output( fsl_deck * const d, fsl_output_f out, - void * outputState ){ +int fsl_deck_output( fsl_deck * d, fsl_output_f out, void * outputState ){ static const bool allowTypeAny = false /* Only enable for debugging/testing. Allows outputing decks of type FSL_SATYPE_ANY, which bypasses some validation checks and may trigger other validation assertions. And may allow you to inject garbage into the repo. So be careful. @@ -19424,14 +19569,10 @@ fsl_deck_out_state OS = fsl_deck_out_state_empty; fsl_deck_out_state * const os = &OS; fsl_cx * const f = d->f; int rc = 0; - if(NULL==out && NULL==outputState && f){ - out = f->output.out; - outputState = f->output.state; - } if(!f || !out) return FSL_RC_MISUSE; else if(FSL_SATYPE_ANY==d->type){ if(!allowTypeAny){ return fsl_cx_err_set(d->f, FSL_RC_TYPE, "Artifact type ANY cannot be" @@ -19518,15 +19659,18 @@ Adds a record in the pending_xlink temp table, to be processed when crosslinking is completed. Returns 0 on success, non-0 for db error. */ static int fsl__deck_crosslink_add_pending(fsl_cx * f, char cType, fsl_uuid_cstr uuid){ + int rc = 0; assert(f->cache.isCrosslinking); - return fsl_cx_exec(f, + rc = fsl_db_exec(f->dbMain, "INSERT OR IGNORE INTO pending_xlink VALUES('%c%q')", cType, uuid); + return fsl_cx_uplift_db_error2(f, 0, rc); } + /** @internal Add a single entry to the mlink table. Also add the filename to the filename table if it is not there already. @@ -19832,31 +19976,26 @@ }else{ return fsl_deck_F_add(d, zName, uuid, perms, priorName); } } -int fsl_deck_F_set_content( fsl_deck * const d, char const * zName, - fsl_buffer const * const src, +int fsl_deck_F_set_content( fsl_deck * d, char const * zName, + fsl_buffer const * src, fsl_fileperm_e perm, char const * priorName){ fsl_uuid_str zHash = 0; fsl_id_t rid = 0; fsl_id_t prevRid = 0; int rc = 0; - assert(d->f); if(d->rid>0){ return fsl_cx_err_set(d->f, FSL_RC_MISUSE, "%s() cannot be applied to a saved deck.", __func__); }else if(!fsl_cx_transaction_level(d->f)){ return fsl_cx_err_set(d->f, FSL_RC_MISUSE, "%s() requires that a transaction is active.", __func__); - }else if(!fsl_is_simple_pathname(zName, true)){ - return fsl_cx_err_set(d->f, FSL_RC_RANGE, - "Filename is not valid for use as a repository " - "entry: %s", zName); } rc = fsl_repo_blob_lookup(d->f, src, &rid, &zHash); if(rc && FSL_RC_NOT_FOUND!=rc) goto end; assert(zHash); if(!rid){ @@ -20590,39 +20729,21 @@ rc = fsl__tag_propagate_all(d->f, parentId); } return rc; } -int fsl__call_xlink_listeners(fsl_deck * const d){ - int rc = 0; - fsl_xlinker * xl = NULL; - fsl_cx_err_reset(d->f); - for( fsl_size_t i = 0; !rc && (i < d->f->xlinkers.used); ++i ){ - xl = d->f->xlinkers.list+i; - rc = xl->f( d, xl->state ); - } - if(rc && !d->f->error.code){ - assert(xl); - rc = fsl_cx_err_set(d->f, rc, "Crosslink callback handler " - "'%s' failed with code %d (%s) for " - "artifact RID #%" FSL_ID_T_PFMT ".", - xl->name, rc, fsl_rc_cstr(rc), - d->rid); - } - return rc; -} /** Overrideable crosslink listener which updates the timeline for attachment records. */ static int fsl_deck_xlink_f_attachment(fsl_deck * const d, void * state){ if(FSL_SATYPE_ATTACHMENT!=d->type) return 0; int rc; fsl_db * const db = fsl_cx_db_repo(d->f); - fsl_buffer * const comment = fsl__cx_scratchpad(d->f); - const bool isAdd = (d->A.src && *d->A.src) ? 1 : 0; + fsl_buffer comment = fsl_buffer_empty; + const char isAdd = (d->A.src && *d->A.src) ? 1 : 0; char attachToType = 'w' /* Assume wiki until we know otherwise, keeping in mind that the d->A.tgt might not yet be in the blob table, in which case we are unable to know, for certain, what the target is. That only affects the timeline (event table), though, not @@ -20638,42 +20759,42 @@ } } if('w'==attachToType){ /* Attachment applies to a wiki page */ if(isAdd){ - rc = fsl_buffer_appendf(comment, + rc = fsl_buffer_appendf(&comment, "Add attachment \"%h\" " "to wiki page [%h]", d->A.name, d->A.tgt); }else{ - rc = fsl_buffer_appendf(comment, + rc = fsl_buffer_appendf(&comment, "Delete attachment \"%h\" " "from wiki page [%h]", d->A.name, d->A.tgt); } }else if('e' == attachToType){/*technote*/ if(isAdd){ - rc = fsl_buffer_appendf(comment, + rc = fsl_buffer_appendf(&comment, "Add attachment [/artifact/%!S|%h] to " "tech note [/technote/%!S|%S]", d->A.src, d->A.name, d->A.tgt, d->A.tgt); }else{ - rc = fsl_buffer_appendf(comment, + rc = fsl_buffer_appendf(&comment, "Delete attachment \"/artifact/%!S|%h\" " "from tech note [/technote/%!S|%S]", d->A.name, d->A.name, d->A.tgt, d->A.tgt); } }else{ /* Attachment applies to a ticket */ if(isAdd){ - rc = fsl_buffer_appendf(comment, + rc = fsl_buffer_appendf(&comment, "Add attachment [/artifact/%!S|%h] " "to ticket [%!S|%S]", d->A.src, d->A.name, d->A.tgt, d->A.tgt); }else{ - rc = fsl_buffer_appendf(comment, + rc = fsl_buffer_appendf(&comment, "Delete attachment \"%h\" " "from ticket [%!S|%S]", d->A.name, d->A.tgt, d->A.tgt); } } @@ -20681,13 +20802,13 @@ rc = fsl_db_exec(db, "REPLACE INTO event(type,mtime,objid,user,comment)" "VALUES(" "'%c',%"FSL_JULIAN_T_PFMT",%"FSL_ID_T_PFMT"," "%Q,%B)", - attachToType, d->D, d->rid, d->U, comment); + attachToType, d->D, d->rid, d->U, &comment); } - fsl__cx_scratchpad_yield(d->f, comment); + fsl_buffer_clear(&comment); return rc; } /** Overrideable crosslink listener which updates the timeline for @@ -20750,11 +20871,11 @@ fossil(1). i would prefer to farm this out to a crosslink callback, and provide a default implementation which more or less mimics fossil(1). */ int rc = 0; - fsl_buffer * const comment = fsl__cx_scratchpad(d->f); + fsl_buffer comment = fsl_buffer_empty; fsl_size_t i; const char *zName; const char *zValue; const char *zUuid; int branchMove = 0; @@ -20787,16 +20908,16 @@ output of grouping tags by the UUID they tag. So far (201404) such groups of tags have not appeared in the wild because fossil(1) has no mechanism for creating them. */ for( i = 0; !rc && (i < li->used); ++i, prevTag = tag){ - bool isProp = 0, isAdd = 0, isCancel = 0; + char isProp = 0, isAdd = 0, isCancel = 0; tag = (fsl_card_T const *)li->list[i]; zUuid = tag->uuid; if(!zUuid /*tag on self*/) continue; if( i==0 || 0!=fsl_uuidcmp(tag->uuid, prevTag->uuid)){ - rc = fsl_buffer_appendf(comment, + rc = fsl_buffer_appendf(&comment, " Edit [%.*s]:", uuidLen, zUuid); branchMove = 0; } if(rc) goto end; isProp = FSL_TAGTYPE_PROPAGATING==tag->type; @@ -20804,67 +20925,67 @@ isCancel = FSL_TAGTYPE_CANCEL==tag->type; assert(isProp || isAdd || isCancel); zName = tag->name; zValue = tag->value; if( isProp && 0==fsl_strcmp(zName, "branch")){ - rc = fsl_buffer_appendf(comment, + rc = fsl_buffer_appendf(&comment, " Move to branch %s" "[/timeline?r=%h&nd&dp=%.*s | %h].", zValue, zValue, uuidLen, zUuid, zValue); branchMove = 1; }else if( isProp && fsl_strcmp(zName, "bgcolor")==0 ){ - rc = fsl_buffer_appendf(comment, + rc = fsl_buffer_appendf(&comment, " Change branch background color to \"%h\".", zValue); }else if( isAdd && fsl_strcmp(zName, "bgcolor")==0 ){ - rc = fsl_buffer_appendf(comment, + rc = fsl_buffer_appendf(&comment, " Change background color to \"%h\".", zValue); }else if( isCancel && fsl_strcmp(zName, "bgcolor")==0 ){ - rc = fsl_buffer_appendf(comment, " Cancel background color."); + rc = fsl_buffer_appendf(&comment, " Cancel background color."); }else if( isAdd && fsl_strcmp(zName, "comment")==0 ){ - rc = fsl_buffer_appendf(comment, " Edit check-in comment."); + rc = fsl_buffer_appendf(&comment, " Edit check-in comment."); }else if( isAdd && fsl_strcmp(zName, "user")==0 ){ - rc = fsl_buffer_appendf(comment, " Change user to \"%h\".", zValue); + rc = fsl_buffer_appendf(&comment, " Change user to \"%h\".", zValue); }else if( isAdd && fsl_strcmp(zName, "date")==0 ){ - rc = fsl_buffer_appendf(comment, " Timestamp %h.", zValue); + rc = fsl_buffer_appendf(&comment, " Timestamp %h.", zValue); }else if( isCancel && memcmp(zName, "sym-",4)==0 ){ if( !branchMove ){ - rc = fsl_buffer_appendf(comment, " Cancel tag %h.", zName+4); + rc = fsl_buffer_appendf(&comment, " Cancel tag %h.", zName+4); } }else if( isProp && memcmp(zName, "sym-",4)==0 ){ if( !branchMove ){ - rc = fsl_buffer_appendf(comment, " Add propagating tag \"%h\".", zName+4); + rc = fsl_buffer_appendf(&comment, " Add propagating tag \"%h\".", zName+4); } }else if( isAdd && memcmp(zName, "sym-",4)==0 ){ - rc = fsl_buffer_appendf(comment, " Add tag \"%h\".", zName+4); + rc = fsl_buffer_appendf(&comment, " Add tag \"%h\".", zName+4); }else if( isCancel && memcmp(zName, "sym-",4)==0 ){ - rc = fsl_buffer_appendf(comment, " Cancel tag \"%h\".", zName+4); + rc = fsl_buffer_appendf(&comment, " Cancel tag \"%h\".", zName+4); }else if( isAdd && fsl_strcmp(zName, "closed")==0 ){ - rc = fsl_buffer_append(comment, " Marked \"Closed\"", -1); + rc = fsl_buffer_append(&comment, " Marked \"Closed\"", -1); if( !rc && zValue && *zValue ){ - rc = fsl_buffer_appendf(comment, " with note \"%h\"", zValue); + rc = fsl_buffer_appendf(&comment, " with note \"%h\"", zValue); } - if(!rc) rc = fsl_buffer_append(comment, ".", 1); + if(!rc) rc = fsl_buffer_append(&comment, ".", 1); }else if( isCancel && fsl_strcmp(zName, "closed")==0 ){ - rc = fsl_buffer_append(comment, " Removed the \"Closed\" mark", -1); + rc = fsl_buffer_append(&comment, " Removed the \"Closed\" mark", -1); if( !rc && zValue && *zValue ){ - rc = fsl_buffer_appendf(comment, " with note \"%h\"", zValue); + rc = fsl_buffer_appendf(&comment, " with note \"%h\"", zValue); } - if(!rc) rc = fsl_buffer_append(comment, ".", 1); + if(!rc) rc = fsl_buffer_append(&comment, ".", 1); }else { if( isCancel ){ - rc = fsl_buffer_appendf(comment, " Cancel \"%h\"", zName); + rc = fsl_buffer_appendf(&comment, " Cancel \"%h\"", zName); }else if( isAdd ){ - rc = fsl_buffer_appendf(comment, " Add \"%h\"", zName); + rc = fsl_buffer_appendf(&comment, " Add \"%h\"", zName); }else{ assert(isProp); - rc = fsl_buffer_appendf(comment, " Add propagating \"%h\"", zName); + rc = fsl_buffer_appendf(&comment, " Add propagating \"%h\"", zName); } if(rc) goto end; if( zValue && zValue[0] ){ - rc = fsl_buffer_appendf(comment, " with value \"%h\".", zValue); + rc = fsl_buffer_appendf(&comment, " with value \"%h\".", zValue); }else{ - rc = fsl_buffer_append(comment, ".", 1); + rc = fsl_buffer_append(&comment, ".", 1); } } } /* foreach tag loop */ if(!rc){ /* TODO: cached statement */ @@ -20874,18 +20995,18 @@ "VALUES('g'," "%"FSL_JULIAN_T_PFMT"," "%"FSL_ID_T_PFMT"," "%Q,%Q)", mtime, d->rid, d->U, - (comment->used>1) - ? (fsl_buffer_cstr(comment) + (comment.used>1) + ? (fsl_buffer_cstr(&comment) +1/*leading space on all entries*/) : NULL); } end: - fsl__cx_scratchpad_yield(d->f, comment); + fsl_buffer_clear(&comment); return rc; } static int fsl_deck_xlink_f_forum(fsl_deck * const d, void * state){ @@ -21079,11 +21200,11 @@ in the internal fsl__deck_crosslink_XXX() functions. That should allow clients to override how the timeline is updated without requiring them to understand the rest of the required schema updates. */ -int fsl__cx_install_timeline_crosslinkers(fsl_cx * const f){ +int fsl_cx_install_timeline_crosslinkers(fsl_cx * const f){ int rc; assert(!f->xlinkers.used); assert(!f->xlinkers.list); rc = fsl_xlink_listener(f, "fsl/attachment/timeline", fsl_deck_xlink_f_attachment, 0); @@ -21381,56 +21502,29 @@ } static int fsl__deck_crosslink_ticket(fsl_deck * const d){ int rc; fsl_cx * const f = d->f; - char * zTag; - fsl_stmt qAtt = fsl_stmt_empty; - assert(f->cache.isCrosslinking - && "This only works if fsl__crosslink_begin() is active."); - zTag = fsl_mprintf("tkt-%s", d->K); - if(!zTag) return FSL_RC_OOM; - rc = fsl__tag_insert(f, FSL_TAGTYPE_ADD, zTag, NULL, - d->rid, d->D, d->rid, NULL); - fsl_free(zTag); - if(rc) goto end; - assert(d->K); - rc = fsl__deck_crosslink_add_pending(f, 't', d->K); - if(rc) goto end;; - /* Locate and update comment for any attachments */ - rc = fsl_cx_prepare(f, &qAtt, - "SELECT attachid, src, target, filename FROM attachment" - " WHERE target=%Q", - d->K); - while(0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&qAtt)){ - const char *zAttachId = fsl_stmt_g_text(&qAtt, 0, NULL); - const char *zSrc = fsl_stmt_g_text(&qAtt, 1, NULL); - const char *zTarget = fsl_stmt_g_text(&qAtt, 2, NULL); - const char *zName = fsl_stmt_g_text(&qAtt, 3, NULL); - const bool isAdd = (zSrc && zSrc[0]) ? true : false; - char *zComment; - if( isAdd ){ - zComment = - fsl_mprintf( - "Add attachment [/artifact/%!S|%h] to ticket [%!S|%S]", - zSrc, zName, zTarget, zTarget); - }else{ - zComment = - fsl_mprintf("Delete attachment \"%h\" from ticket [%!S|%S]", - zName, zTarget, zTarget); - } - if(!zComment){ - rc = FSL_RC_OOM; - break; - } - rc = fsl_cx_exec_multi(f, "UPDATE event SET comment=%Q, type='t'" - " WHERE objid=%Q", - zComment, zAttachId); - fsl_free(zComment); - } - end: - fsl_stmt_finalize(&qAtt); +#if 0 + fsl_db * const db = fsl_cx_db_repo(f); +#endif + /* + TODO: huge block from manifest_crosslink(). A full port + requires other infrastructure for collapsing relatively close + time values into the same time for timeline purposes. i'd prefer + to farm this out to a crosslink callback. Even then, the future + of tickets in libfossil is uncertain, but we should crosslink + them so that repos stay compatible with fossil(1) without + requiring a rebuild using fossil(1). + */ + if(f->flags & FSL_CX_F_SKIP_UNKNOWN_CROSSLINKS){ + return 0; + } + rc = fsl_cx_err_set(f, FSL_RC_NYI, + "MISSING: a huge block of TICKET stuff from " + "manifest_crosslink(). It requires infrastructure " + "libfossil does not yet have."); return rc; } int fsl__deck_crosslink_one( fsl_deck * const d ){ int rc; @@ -21514,28 +21608,47 @@ /* FSL_SATYPE_CONTROL is handled above except for the timeline update, which is handled by a callback below */ default: break; } + if(rc) goto end; + /* Call any crosslink callbacks... */ - if(0==rc && FSL_SATYPE_TICKET!=d->type){ - /* ^^^ the real work of ticket crosslinking is delated until - fsl__crosslink_end(), for reasons lost to history, so we'll skip - calling the xlink listeners for those until that step. */ - rc = fsl__call_xlink_listeners(d); - } + if(f->xlinkers.list){ + fsl_size_t i; + fsl_xlinker * xl = NULL; + for( i = 0; !rc && (i < f->xlinkers.used); ++i ){ + xl = f->xlinkers.list+i; + rc = xl->f( d, xl->state ); + } + if(rc){ + assert(xl); + if(!f->error.code){ + if(f->dbMain->error.code){ + fsl_cx_uplift_db_error(f, f->dbMain); + }else{ + fsl_cx_err_set(f, rc, "Crosslink callback handler " + "'%s' failed with code %d (%s) for " + "artifact RID #%" FSL_ID_T_PFMT ".", + xl->name, rc, fsl_rc_cstr(rc), + d->rid); + } + } + } + }/*end crosslink callbacks*/ end: if(!rc){ rc = fsl_db_transaction_end(db, false); }else{ if(db->error.code && !f->error.code){ fsl_cx_uplift_db_error(f,db); } fsl_db_transaction_end(db, true); } - return rc ? rc : f->interrupted; + return rc; }/*end fsl__deck_crosslink()*/ + /** Return true if z points to the first character after a blank line. Tolerate either \r\n or \n line endings. As this looks backwards @@ -21634,13 +21747,13 @@ } /** Internal helper for parsing manifests. Holds a source file (memory - range) and gets updated by fsl__deck_next_token() and friends. + range) and gets updated by fsl_deck_next_token() and friends. */ -struct fsl__src { +struct fsl_src { /** First char of the next token. */ unsigned char * z; /** @@ -21648,51 +21761,49 @@ */ unsigned char * zEnd; /** True if z points to the start of a new line. */ - bool atEol; + char atEol; }; -typedef struct fsl__src fsl__src; -static const fsl__src fsl__src_empty = {NULL,NULL,0}; +typedef struct fsl_src fsl_src; +static const fsl_src fsl_src_empty = {NULL,NULL,0}; /** Return a pointer to the next token. The token is zero-terminated. - Return NULL if there are no more tokens on the current line, but - the call after that will return non-NULL unless we have reached the - end of the input. If this function returns non-NULL then *pLen is - set to the byte length of the new token. Once the end of the input - is reached, this function always returns NULL. + Return NULL if there are no more tokens on the current line. If + pLen is not NULL and this function returns non-NULL then *pLen is + set to the byte length of the new token. */ -static unsigned char *fsl__deck_next_token(fsl__src * const p, - fsl_size_t * const pLen){ +static unsigned char *fsl_deck_next_token(fsl_src *p, fsl_size_t *pLen){ + unsigned char *z; + unsigned char *zStart; + int c; if( p->atEol ) return NULL; - int c; - unsigned char * z = p->z; - unsigned char * const zStart = z; - while( (c=(*z))!=' ' && c!='\n' ) ++z; + zStart = z = p->z; + while( (c=(*z))!=' ' && c!='\n' ){ ++z; } *z = 0; p->z = &z[1]; p->atEol = c=='\n'; - *pLen = z - zStart; + if( pLen ) *pLen = z - zStart; return zStart; } /** Return the card-type for the next card. Return 0 if there are no more cards or if we are not at the end of the current card. */ -static unsigned char deck__next_card(fsl__src * const p){ +static unsigned char mf_next_card(fsl_src *p){ unsigned char c; if( !p->atEol || p->z>=p->zEnd ) return 0; c = p->z[0]; if( p->z[1]==' ' ){ p->z += 2; - p->atEol = false; + p->atEol = 0; }else if( p->z[1]=='\n' ){ p->z += 2; - p->atEol = true; + p->atEol = 1; }else{ c = 0; } return c; } @@ -21769,22 +21880,23 @@ #endif #define ERROR(RC,MSG) do{ rc = (RC); zMsg = (MSG); goto bailout; } while(0) #define SYNTAX(MSG) ERROR(rc ? rc : FSL_RC_SYNTAX,MSG) bool isRepeat = 0/* , hasSelfRefTag = 0 */; int rc = 0; - fsl__src x = fsl__src_empty; + fsl_src x = fsl_src_empty; char const * zMsg = NULL; + fsl_id_bag * seen; char cType = 0, cPrevType = 0; unsigned char * z = src ? src->mem : NULL; fsl_size_t tokLen = 0; unsigned char * token; fsl_size_t n = z ? src->used : 0; unsigned char * uuid; double ts; int cardCount = 0; - fsl_cx * const f = d->f; - fsl_error * const err = f ? &f->error : 0; + fsl_cx * f; + fsl_error * err; int stealBuf = 0 /* gets incremented if we need to steal src->mem. */; unsigned nSelfTag = 0 /* number of T cards which refer to '*' (this artifact). */; unsigned nSimpleTag = 0 /* number of T cards with "+" prefix */; /* lettersSeen keeps track of the card letters we have seen so that @@ -21794,51 +21906,61 @@ */ int lettersSeen[27] = {0/*A*/,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0/*Z*/, 0 /* sentinel element for reasons lost to history but removing it breaks stuff. */}; - if(!f || !z) return FSL_RC_MISUSE; - if(rid>0 && (fsl__cx_mcache_search2(f, rid, d, FSL_SATYPE_ANY, &rc) - || rc)){ - if(0==rc){ - assert(d->rid == rid); - fsl_buffer_clear(src); - } - return rc; - }else if(rid<0){ - return fsl_error_set(err, FSL_RC_RANGE, - "Invalid (negative) RID %" FSL_ID_T_PFMT - " for %s()", rid, __func__); - }else if(!*z || !n || ( '\n' != z[n-1]) ){ - /* Every control artifact ends with a '\n' character. Exit early - if that is not the case for this artifact. */ + if(!d->f || !z) return FSL_RC_MISUSE; + /* Every control artifact ends with a '\n' character. Exit early + if that is not the case for this artifact. */ + f = d->f; + + if(rid>0){ + d->rid = rid; +#if 1 + if(fsl__cx_mcache_search2(f, rid, d, FSL_SATYPE_ANY, &rc) || rc){ + if(0==rc){ + assert(d->rid == rid); + fsl_buffer_clear(src); + } + return rc; + } +#endif + } + + err = &f->error; + if(!*z || !n || ( '\n' != z[n-1]) ){ return fsl_error_set(err, FSL_RC_SYNTAX, "%s.", n ? "Not terminated with \\n" : "Zero-length input"); } - if((0==rid) || fsl_id_bag_contains(&f->cache.mfSeen,rid)){ + else if(rid<0){ + return fsl_error_set(err, FSL_RC_RANGE, + "Invalid (negative) RID %"FSL_ID_T_PFMT + " for fsl_deck_parse()", rid); + } + seen = &f->cache.mfSeen; + if((0==rid) || fsl_id_bag_contains(seen,rid)){ isRepeat = 1; }else{ isRepeat = 0; - rc = fsl_id_bag_insert(&f->cache.mfSeen, rid); + rc = fsl_id_bag_insert(seen, rid); if(rc){ assert(FSL_RC_OOM==rc); return rc; } } + fsl_deck_clean(d); + fsl_deck_init(f, d, FSL_SATYPE_ANY); /* Verify that the first few characters of the artifact look like a control artifact. */ if( !fsl_might_be_artifact(src) ){ SYNTAX("Content does not look like a structural artifact"); } - fsl_deck_clean(d); - fsl_deck_init(f, d, FSL_SATYPE_ANY); - /* Strip off the PGP signature if there is one. Example of signed manifest: https://fossil-scm.org/index.html/artifact/28987096ac @@ -21860,19 +21982,19 @@ /* Reminder: parsing modifies the input (to simplify the tokenization/parsing). As of mid-201403, we recycle as much as possible from the source - buffer. + buffer and take over ownership _if_ we do so. */ /* Now parse, card by card... */ x.z = z; x.zEnd = z+n; - x.atEol= true; + x.atEol= 1; /* Parsing helpers... */ -#define TOKEN(DEFOS) tokLen=0; token = fsl__deck_next_token(&x,&tokLen); \ +#define TOKEN(DEFOS) tokLen=0; token = fsl_deck_next_token(&x,&tokLen); \ if(token && tokLen && (DEFOS)) fsl_bytes_defossilize(token, &tokLen) #define TOKEN_EXISTS(MSG_IF_NOT) if(!token){ SYNTAX(MSG_IF_NOT); }(void)0 #define TOKEN_CHECKHEX(MSG) if(token && (int)tokLen!=fsl_is_uuid((char const *)token))\ { SYNTAX(MSG); } #define TOKEN_UUID(CARD) TOKEN_CHECKHEX("Malformed UUID in " #CARD "-card") @@ -21887,11 +22009,11 @@ and do a post-parse check for the legality of cards added before validation became possible. */ #define SEEN(CARD) lettersSeen[*#CARD - 'A'] - for( cPrevType=1; !rc && (0 < (cType = deck__next_card(&x))); + for( cPrevType=1; !rc && (0 < (cType = mf_next_card(&x))); cPrevType = cType ){ ++cardCount; if(cTypeE.uuid && 'N'==cType && 'P'==cPrevType){ /* Workaround for a pair of historical fossil bugs @@ -21909,11 +22031,11 @@ SYNTAX("Invalid card name"); } switch(cType){ /* A ?? - + Identifies an attachment to either a wiki page, a ticket, or a technote. is the artifact that is the attachment. is omitted to delete an attachment. is the name of a wiki page, technote, or ticket to which that attachment is connected. @@ -21944,11 +22066,11 @@ d->type = FSL_SATYPE_ATTACHMENT; break; } /* B - + A B-line gives the UUID for the baseline of a delta-manifest. */ case 'B':{ if(d->B.uuid){ SYNTAX("Multiple B-cards"); @@ -21961,11 +22083,11 @@ /* rc = fsl_deck_B_set(d, (char const *)token); */ break; } /* C - + Comment text is fossil-encoded. There may be no more than one C line. C lines are required for manifests, are optional for Events and Attachments, and are disallowed on all other control files. */ @@ -21980,11 +22102,11 @@ ++stealBuf; break; } /* D - + The timestamp should be ISO 8601. YYYY-MM-DDtHH:MM:SS There can be no more than 1 D line. D lines are required for all control files except for clusters. */ case 'D':{ @@ -22003,17 +22125,16 @@ rc = fsl_deck_D_set(d, ts); break; } /* E - - An "event" (technote) card that contains the timestamp of the - event in the format YYYY-MM-DDtHH:MM:SS and a unique - identifier for the event. The event timestamp is distinct - from the D timestamp. The D timestamp is when the artifact - was created whereas the E timestamp is when the specific - event is said to occur. + + An "event" card that contains the timestamp of the event in the + format YYYY-MM-DDtHH:MM:SS and a unique identifier for the event. + The event timestamp is distinct from the D timestamp. The D + timestamp is when the artifact was created whereas the E timestamp + is when the specific event is said to occur. */ case 'E':{ TOKEN_DATETIME(E,E.julian); TOKEN(0); TOKEN_EXISTS("Missing UUID part of E-card"); @@ -22024,11 +22145,11 @@ d->type = FSL_SATYPE_EVENT; break; } /* F ?? ?? ?? - + Identifies a file in a manifest. Multiple F lines are allowed in a manifest. F lines are not allowed in any other control file. The filename and old-name are fossil-encoded. In delta manifests, deleted files are denoted by the 1-arg @@ -22039,18 +22160,17 @@ char * name; char * perms = NULL; char * priorName = NULL; fsl_fileperm_e perm = FSL_FILE_PERM_REGULAR; fsl_card_F * fc = NULL; + /** + Basic tests with various repos have shown that the + approximate number of F-cards in a manifest is rougly the + manifest size/75. We'll use that as an initial alloc size. + */ rc = 0; if(!d->F.capacity){ - /** - Basic tests with various repos have shown that the - approximate number of F-cards in a manifest is roughly - the manifest size/75. We'll use that as an initial alloc - size. - */ rc = fsl_card_F_list_reserve(&d->F, src->used/75+10); } TOKEN(0); TOKEN_EXISTS("Missing name for F-card"); name = (char *)token; @@ -22077,18 +22197,18 @@ } TOKEN(0); if(token) priorName = (char *)token; } fsl_bytes_defossilize( (unsigned char *)name, 0 ); + if(priorName) fsl_bytes_defossilize( (unsigned char *)priorName, 0 ); if(fsl_is_reserved_fn(name, -1)){ /* Some historical (pre-late-2020) manifests contain files they really shouldn't, like _FOSSIL_ and .fslckout. Since late 2020, fossil simply skips over these when parsing manifests, so we'll do the same. */ break; } - if(priorName) fsl_bytes_defossilize( (unsigned char *)priorName, 0 ); fc = rc ? 0 : fsl_card_F_list_push(&d->F); if(!fc){ zMsg = "OOM"; goto bailout; } @@ -22104,11 +22224,11 @@ d->type = FSL_SATYPE_CHECKIN; break; } /* G - + A G-line gives the UUID for the thread root of a forum post. */ case 'G':{ if(d->G){ SYNTAX("Multiple G-cards"); @@ -22121,11 +22241,11 @@ d->type = FSL_SATYPE_FORUMPOST; break; } /* H - + H text is fossil-encoded. There may be no more than one H line. H lines are optional for forum posts and are disallowed on all other control files. */ case 'H':{ @@ -22139,11 +22259,11 @@ d->type = FSL_SATYPE_FORUMPOST; break; } /* I - + A I-line gives the UUID for the in-response-to UUID for a forum post. */ case 'I':{ if(d->I){ @@ -22156,12 +22276,12 @@ ++stealBuf; d->type = FSL_SATYPE_FORUMPOST; break; } /* - J ?? - + J ?? + Specifies a name value pair for ticket. If the first character of is "+" then the is appended to any preexisting value. If is omitted then it is understood to be an empty string. */ @@ -22180,12 +22300,12 @@ (char const *)token); d->type = FSL_SATYPE_TICKET; break; } /* - K - + K + A K-line gives the UUID for the ticket which this control file is amending. */ case 'K':{ if(d->K){ @@ -22198,12 +22318,12 @@ ++stealBuf; d->type = FSL_SATYPE_TICKET; break; } /* - L - + L + The wiki page title is fossil-encoded. There may be no more than one L line. */ case 'L':{ if(d->L){ @@ -22215,12 +22335,12 @@ ++stealBuf; d->type = FSL_SATYPE_WIKI; break; } /* - M - + M + An M-line identifies another artifact by its UUID. M-lines occur in clusters only. */ case 'M':{ TOKEN(0); @@ -22235,12 +22355,12 @@ SYNTAX("M-card in the wrong order"); } break; } /* - N - + N + An N-line identifies the mimetype of wiki or comment text. */ case 'N':{ if(1N = (char *)token; break; } /* - P ... - + P ... + Specify one or more other artifacts which are the parents of this artifact. The first parent is the primary parent. All others are parents by merge. */ case 'P':{ @@ -22282,12 +22402,12 @@ } } break; } /* - Q (+|-) ?? - + Q (+|-) ?? + Specify one or a range of checkins that are cherrypicked into this checkin ("+") or backed out of this checkin ("-"). */ case 'Q':{ fsl_cherrypick_type_e qType = FSL_CHERRYPICK_INVALID; @@ -22310,12 +22430,12 @@ rc = fsl_deck_Q_add(d, qType, (char const *)uuid, (char const *)token); break; } /* - R - + R + Specify the MD5 checksum over the name and content of all files in the manifest. */ case 'R':{ if(1type = FSL_SATYPE_CHECKIN; break; } /* - T (+|*|-) ?? - - Create or cancel a tag or property. The tagname is fossil-encoded. + T (+|*|-) ?? + + Create or cancel a tag or property. The tagname is fossil-encoded. The first character of the name must be either "+" to create a singleton tag, "*" to create a propagating tag, or "-" to create anti-tag that undoes a prior "+" or blocks propagation of of a "*". - - The tag is applied to . If is "*" then the tag is - applied to the current manifest. If is provided then + + The tag is applied to . If is "*" then the tag is + applied to the current manifest. If is provided then the tag is really a property with the given value. - + Tags are not allowed in clusters. Multiple T lines are allowed. */ case 'T':{ unsigned char * name, * value; fsl_tagtype_e tagType = FSL_TAGTYPE_INVALID; @@ -22376,45 +22496,22 @@ break; case '-': tagType = FSL_TAGTYPE_CANCEL; break; default: SYNTAX("Malformed tag name"); } ++name /* skip type marker byte */; - /* Tag order check from: - - https://fossil-scm.org/home/info/55cacfcace - - (It was subsequently made stricter so that the same tag - type/name/target combination fails.) - - That's difficult to do here until _after_ we add the new - tag to the list... */ + /* Potential todo: add the order check from this commit: + + https://fossil-scm.org/index.html/info/55cacfcace + */ rc = fsl_deck_T_add(d, tagType, (fsl_uuid_cstr)uuid, (char const *)name, (char const *)value); - if(0==rc && d->T.used>1){ - fsl_card_T const * tagPrev = - (fsl_card_T const *)d->T.list[d->T.used-2]; - fsl_card_T const * tagSelf = - (fsl_card_T const *)d->T.list[d->T.used-1]; - int const cmp = fsl_card_T_cmp(&tagPrev, &tagSelf); - if(cmp>=0){ - rc = fsl_cx_err_set(d->f, FSL_RC_SYNTAX, - "T-cards are not in lexical order: " - "%c%s %s %c%s", - fsl_tag_prefix_char(tagPrev->type), - tagPrev->name, - cmp ? ">=" : "==", - fsl_tag_prefix_char(tagSelf->type), - tagSelf->name); - goto bailout; - } - } break; } /* - U ?? - + U ?? + Identify the user who created this control file by their login. Only one U line is allowed. Prohibited in clusters. If the user name is omitted, take that to be "anonymous". */ case 'U':{ @@ -22448,14 +22545,12 @@ SYNTAX("Wiki size token is invalid"); } if( (&x.z[wlen+1]) > x.zEnd){ SYNTAX("Not enough content after W-card"); } - //rc = fsl_buffer_append(&d->W, x.z, wlen); - //if(rc) goto bailout; - fsl_buffer_external(&d->W, x.z, wlen); - ++stealBuf; + rc = fsl_buffer_append(&d->W, x.z, wlen); + if(rc) goto bailout; x.z += wlen; if( '\n' != x.z[0] ){ SYNTAX("W-card content not \\n terminated"); } x.z[0] = 0; @@ -22462,11 +22557,11 @@ ++x.z; break; } /* Z - + MD5 checksum on this control file. The checksum is over all lines (other than PGP-signature lines) prior to the current line. This must be the last record. This card is required for all control file types except for @@ -22517,11 +22612,12 @@ } if(FSL_SATYPE_ANY==d->type){ rc = fsl_cx_err_set(f, FSL_RC_ERROR, "Internal error: could not determine type of " - "artifact we just (successfully!) parsed."); + "control artifact we just (successfully!) " + "parsed."); goto bailout; }else { /* Make sure we didn't pick up any cards which were picked up before d->type was guessed and are invalid for the post-guessed @@ -22551,27 +22647,27 @@ /* Additional checks based on artifact type */ switch( d->type ){ case FSL_SATYPE_CONTROL: { if( nSelfTag ){ - SYNTAX("Self-referential T-card in control artifact"); + SYNTAX("self-referential T-card in control artifact"); } break; } case FSL_SATYPE_TECHNOTE: { if( d->T.used!=nSelfTag ){ - SYNTAX("Non-self-referential T-card in technote"); + SYNTAX("non-self-referential T-card in technote"); }else if( d->T.used!=nSimpleTag ){ SYNTAX("T-card with '*' or '-' in technote"); } break; } case FSL_SATYPE_FORUMPOST: { if( d->H && d->I ){ - SYNTAX("Cannot have I-card and H-card in a forum post"); + SYNTAX("cannot have I-card and H-card in a forum post"); }else if( d->P.used>1 ){ - SYNTAX("Too many arguments to P-card"); + SYNTAX("too many arguments to P-card"); } break; } default: break; } @@ -22836,11 +22932,11 @@ int fsl_deck_save( fsl_deck * const d, bool isPrivate ){ int rc; fsl_cx * const f = d->f; fsl_db * const db = fsl_needs_repo(f); - fsl_buffer * const buf = &d->f->cache.fileContent; + fsl_buffer * const buf = &d->f->fileContent; fsl_id_t newRid = 0; bool const oldPrivate = f->cache.markPrivate; if(!f || !d ) return FSL_RC_MISUSE; else if(!db) return FSL_RC_NOT_A_REPO; if(d->rid>0){ @@ -23014,28 +23110,29 @@ fsl_stmt_finalize(&q); if(rc) goto end; /* Process entries from pending_xlink temp table... */ rc = fsl_cx_prepare(f, &q, "SELECT id FROM pending_xlink"); - while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){ + if(rc) goto end; + while( FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){ const char *zId = fsl_stmt_g_text(&q, 0, NULL); char cType; if(!zId || !*zId) continue; cType = zId[0]; ++zId; if('t'==cType){ - rc = fsl__ticket_rebuild(f, zId); + /* FSL-MISSING: + ticket_rebuild_entry(zId) */ continue; }else if('w'==cType){ /* FSL-MISSING: backlink_wiki_refresh(zId) */ continue; } } - fsl_stmt_finalize(&q); - if(rc) goto end; - rc = fsl_cx_exec(f, "DELETE FROM pending_xlink"); + fsl_stmt_finalize(&q); + rc = fsl_cx_exec(f, "DROP TABLE pending_xlink"); if(rc) goto end; /* If multiple check-ins happen close together in time, adjust their times by a few milliseconds to make sure they appear in chronological order. */ @@ -23069,11 +23166,13 @@ " WHERE objid IN (SELECT mid FROM time_fudge)" " AND (mtime=omtime OR omtime IS NULL)" ); } end: - fsl_cx_exec(f, "DELETE FROM time_fudge"); + if(!rc){ + fsl_cx_exec(f, "DROP TABLE time_fudge"); + } if(rc) fsl_cx_transaction_end(f, true); else rc = fsl_cx_transaction_end(f, false); return rc; } @@ -23086,20 +23185,17 @@ "Crosslink is already running."); } rc = fsl_cx_transaction_begin(f); if(rc) return rc; rc = fsl_cx_exec_multi(f, - "CREATE TEMP TABLE IF NOT EXISTS " - "pending_xlink(id TEXT PRIMARY KEY)WITHOUT ROWID;" - "CREATE TEMP TABLE IF NOT EXISTS time_fudge(" + "CREATE TEMP TABLE pending_xlink(id TEXT PRIMARY KEY)WITHOUT ROWID;" + "CREATE TEMP TABLE time_fudge(" " mid INTEGER PRIMARY KEY," /* The rid of a manifest */ " m1 REAL," /* The timestamp on mid */ " cid INTEGER," /* A child or mid */ " m2 REAL" /* Timestamp on the child */ - ");" - "DELETE FROM pending_xlink; " - "DELETE FROM time_fudge;"); + ");"); if(0==rc){ f->cache.isCrosslinking = true; }else{ fsl_cx_transaction_end(f, true); } @@ -23108,12 +23204,12 @@ #undef MARKER #undef AGE_FUDGE_WINDOW #undef AGE_ADJUST_INCREMENT #undef F_at -/* end of file ./src/deck.c */ -/* start of file ./src/delta.c */ +/* end of file deck.c */ +/* start of file delta.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -23360,20 +23456,21 @@ unsigned int *landmark; /* Primary hash table */ unsigned int *collide = NULL; /* Collision chain */ int lastRead = -1; /* Last byte of zSrc read by a COPY command */ int rc; /* generic return code checker. */ unsigned int olen = 0; /* current output length. */ + unsigned int total = 0; /* total byte count. */ fsl_delta_hash h; unsigned char theBuf[IntegerBufSize] = {0,}; unsigned char * intBuf = theBuf; if(!zSrc || !zOut || !out) return FSL_RC_MISUSE; /* Add the target file size to the beginning of the delta */ #ifdef OUT #undef OUT #endif -#define OUT(BLOB,LEN) rc=out(outState, BLOB, LEN); if(0 != rc) {fsl_free(collide); return rc;} else (void)0 +#define OUT(BLOB,LEN) rc=out(outState, BLOB, LEN); if(0 != rc) {fsl_free(collide); return rc;} else total += LEN #define OUTCH(CHAR) OUT(CHAR,1) #define PINT(I) intBuf = theBuf; olen=fsl_delta_int_put(I, &intBuf); OUT(theBuf,olen) PINT(lenOut); OUTCH("\n"); @@ -23755,12 +23852,12 @@ } #undef NHASH #undef DEBUG1 #undef DEBUG2 -/* end of file ./src/delta.c */ -/* start of file ./src/diff.c */ +/* end of file delta.c */ +/* start of file diff.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -23778,17 +23875,254 @@ #include #include #include #include /* for memmove()/strlen() */ +#define MARKER(pfexp) \ + do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ + printf pfexp; \ + } while(0) + +typedef uint64_t u64; +typedef void ReCompiled /* porting crutch. i would strongly prefer to + replace the regex support with a stateful + predicate callback. + */; + +#define DIFF_CONTEXT_MASK ((u64)0x0000ffff) /* Lines of context. Default if 0 */ +#define DIFF_WIDTH_MASK ((u64)0x00ff0000) /* side-by-side column width */ +#define DIFF_IGNORE_EOLWS ((u64)0x01000000) /* Ignore end-of-line whitespace */ +#define DIFF_IGNORE_ALLWS ((u64)0x03000000) /* Ignore all whitespace */ +#define DIFF_SIDEBYSIDE ((u64)0x04000000) /* Generate a side-by-side diff */ +#define DIFF_VERBOSE ((u64)0x08000000) /* Missing shown as empty files */ +#define DIFF_BRIEF ((u64)0x10000000) /* Show filenames only */ +#define DIFF_HTML ((u64)0x20000000) /* Render for HTML */ +#define DIFF_LINENO ((u64)0x40000000) /* Show line numbers */ +#define DIFF_NOOPT (((u64)0x01)<<32) /* Suppress optimizations (debug) */ +#define DIFF_INVERT (((u64)0x02)<<32) /* Invert the diff (debug) */ +#define DIFF_CONTEXT_EX (((u64)0x04)<<32) /* Use context even if zero */ +#define DIFF_NOTTOOBIG (((u64)0x08)<<32) /* Only display if not too big */ +#define DIFF_STRIP_EOLCR (((u64)0x10)<<32) /* Strip trailing CR */ + +/* Annotation flags (any DIFF flag can be used as Annotation flag as well) */ +#define ANN_FILE_VERS (((u64)0x20)<<32) /* Show file vers rather than commit vers */ +#define ANN_FILE_ANCEST (((u64)0x40)<<32) /* Prefer check-ins in the ANCESTOR table */ + + +/* + ANSI escape codes: https://en.wikipedia.org/wiki/ANSI_escape_code +*/ +#define ANSI_COLOR_BLACK(BOLD) ((BOLD) ? "\x1b[30m" : "\x1b[30m") +#define ANSI_COLOR_RED(BOLD) ((BOLD) ? "\x1b[31;1m" : "\x1b[31m") +#define ANSI_COLOR_GREEN(BOLD) ((BOLD) ? "\x1b[32;1m" : "\x1b[32m") +#define ANSI_COLOR_YELLOW(BOLD) ((BOLD) ? "\x1b[33;1m" : "\x1b[33m") +#define ANSI_COLOR_BLUE(BOLD) ((BOLD) ? "\x1b[34;1m" : "\x1b[34m") +#define ANSI_COLOR_MAGENTA(BOLD) ((BOLD) ? "\x1b[35;1m" : "\x1b[35m") +#define ANSI_COLOR_CYAN(BOLD) ((BOLD) ? "\x1b[36;1m" : "\x1b[36m") +#define ANSI_COLOR_WHITE(BOLD) ((BOLD) ? "\x1b[37;1m" : "\x1b[37m") +#define ANSI_DIFF_ADD(BOLD) ANSI_COLOR_GREEN(BOLD) +#define ANSI_DIFF_RM(BOLD) ANSI_COLOR_RED(BOLD) +#define ANSI_DIFF_MOD(BOLD) ANSI_COLOR_BLUE(BOLD) +#define ANSI_BG_BLACK(BOLD) ((BOLD) ? "\x1b[40;1m" : "\x1b[40m") +#define ANSI_BG_RED(BOLD) ((BOLD) ? "\x1b[41;1m" : "\x1b[41m") +#define ANSI_BG_GREEN(BOLD) ((BOLD) ? "\x1b[42;1m" : "\x1b[42m") +#define ANSI_BG_YELLOW(BOLD) ((BOLD) ? "\x1b[43;1m" : "\x1b[43m") +#define ANSI_BG_BLUE(BOLD) ((BOLD) ? "\x1b[44;1m" : "\x1b[44m") +#define ANSI_BG_MAGENTA(BOLD) ((BOLD) ? "\x1b[45;1m" : "\x1b[45m") +#define ANSI_BG_CYAN(BOLD) ((BOLD) ? "\x1b[46;1m" : "\x1b[46m") +#define ANSI_BG_WHITE(BOLD) ((BOLD) ? "\x1b[47;1m" : "\x1b[47m") +#define ANSI_RESET_COLOR "\x1b[39;49m" +#define ANSI_RESET_ALL "\x1b[0m" +#define ANSI_RESET ANSI_RESET_ALL +/*#define ANSI_BOLD ";1m"*/ + +/** + Extract the number of lines of context from diffFlags. + */ +static int diff_context_lines(uint64_t diffFlags){ + int n = diffFlags & DIFF_CONTEXT_MASK; + if( n==0 && (diffFlags & DIFF_CONTEXT_EX)==0 ) n = 5; + return n; +} + +/* + Extract the width of columns for side-by-side diff. Supply an + appropriate default if no width is given. +*/ +static int diff_width(uint64_t diffFlags){ + int w = (diffFlags & DIFF_WIDTH_MASK)/(DIFF_CONTEXT_MASK+1); + if( w==0 ) w = 80; + return w; +} /** + Converts mask of public fsl_diff_flag_t (32-bit) values to the + Fossil-internal 64-bit bitmask used by the DIFF_xxx macros. Why? + (A) fossil(1) uses the macro approach and a low-level encoding of + data in the bitmask (e.g. the context lines count). The public API + hides the lower-level flags and allows the internal API to take + care of the encoding. +*/ +static uint64_t fsl_diff_flags_convert( int mask ){ + uint64_t rc = 0U; +#define DO(F) if( (mask & F)==F ) rc |= (((u64)F) << 24) + DO(FSL_DIFF_IGNORE_EOLWS); + DO(FSL_DIFF_IGNORE_ALLWS); + DO(FSL_DIFF_SIDEBYSIDE); + DO(FSL_DIFF_VERBOSE); + DO(FSL_DIFF_BRIEF); + DO(FSL_DIFF_HTML); + DO(FSL_DIFF_LINENO); + DO(FSL_DIFF_NOOPT); + DO(FSL_DIFF_INVERT); + DO(FSL_DIFF_NOTTOOBIG); + DO(FSL_DIFF_STRIP_EOLCR); +#undef DO + return rc; +} + +/* Length of a dline */ #define LENGTH(X) ((X)->n) /** + Holds output state for diff generation. + */ +struct DiffOutState { + /** Output callback. */ + fsl_output_f out; + /** State for this->out(). */ + void * oState; + /** For propagating output errors. */ + int rc; + char ansiColor; +}; +typedef struct DiffOutState DiffOutState; +static const DiffOutState DiffOutState_empty = { +NULL/*out*/, +NULL/*oState*/, +0/*rc*/, +0/*useAnsiColor*/ +}; + +/** + Internal helper. Sends src to o->out(). If n is negative, fsl_strlen() + is used to determine the length. + */ +static int diff_out( DiffOutState * const o, void const * src, fsl_int_t n ){ + return o->rc = n + ? o->out(o->oState, src, n<0 ? fsl_strlen((char const *)src) : (fsl_size_t)n) + : 0; +} + +/** + fsl_output_f() impl for use with diff_outf(). state must be a + (DiffOutState*). + */ +static int fsl_output_f_diff_out( void * state, void const * src, + fsl_size_t n ){ + DiffOutState * const os = (DiffOutState *)state; + return os->rc = os->out(os->oState, src, n); +} + +static int diff_outf( DiffOutState * o, char const * fmt, ... ){ + va_list va; + va_start(va,fmt); + fsl_appendfv(fsl_output_f_diff_out, o, fmt, va); + va_end(va); + return o->rc; +} + +/* + Append a single line of context-diff output to pOut. +*/ +static int appendDiffLine( + DiffOutState *const pOut, /* Where to write the line of output */ + char cPrefix, /* One of " ", "+", or "-" */ + fsl_dline *pLine, /* The line to be output */ + int html, /* True if generating HTML. False for plain text */ + ReCompiled *pRe /* Colorize only if line matches this Regex */ +){ + int rc = 0; + char const * ansiPrefix = + !pOut->ansiColor + ? NULL + : (('+'==cPrefix) + ? ANSI_DIFF_ADD(0) + : (('-'==cPrefix) ? ANSI_DIFF_RM(0) : NULL)) + ; + if(ansiPrefix) rc = diff_out(pOut, ansiPrefix, -1 ); + if(!rc) rc = diff_out(pOut, &cPrefix, 1); + if(rc) return rc; + else if( html ){ +#if 0 + if( pRe /*MISSING: && re_dline_match(pRe, pLine, 1)==0 */ ){ + cPrefix = ' '; + }else +#endif + if( cPrefix=='+' ){ + rc = diff_out(pOut, "", -1); + }else if( cPrefix=='-' ){ + rc = diff_out(pOut, "", -1); + } + if(!rc){ + /* unsigned short n = pLine->n; */ + /* while( n>0 && (pLine->z[n-1]=='\n' || pLine->z[n-1]=='\r') ) n--; */ + rc = pOut->rc = fsl_htmlize(pOut->out, pOut->oState, + pLine->z, pLine->n); + if( !rc && cPrefix!=' ' ){ + rc = diff_out(pOut, "", -1); + } + } + }else{ + rc = diff_out(pOut, pLine->z, pLine->n); + } + if(!rc){ + if(ansiPrefix){ + rc = diff_out(pOut, ANSI_RESET, -1 ); + } + if(!rc) rc = diff_out(pOut, "\n", 1); + } + return rc; +} + + +/* + Add two line numbers to the beginning of an output line for a context + diff. One or the other of the two numbers might be zero, which means + to leave that number field blank. The "html" parameter means to format + the output for HTML. +*/ +static int appendDiffLineno(DiffOutState *pOut, int lnA, + int lnB, int html){ + int rc = 0; + if( html ){ + rc = diff_out(pOut, "", -1); + } + if(!rc){ + if( lnA>0 ){ + rc = diff_outf(pOut, "%6d ", lnA); + }else{ + rc = diff_out(pOut, " ", 7); + } + } + if(!rc){ + if( lnB>0 ){ + rc = diff_outf(pOut, "%6d ", lnB); + }else{ + rc = diff_out(pOut, " ", 8); + } + if( !rc && html ){ + rc = diff_out(pOut, "", -1); + } + } + return rc; +} + + +/* Minimum of two values */ static int minInt(int a, int b){ return aaTo[p->aFrom[i].h % p->nTo].iHash; - while( j>0 - && (j-1=iE2 || p->cmpLine(&p->aFrom[i], &p->aTo[j-1])) - ){ - if( limit++ > cutoff ){ - j = 0; - nextCutoff = cutoff*4; - break; - } - j = p->aTo[j-1].iNext; - } - if( j==0 ) continue; - assert( i>=iSXb && i>=iSXp ); - if( i=iSYb && j=iSYp && jaFrom[iSX-1]; - pB = &p->aTo[iSY-1]; - n = minInt(iSX-iS1, iSY-iS2); - for(k=0; kcmpLine(pA,pB)==0; k++, pA--, pB--){} - iSX -= k; - iSY -= k; - iEX = i+1; - iEY = j; - pA = &p->aFrom[iEX]; - pB = &p->aTo[iEY]; - n = minInt(iE1-iEX, iE2-iEY); - for(k=0; kcmpLine(pA,pB)==0; k++, pA++, pB++){} - iEX += k; - iEY += k; - skew = (iSX-iS1) - (iSY-iS2); - if( skew<0 ) skew = -skew; - dist = (iSX+iEX)/2 - mid; - if( dist<0 ) dist = -dist; - score = (iEX - iSX)*(sqlite3_int64)span - (skew + dist); - if( score>bestScore ){ - bestScore = score; - iSXb = iSX; - iSYb = iSY; - iEXb = iEX; - iEYb = iEY; - }else if( iEX>iEXp ){ - iSXp = iSX; - iSYp = iSY; - iEXp = iEX; - iEYp = iEY; - } - } - }while( iSXb==iEXb && nextCutoff && (cutoff=nextCutoff)<=64 ); - if( iSXb==iEXb && (sqlite3_int64)(iE1-iS1)*(iE2-iS2)<2500 ){ + for(i=iS1; iaTo[p->aFrom[i].h % p->nTo].iHash; + while( j>0 + && (j-1=iE2 || p->cmpLine(&p->aFrom[i], &p->aTo[j-1])) + ){ + if( limit++ > 10 ){ + j = 0; + break; + } + j = p->aTo[j-1].iNext; + } + if( j==0 ) continue; + assert( i>=iSXb && i>=iSXp ); + if( i=iSYb && j=iSYp && jaFrom[iSX-1]; + pB = &p->aTo[iSY-1]; + n = minInt(iSX-iS1, iSY-iS2); + for(k=0; kcmpLine(pA,pB)==0; k++, pA--, pB--){} + iSX -= k; + iSY -= k; + iEX = i+1; + iEY = j; + pA = &p->aFrom[iEX]; + pB = &p->aTo[iEY]; + n = minInt(iE1-iEX, iE2-iEY); + for(k=0; kcmpLine(pA,pB)==0; k++, pA++, pB++){} + iEX += k; + iEY += k; + skew = (iSX-iS1) - (iSY-iS2); + if( skew<0 ) skew = -skew; + dist = (iSX+iEX)/2 - mid; + if( dist<0 ) dist = -dist; + score = (iEX - iSX)*(sqlite3_int64)span - (skew + dist); + if( score>bestScore ){ + bestScore = score; + iSXb = iSX; + iSYb = iSY; + iEXb = iEX; + iEYb = iEY; + }else if( iEX>iEXp ){ + iSXp = iSX; + iSYp = iSY; + iEXp = iEX; + iEYp = iEY; + } + } + if( +#if 0 + 1 + /* CANNOT EXPLAIN why we get different diff results than fossil + unless we use fsl_diff_optimal_lcs() despite using, insofar as + i can tell, the same inputs. There is some aspect i'm + overlooking. */ +#else + iSXb==iEXb && (sqlite3_int64)(iE1-iS1)*(iE2-iS2)<400 +#endif + ){ + /* If no common sequence is found using the hashing heuristic and + ** the input is not too big, use the expensive exact solution */ fsl__diff_optimal_lcs(p, iS1, iE1, iS2, iE2, piSX, piEX, piSY, piEY); }else{ *piSX = iSXb; *piSY = iSYb; *piEX = iEXb; @@ -24196,244 +24536,10 @@ } //fsl__dump_triples(p, __FILE__, __LINE__); } -#if !defined(FSL_OMIT_DEPRECATED) - -#define MARKER(pfexp) \ - do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ - printf pfexp; \ - } while(0) - -typedef uint64_t u64; -typedef void ReCompiled /* porting crutch. i would strongly prefer to - replace the regex support with a stateful - predicate callback. - */; - -#define DIFF_CONTEXT_MASK ((u64)0x0000ffff) /* Lines of context. Default if 0 */ -#define DIFF_WIDTH_MASK ((u64)0x00ff0000) /* side-by-side column width */ -#define DIFF_IGNORE_EOLWS ((u64)0x01000000) /* Ignore end-of-line whitespace */ -#define DIFF_IGNORE_ALLWS ((u64)0x03000000) /* Ignore all whitespace */ -#define DIFF_SIDEBYSIDE ((u64)0x04000000) /* Generate a side-by-side diff */ -#define DIFF_VERBOSE ((u64)0x08000000) /* Missing shown as empty files */ -#define DIFF_BRIEF ((u64)0x10000000) /* Show filenames only */ -#define DIFF_HTML ((u64)0x20000000) /* Render for HTML */ -#define DIFF_LINENO ((u64)0x40000000) /* Show line numbers */ -#define DIFF_NOOPT (((u64)0x01)<<32) /* Suppress optimizations (debug) */ -#define DIFF_INVERT (((u64)0x02)<<32) /* Invert the diff (debug) */ -#define DIFF_CONTEXT_EX (((u64)0x04)<<32) /* Use context even if zero */ -#define DIFF_NOTTOOBIG (((u64)0x08)<<32) /* Only display if not too big */ -#define DIFF_STRIP_EOLCR (((u64)0x10)<<32) /* Strip trailing CR */ - -/* - ANSI escape codes: https://en.wikipedia.org/wiki/ANSI_escape_code -*/ -#define ANSI_COLOR_BLACK(BOLD) ((BOLD) ? "\x1b[30m" : "\x1b[30m") -#define ANSI_COLOR_RED(BOLD) ((BOLD) ? "\x1b[31;1m" : "\x1b[31m") -#define ANSI_COLOR_GREEN(BOLD) ((BOLD) ? "\x1b[32;1m" : "\x1b[32m") -#define ANSI_COLOR_YELLOW(BOLD) ((BOLD) ? "\x1b[33;1m" : "\x1b[33m") -#define ANSI_COLOR_BLUE(BOLD) ((BOLD) ? "\x1b[34;1m" : "\x1b[34m") -#define ANSI_COLOR_MAGENTA(BOLD) ((BOLD) ? "\x1b[35;1m" : "\x1b[35m") -#define ANSI_COLOR_CYAN(BOLD) ((BOLD) ? "\x1b[36;1m" : "\x1b[36m") -#define ANSI_COLOR_WHITE(BOLD) ((BOLD) ? "\x1b[37;1m" : "\x1b[37m") -#define ANSI_DIFF_ADD(BOLD) ANSI_COLOR_GREEN(BOLD) -#define ANSI_DIFF_RM(BOLD) ANSI_COLOR_RED(BOLD) -#define ANSI_DIFF_MOD(BOLD) ANSI_COLOR_BLUE(BOLD) -#define ANSI_BG_BLACK(BOLD) ((BOLD) ? "\x1b[40;1m" : "\x1b[40m") -#define ANSI_BG_RED(BOLD) ((BOLD) ? "\x1b[41;1m" : "\x1b[41m") -#define ANSI_BG_GREEN(BOLD) ((BOLD) ? "\x1b[42;1m" : "\x1b[42m") -#define ANSI_BG_YELLOW(BOLD) ((BOLD) ? "\x1b[43;1m" : "\x1b[43m") -#define ANSI_BG_BLUE(BOLD) ((BOLD) ? "\x1b[44;1m" : "\x1b[44m") -#define ANSI_BG_MAGENTA(BOLD) ((BOLD) ? "\x1b[45;1m" : "\x1b[45m") -#define ANSI_BG_CYAN(BOLD) ((BOLD) ? "\x1b[46;1m" : "\x1b[46m") -#define ANSI_BG_WHITE(BOLD) ((BOLD) ? "\x1b[47;1m" : "\x1b[47m") -#define ANSI_RESET_COLOR "\x1b[39;49m" -#define ANSI_RESET_ALL "\x1b[0m" -#define ANSI_RESET ANSI_RESET_ALL -/*#define ANSI_BOLD ";1m"*/ - -/** - Converts mask of public fsl_diff_flag_t (32-bit) values to the - Fossil-internal 64-bit bitmask used by the DIFF_xxx macros. Why? - (A) fossil(1) uses the macro approach and a low-level encoding of - data in the bitmask (e.g. the context lines count). The public API - hides the lower-level flags and allows the internal API to take - care of the encoding. -*/ -static uint64_t fsl_diff_flags_convert( int mask ){ - uint64_t rc = 0U; -#define DO(F) if( (mask & F)==F ) rc |= (((u64)F) << 24) - DO(FSL_DIFF2_IGNORE_EOLWS); - DO(FSL_DIFF2_IGNORE_ALLWS); - DO(FSL_DIFF2_LINE_NUMBERS); - DO(FSL_DIFF_SIDEBYSIDE); - DO(FSL_DIFF2_NOTTOOBIG); - DO(FSL_DIFF2_STRIP_EOLCR); - DO(FSL_DIFF_VERBOSE); - DO(FSL_DIFF_BRIEF); - DO(FSL_DIFF_HTML); - DO(FSL_DIFF_NOOPT); - DO(FSL_DIFF_INVERT); -#undef DO - return rc; -} - -/** - Holds output state for diff generation. - */ -struct DiffOutState { - /** Output callback. */ - fsl_output_f out; - /** State for this->out(). */ - void * oState; - /** For propagating output errors. */ - int rc; - char ansiColor; -}; -typedef struct DiffOutState DiffOutState; -static const DiffOutState DiffOutState_empty = { -NULL/*out*/, -NULL/*oState*/, -0/*rc*/, -0/*useAnsiColor*/ -}; - -/** - Internal helper. Sends src to o->out(). If n is negative, fsl_strlen() - is used to determine the length. - */ -static int diff_out( DiffOutState * const o, void const * src, fsl_int_t n ){ - return o->rc = n - ? o->out(o->oState, src, n<0 ? fsl_strlen((char const *)src) : (fsl_size_t)n) - : 0; -} - -/** - fsl_output_f() impl for use with diff_outf(). state must be a - (DiffOutState*). - */ -static int fsl_output_f_diff_out( void * state, void const * src, - fsl_size_t n ){ - DiffOutState * const os = (DiffOutState *)state; - return os->rc = os->out(os->oState, src, n); -} - -static int diff_outf( DiffOutState * o, char const * fmt, ... ){ - va_list va; - va_start(va,fmt); - fsl_appendfv(fsl_output_f_diff_out, o, fmt, va); - va_end(va); - return o->rc; -} - -/* - Append a single line of context-diff output to pOut. -*/ -static int appendDiffLine( - DiffOutState *const pOut, /* Where to write the line of output */ - char cPrefix, /* One of " ", "+", or "-" */ - fsl_dline *pLine, /* The line to be output */ - int html, /* True if generating HTML. False for plain text */ - ReCompiled *pRe /* Colorize only if line matches this Regex */ -){ - int rc = 0; - char const * ansiPrefix = - !pOut->ansiColor - ? NULL - : (('+'==cPrefix) - ? ANSI_DIFF_ADD(0) - : (('-'==cPrefix) ? ANSI_DIFF_RM(0) : NULL)) - ; - if(ansiPrefix) rc = diff_out(pOut, ansiPrefix, -1 ); - if(!rc) rc = diff_out(pOut, &cPrefix, 1); - if(rc) return rc; - else if( html ){ -#if 0 - if( pRe /*MISSING: && re_dline_match(pRe, pLine, 1)==0 */ ){ - cPrefix = ' '; - }else -#endif - if( cPrefix=='+' ){ - rc = diff_out(pOut, "", -1); - }else if( cPrefix=='-' ){ - rc = diff_out(pOut, "", -1); - } - if(!rc){ - /* unsigned short n = pLine->n; */ - /* while( n>0 && (pLine->z[n-1]=='\n' || pLine->z[n-1]=='\r') ) n--; */ - rc = pOut->rc = fsl_htmlize(pOut->out, pOut->oState, - pLine->z, pLine->n); - if( !rc && cPrefix!=' ' ){ - rc = diff_out(pOut, "", -1); - } - } - }else{ - rc = diff_out(pOut, pLine->z, pLine->n); - } - if(!rc){ - if(ansiPrefix){ - rc = diff_out(pOut, ANSI_RESET, -1 ); - } - if(!rc) rc = diff_out(pOut, "\n", 1); - } - return rc; -} - - -/* - Add two line numbers to the beginning of an output line for a context - diff. One or the other of the two numbers might be zero, which means - to leave that number field blank. The "html" parameter means to format - the output for HTML. -*/ -static int appendDiffLineno(DiffOutState *pOut, int lnA, - int lnB, int html){ - int rc = 0; - if( html ){ - rc = diff_out(pOut, "", -1); - } - if(!rc){ - if( lnA>0 ){ - rc = diff_outf(pOut, "%6d ", lnA); - }else{ - rc = diff_out(pOut, " ", 7); - } - } - if(!rc){ - if( lnB>0 ){ - rc = diff_outf(pOut, "%6d ", lnB); - }else{ - rc = diff_out(pOut, " ", 8); - } - if( !rc && html ){ - rc = diff_out(pOut, "", -1); - } - } - return rc; -} - -/** - Extract the number of lines of context from diffFlags. - */ -static int diff_context_lines(uint64_t diffFlags){ - int n = diffFlags & DIFF_CONTEXT_MASK; - if( n==0 && (diffFlags & DIFF_CONTEXT_EX)==0 ) n = 5; - return n; -} - -/* - Extract the width of columns for side-by-side diff. Supply an - appropriate default if no width is given. -*/ -static int diff_width(uint64_t diffFlags){ - int w = (diffFlags & DIFF_WIDTH_MASK)/(DIFF_CONTEXT_MASK+1); - if( w==0 ) w = 80; - return w; -} - /* Given a raw diff p[] in which the p->aEdit[] array has been filled in, compute a context diff into pOut. */ static int contextDiff( @@ -25331,10 +25437,11 @@ int b = 0; /* Index of next line in B[] */ int *R; /* Array of COPY/DELETE/INSERT triples */ int r; /* Index into R[] */ int nr; /* Number of COPY/DELETE/INSERT triples to process */ int mxr; /* Maximum value for r */ + int na, nb; /* Number of lines shown from A and B */ int i, j; /* Loop counters */ int m, ma, mb;/* Number of lines to output */ int skip; /* Number of lines to skip */ static int nChunk = 0; /* Number of chunks of diff output seen so far */ SbsLine s; /* Output line buffer */ @@ -25400,15 +25507,33 @@ continue; } } #endif /* For the current block comprising nr triples, figure out - how many lines to skip. */ + how many lines of A and B are to be displayed + */ if( R[r]>nContext ){ + na = nb = nContext; skip = R[r] - nContext; }else{ + na = nb = R[r]; skip = 0; + } + for(i=0; inContext ){ + na += nContext; + nb += nContext; + }else{ + na += R[r+nr*3]; + nb += R[r+nr*3]; + } + for(i=1; i #include #include #include /* for memmove()/strlen() */ #include @@ -25806,12 +25935,12 @@ do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ printf pfexp; \ } while(0) -const fsl_dibu_opt fsl_dibu_opt_empty = fsl_dibu_opt_empty_m; -const fsl_dibu fsl_dibu_empty = fsl_dibu_empty_m; +const fsl_diff_opt fsl_diff_opt_empty = fsl_diff_opt_empty_m; +const fsl_diff_builder fsl_diff_builder_empty = fsl_diff_builder_empty_m; const fsl_dline fsl_dline_empty = fsl_dline_empty_m; const fsl_dline_change fsl_dline_change_empty = fsl_dline_change_empty_m; const fsl__diff_cx fsl__diff_cx_empty = fsl__diff_cx_empty_m; void fsl__diff_cx_clean(fsl__diff_cx * const cx){ @@ -26260,139 +26389,10 @@ ** O(N*N) Wagner minimum-edit-distance algorithm to a less process ** O(NlogN) divide-and-conquer approach. */ #define DIFF_ALIGN_MX 1225 -/** - FSL_DIFF_SMALL_GAP=0 is a temporary(? as of 2022-01-04) patch for a - cosmetic-only (but unsightly) quirk of the diff engine where it - produces a pair of identical DELETE/INSERT lines. Richard's - preliminary solution for it is to remove the "small gap merging," - but he notes (in fossil /chat) that he's not recommending this as - "the" fix. - - PS: we colloquially know this as "the lineno diff" because it was first - reported in a diff which resulted in: - -``` -- int lineno; -+ int lineno; -``` - - (No, there are no whitespace changes there.) - - To reiterate, though: this is not a "bug," in that it does not - cause incorrect results when applying the resulting unfified-diff - patches. It does, however, cause confusion for human users. - - - Here are two inputs which, when diffed, expose the lineno behavior: - - #1: - -``` -struct fnc_diff_view_state { - int first_line_onscreen; - int last_line_onscreen; - int diff_flags; - int context; - int sbs; - int matched_line; - int current_line; - int lineno; - size_t ncols; - size_t nlines; - off_t *line_offsets; - bool eof; - bool colour; - bool showmeta; - bool showln; -}; -``` - - #2: - -``` -struct fnc_diff_view_state { - int first_line_onscreen; - int last_line_onscreen; - int diff_flags; - int context; - int sbs; - int matched_line; - int selected_line; - int lineno; - int gtl; - size_t ncols; - size_t nlines; - off_t *line_offsets; - bool eof; - bool colour; - bool showmeta; - bool showln; -}; -``` - - Result without this patch: - -``` -Index: X.0 -================================================================== ---- X.0 -+++ X.1 -@@ -3,15 +3,16 @@ - int last_line_onscreen; - int diff_flags; - int context; - int sbs; - int matched_line; -+ int selected_line; -- int current_line; -- int lineno; -+ int lineno; -+ int gtl; - size_t ncols; - size_t nlines; - off_t *line_offsets; - bool eof; - bool colour; - bool showmeta; - bool showln; - }; -``` - - And with the patch: - -``` -Index: X.0 -================================================================== ---- X.0 -+++ X.1 -@@ -3,15 +3,16 @@ - int last_line_onscreen; - int diff_flags; - int context; - int sbs; - int matched_line; -- int current_line; -+ int selected_line; - int lineno; -+ int gtl; - size_t ncols; - size_t nlines; - off_t *line_offsets; - bool eof; - bool colour; - bool showmeta; - bool showln; - }; -``` - -*/ -#define FSL_DIFF_SMALL_GAP 0 - -#if FSL_DIFF_SMALL_GAP /* ** R[] is an array of six integer, two COPY/DELETE/INSERT triples for a ** pair of adjacent differences. Return true if the gap between these ** two differences is so small that they should be rendered as a single ** edit. @@ -26402,13 +26402,12 @@ ma += R[4] + m; mb += R[5] + m; if( ma*mb>DIFF_ALIGN_MX ) return 0; return m<=2 || m<=(R[1]+R[2]+R[4]+R[5])/8; } -#endif -static unsigned short diff_opt_context_lines(fsl_dibu_opt const * opt){ +static unsigned short diff_opt_context_lines(fsl_diff_opt const * opt){ const unsigned short dflt = 5; unsigned short n = opt ? opt->contextLines : dflt; if( !n && (opt->diffFlags & FSL_DIFF2_CONTEXT_ZERO)==0 ){ n = dflt; } @@ -26523,11 +26522,11 @@ ** mismatch. */ static int diffBlockAlignment( const fsl_dline *aLeft, int nLeft, /* Text on the left */ const fsl_dline *aRight, int nRight, /* Text on the right */ - fsl_dibu_opt * const pOpt, /* Configuration options */ + fsl_diff_opt *pOpt, /* Configuration options */ unsigned char **pResult, /* Raw result */ unsigned *pNResult /* OUTPUT: length of result */ ){ int i, j, k; /* Loop counters */ int *a = 0; /* One row of the Wagner matrix */ @@ -26706,19 +26705,19 @@ return rc; } /* -** Format a diff using a fsl_dibu object +** Format a diff using a fsl_diff_builder object */ static int fdb__format( fsl__diff_cx * const cx, - fsl_dibu * const pBuilder + fsl_diff_builder * const pBuilder ){ const fsl_dline *A; /* Left side of the diff */ const fsl_dline *B; /* Right side of the diff */ - fsl_dibu_opt * const pOpt = pBuilder->opt; + fsl_diff_opt * const pOpt = pBuilder->opt; const int *R; /* Array of COPY/DELETE/INSERT triples */ unsigned int a; /* Index of next line in A[] */ unsigned int b; /* Index of next line in B[] */ unsigned int r; /* Index into R[] */ unsigned int nr; /* Number of COPY/DELETE/INSERT triples to process */ @@ -26728,13 +26727,12 @@ unsigned int m, ma, mb;/* Number of lines to output */ signed int skip; /* Number of lines to skip */ unsigned int contextLines; /* Lines of context above and below each change */ unsigned short passNumber = 0; int rc = 0; - + #define RC if(rc) goto end -#define METRIC(M) if(1==passNumber) ++pBuilder->metrics.M pass_again: contextLines = diff_opt_context_lines(pOpt); skip = 0; a = b = 0; A = cx->aFrom; @@ -26743,23 +26741,23 @@ mxr = cx->nEdit; //MARKER(("contextLines=%u, nEdit = %d, mxr=%u\n", contextLines, cx->nEdit, mxr)); while( mxr>2 && R[mxr-1]==0 && R[mxr-2]==0 ){ mxr -= 3; } pBuilder->lnLHS = pBuilder->lnRHS = 0; - ++passNumber; if(pBuilder->start){ - pBuilder->passNumber = passNumber; + pBuilder->passNumber = ++passNumber; rc = pBuilder->start(pBuilder); RC; } + for(r=0; r0 && R[r+nr*3]<(int)contextLines*2; nr++){} #if 0 /* MISSING: this "should" be replaced by a stateful predicate - function, probably in the fsl_dibu_opt class. */ + function, probably in the fsl_diff_opt class. */ /* If there is a regex, skip this block (generate no diff output) ** if the regex matches or does not match both insert and delete. ** Only display the block if one side matches but the other side does ** not. */ @@ -26810,29 +26808,15 @@ nb += R[r+i*3]; } //MARKER(("Chunk header... a=%u, b=%u, na=%u, nb=%u, skip=%d\n", a, b, na, nb, skip)); if(pBuilder->chunkHeader - /* The following bit is a kludge to keep from injecting a chunk - header between chunks which are directly adjacent. - - The problem, however, is that we cannot skip _reliably_ - without also knowing how the next chunk aligns. If we skip - it here, the _previous_ chunk header may well be telling - the user a lie with regards to line numbers. - - Fossil itself does not have this issue because it generates - these chunk headers directly in this routine, instead of in - the diff builder, depending on a specific flag being set in - builder->opt. Also (related), in that implementation, fossil - will collapse chunks which are separated by less than the - context distance into contiguous chunks (see below). Because - we farm out the chunkHeader lines to the builder, we cannot - reliably do that here. - */ #if 0 - && !skip + /* The following two bits are a kludge to keep from injecting + a chunk header between chunks which are directly adjacent */ + && pBuilder->lnLHS != (uint32_t)(na ? a+skip+1 : a+skip)-1 + && pBuilder->lnRHS != (uint32_t)(nb ? b+skip+1 : b+skip)-1 #endif ){ rc = pBuilder->chunkHeader(pBuilder, (uint32_t)(na ? a+skip+1 : a+skip), (uint32_t)na, @@ -26852,14 +26836,12 @@ if( NULL==pBuilder->chunkHeader && skip<(int)contextLines ){ /* 2021-09-27: BUG: this is incompatible with unified diff format. The generated header lines say we're skipping X lines but we then end up including lines which that header says to skip. As a workaround, we'll only run this when - pBuilder->chunkHeader is NULL, noting that fossil's diff - builder interface does not have that method (and thus - doesn't have this issue, instead generating chunk headers - directly in this algorithm). + pBuilder->chunkHeader is NULL, noting that fossil's + diff builder interface does not have that method. Without this block, our "utxt" diff builder can mimic fossil's non-diff builder unified diff format, except that we add Index lines (feature or bug?). With this block, the header values output above are wrong. @@ -26891,21 +26873,19 @@ unsigned int nAlign; unsigned char *alignment = 0; ma = R[r+i*3+1]; /* Lines on left but not on right */ mb = R[r+i*3+2]; /* Lines on right but not on left */ -#if FSL_DIFF_SMALL_GAP - /* Try merging the current block with subsequent blocks, if the + /* Try merging the current block with subsequent blocks, if the ** subsequent blocks are nearby and their result isn't too big. */ while( i0; j++){ assert( jdeletion(pBuilder, &A[a]); if(rc) goto bail; ma--; a++; break; } case 2: { /* Insert one line on the right */ - METRIC(insertions); rc = pBuilder->insertion(pBuilder, &B[b]); if(rc) goto bail; assert( mb>0 ); mb--; b++; break; } case 3: { /* The left line is changed into the right line */ - if( 0==cx->cmpLine(&A[a], &B[b]) ){ + if( cx->cmpLine(&A[a], &B[b])==0 ){ rc = pBuilder->common(pBuilder, &A[a]); }else{ - METRIC(edits); rc = pBuilder->edit(pBuilder, &A[a], &B[b]); } if(rc) goto bail; assert( ma>0 && mb>0 ); ma--; @@ -26947,11 +26924,10 @@ b++; break; } case 4: { /* Delete from left then separately insert on the right */ - METRIC(replacements); rc = pBuilder->replacement(pBuilder, &A[a], &B[b]); if(rc) goto bail; ma--; a++; mb--; @@ -26992,11 +26968,10 @@ if( R[r]>(int)contextLines ){ rc = pBuilder->skip(pBuilder, R[r] - contextLines); } end: #undef RC -#undef METRIC if(0==rc){ if(pBuilder->finish) pBuilder->finish(pBuilder); if(pBuilder->twoPass && 1==passNumber){ goto pass_again; } @@ -27021,18 +26996,18 @@ case. Ownership of pBuilder is not changed. If pBuilder is not NULL then pBuilder->opt must be non-NULL. */ static int fsl_diff2_text_impl(fsl_buffer const *pA, fsl_buffer const *pB, - fsl_dibu * const pBuilder, - fsl_dibu_opt const * const opt_, + fsl_diff_builder * const pBuilder, + fsl_diff_opt const * const opt_, int ** outRaw){ int rc = 0; fsl__diff_cx c = fsl__diff_cx_empty; bool ignoreWs = false; int ansiOptCount = 0; - fsl_dibu_opt opt = *opt_ + fsl_diff_opt opt = *opt_ /*we need a copy for the sake of the FSL_DIFF2_INVERT flag*/; if(!pA || !pB || (pBuilder && outRaw)) return FSL_RC_MISUSE; blob_to_utf8_no_bom(pA, 0); blob_to_utf8_no_bom(pB, 0); @@ -27109,11 +27084,11 @@ pBuilder->out are not implemented here, e.g. DIFF_RAW. That last point makes this impl tiny compared to the original! */ if(pBuilder){ - fsl_dibu_opt * const oldOpt = pBuilder->opt; + fsl_diff_opt * const oldOpt = pBuilder->opt; pBuilder->opt = &opt; rc = fdb__format(&c, pBuilder); pBuilder->opt = oldOpt; } end: @@ -27125,42 +27100,44 @@ return rc; } int fsl_diff_v2(fsl_buffer const * pv1, fsl_buffer const * pv2, - fsl_dibu * const pBuilder){ + fsl_diff_builder * const pBuilder){ return fsl_diff2_text_impl(pv1, pv2, pBuilder, pBuilder->opt, NULL); } int fsl_diff_v2_raw(fsl_buffer const * pv1, fsl_buffer const * pv2, - fsl_dibu_opt const * const opt, + fsl_diff_opt const * const opt, int **outRaw ){ - return fsl_diff2_text_impl(pv1, pv2, NULL, - opt ? opt : &fsl_dibu_opt_empty, - outRaw); + return fsl_diff2_text_impl(pv1, pv2, NULL, opt, outRaw); } -fsl_dibu * fsl_dibu_alloc(fsl_size_t extra){ - fsl_dibu * rc = - (fsl_dibu*)fsl_malloc(sizeof(fsl_dibu) + extra); +/** + Allocator for fsl_diff_builder instances. If extra is >0 then that + much extra space is allocated as part of the same block and the + pimpl member of the returned object is pointed to that space. +*/ +static fsl_diff_builder * fsl__diff_builder_alloc(fsl_size_t extra){ + fsl_diff_builder * rc = + (fsl_diff_builder*)fsl_malloc(sizeof(fsl_diff_builder) + extra); if(rc){ - *rc = fsl_dibu_empty; + *rc = fsl_diff_builder_empty; if(extra){ - rc->pimpl = ((unsigned char *)rc)+sizeof(fsl_dibu); + rc->pimpl = ((unsigned char *)rc)+sizeof(fsl_diff_builder); } } return rc; } -static int fdb__out(fsl_dibu *const b, - char const *z, fsl_int_t n){ - if(n<0) n = (fsl_int_t)fsl_strlen(z); - return b->opt->out(b->opt->outState, z, (fsl_size_t)n); +static int fdb__out(fsl_diff_builder *const b, + char const *z, fsl_size_t n){ + return b->opt->out(b->opt->outState, z, n); } -static int fdb__outf(fsl_dibu * const b, +static int fdb__outf(fsl_diff_builder * const b, char const *fmt, ...){ int rc = 0; va_list va; assert(b->opt->out); va_start(va,fmt); @@ -27168,100 +27145,12 @@ va_end(va); return rc; } -/** - Column indexes for DiffCounter::cols. -*/ -enum DiffCounterCols { -DICO_NUM1 = 0, DICO_TEXT1, -DICO_MOD, -DICO_NUM2, DICO_TEXT2, -DICO_count -}; -/** - Internal state for the text-mode split diff builder. Used for - calculating column widths in the builder's first pass so that - the second pass can output everything in a uniform width. -*/ -struct DiffCounter { - /** - Largest column width we've yet seen. These are only updated for - DICO_TEXT1 and DICO_TEXT2. The others currently have fixed widths. - - FIXME: these are in bytes, not text columns. The current code may - truncate multibyte characters. - */ - uint32_t maxWidths[DICO_count]; - /** - Max line numbers seen for the LHS/RHS input files. This is likely - much higher than the number of diff lines. - - This can be used, e.g., to size and allocate a curses PAD in the - second pass of the start() method. - */ - uint32_t lineCount[2]; - /** - The actual number of lines needed for rendering the file. - */ - uint32_t displayLines; -}; -typedef struct DiffCounter DiffCounter; -static const DiffCounter DiffCounter_empty = {{1,10,3,1,10},{0,0},0}; -#define DICOSTATE(VNAME) DiffCounter * const VNAME = (DiffCounter *)b->pimpl - -static int maxColWidth(fsl_dibu const * const b, - DiffCounter const * const sst, - int mwIndex){ - static const short minColWidth = - 10/*b->opt.columnWidth values smaller than this are treated as - this value*/; - switch(mwIndex){ - case DICO_NUM1: - case DICO_NUM2: - case DICO_MOD: return sst->maxWidths[mwIndex]; - case DICO_TEXT1: case DICO_TEXT2: break; - default: - assert(!"internal API misuse: invalid column index."); - break; - } - int const y = - (b->opt->columnWidth>0 - && b->opt->columnWidth<=sst->maxWidths[mwIndex]) - ? (int)b->opt->columnWidth - : (int)sst->maxWidths[mwIndex]; - return minColWidth > y ? minColWidth : y; -} - -static void fdb__dico_update_maxlen(DiffCounter * const sst, - int col, - char const * const z, - uint32_t n){ - if(sst->maxWidths[col]maxWidths[col] = n; -#else - n = (uint32_t)fsl_strlen_utf8(z, (fsl_int_t)n); - if(sst->maxWidths[col]maxWidths[col] = n; -#endif - } -} - -static int fdb__debug_start(fsl_dibu * const b){ - int rc = fdb__outf(b, "DEBUG builder starting pass #%d.\n", - b->passNumber); - if(1==b->passNumber){ - DICOSTATE(sst); - *sst = DiffCounter_empty; - if(b->opt->nameLHS) ++sst->displayLines; - if(b->opt->nameRHS) ++sst->displayLines; - if(b->opt->hashLHS) ++sst->displayLines; - if(b->opt->hashRHS) ++sst->displayLines; - ++b->fileCount; - return rc; - } +static int fdb__debug_start(fsl_diff_builder * const b){ + int rc = fdb__outf(b, "DEBUG builder starting up.\n"); if(0==rc && b->opt->nameLHS){ rc = fdb__outf(b,"LHS: %s\n", b->opt->nameLHS); } if(0==rc && b->opt->nameRHS){ rc = fdb__outf(b,"RHS: %s\n", b->opt->nameRHS); @@ -27274,130 +27163,74 @@ } return rc; } -static int fdb__debug_chunkHeader(fsl_dibu* const b, +static int fdb__debug_chunkHeader(fsl_diff_builder* const b, uint32_t lnnoLHS, uint32_t linesLHS, uint32_t lnnoRHS, uint32_t linesRHS ){ #if 1 - if(1==b->passNumber){ - DICOSTATE(sst); - ++sst->displayLines; - return 0; - } - return fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32 - " +%" PRIu32 ",%" PRIu32 " @@\n", - lnnoLHS, linesLHS, lnnoRHS, linesRHS); -#else - return 0; -#endif -} - -static int fdb__debug_skip(fsl_dibu * const b, uint32_t n){ - if(1==b->passNumber){ - DICOSTATE(sst); - b->lnLHS += n; - b->lnRHS += n; - ++sst->displayLines; - return 0; - } - const int rc = fdb__outf(b, "SKIP %u (%u..%u left and %u..%u right)\n", - n, b->lnLHS+1, b->lnLHS+n, b->lnRHS+1, b->lnRHS+n); - b->lnLHS += n; - b->lnRHS += n; - return rc; -} -static int fdb__debug_common(fsl_dibu * const b, fsl_dline const * pLine){ - DICOSTATE(sst); - ++b->lnLHS; - ++b->lnRHS; - if(1==b->passNumber){ - ++sst->displayLines; - fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n); - fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n); - return 0; - } - return fdb__outf(b, "COMMON %8u %8u %.*s\n", - b->lnLHS, b->lnRHS, (int)pLine->n, pLine->z); -} -static int fdb__debug_insertion(fsl_dibu * const b, fsl_dline const * pLine){ - DICOSTATE(sst); - ++b->lnRHS; - if(1==b->passNumber){ - ++sst->displayLines; - fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n); - return 0; - } - return fdb__outf(b, "INSERT %8u %.*s\n", - b->lnRHS, (int)pLine->n, pLine->z); -} -static int fdb__debug_deletion(fsl_dibu * const b, fsl_dline const * pLine){ - DICOSTATE(sst); - ++b->lnLHS; - if(1==b->passNumber){ - ++sst->displayLines; - fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n); - return 0; - } - return fdb__outf(b, "DELETE %8u %.*s\n", - b->lnLHS, (int)pLine->n, pLine->z); -} -static int fdb__debug_replacement(fsl_dibu * const b, - fsl_dline const * lineLhs, - fsl_dline const * lineRhs) { -#if 0 - int rc = b->deletion(b, lineLhs); - if(0==rc) rc = b->insertion(b, lineRhs); - return rc; -#else - DICOSTATE(sst); - ++b->lnLHS; - ++b->lnRHS; - if(1==b->passNumber){ - ++sst->displayLines; - fdb__dico_update_maxlen(sst, DICO_TEXT1, lineLhs->z, lineLhs->n); - fdb__dico_update_maxlen(sst, DICO_TEXT2, lineRhs->z, lineRhs->n); - return 0; - } - int rc = fdb__outf(b, "REPLACE %8u %.*s\n", - b->lnLHS, (int)lineLhs->n, lineLhs->z); - if(!rc){ - rc = fdb__outf(b, " %8u %.*s\n", - b->lnRHS, (int)lineRhs->n, lineRhs->z); - } - return rc; -#endif -} - -static int fdb__debug_edit(fsl_dibu * const b, - fsl_dline const * lineLHS, - fsl_dline const * lineRHS){ -#if 0 - int rc = b->deletion(b, lineLHS); - if(0==rc) rc = b->insertion(b, lineRHS); - return rc; -#else - int rc = 0; - DICOSTATE(sst); - ++b->lnLHS; - ++b->lnRHS; - if(1==b->passNumber){ - sst->displayLines += 4 - /* this is actually 3 or 4, but we don't know that from here */; - fdb__dico_update_maxlen(sst, DICO_TEXT1, lineLHS->z, lineLHS->n); - fdb__dico_update_maxlen(sst, DICO_TEXT2, lineRHS->z, lineRHS->n); - return 0; - } + return fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32 + " +%" PRIu32 ",%" PRIu32 " @@\n", + lnnoLHS, linesLHS, lnnoRHS, linesRHS); +#else + return 0; +#endif +} + +static int fdb__debug_skip(fsl_diff_builder * const p, uint32_t n){ + const int rc = fdb__outf(p, "SKIP %u (%u..%u left and %u..%u right)\n", + n, p->lnLHS+1, p->lnLHS+n, p->lnRHS+1, p->lnRHS+n); + p->lnLHS += n; + p->lnRHS += n; + return rc; +} +static int fdb__debug_common(fsl_diff_builder * const p, fsl_dline const * pLine){ + ++p->lnLHS; + ++p->lnRHS; + return fdb__outf(p, "COMMON %8u %8u %.*s\n", + p->lnLHS, p->lnRHS, (int)pLine->n, pLine->z); +} +static int fdb__debug_insertion(fsl_diff_builder * const p, fsl_dline const * pLine){ + p->lnRHS++; + return fdb__outf(p, "INSERT %8u %.*s\n", + p->lnRHS, (int)pLine->n, pLine->z); +} +static int fdb__debug_deletion(fsl_diff_builder * const p, fsl_dline const * pLine){ + p->lnLHS++; + return fdb__outf(p, "DELETE %8u %.*s\n", + p->lnLHS, (int)pLine->n, pLine->z); +} +static int fdb__debug_replacement(fsl_diff_builder * const p, + fsl_dline const * lineLhs, + fsl_dline const * lineRhs) { + int rc; + p->lnLHS++; + p->lnRHS++; + rc = fdb__outf(p, "REPLACE %8u %.*s\n", + p->lnLHS, (int)lineLhs->n, lineLhs->z); + if(!rc){ + rc = fdb__outf(p, " %8u %.*s\n", + p->lnRHS, (int)lineRhs->n, lineRhs->z); + } + return rc; +} + +static int fdb__debug_edit(fsl_diff_builder * const b, + fsl_dline const * pX, + fsl_dline const * pY){ + int rc = 0; int i, j; int x; fsl_dline_change chng = fsl_dline_change_empty; #define RC if(rc) goto end + b->lnLHS++; + b->lnRHS++; rc = fdb__outf(b, "EDIT %8u %.*s\n", - b->lnLHS, (int)lineLHS->n, lineLHS->z); + b->lnLHS, (int)pX->n, pX->z); RC; - fsl_dline_change_spans(lineLHS, lineRHS, &chng); + fsl_dline_change_spans(pX, pY, &chng); for(i=x=0; i x ){ - if( (lineLHS->z[x]&0xc0)!=0x80 ){ + if( (pX->z[x]&0xc0)!=0x80 ){ rc = fdb__out(b, " ", 1); RC; } x++; } for(j=0; jz[x]&0xc0)!=0x80 ){ + if( (pX->z[x]&0xc0)!=0x80 ){ rc = fdb__out(b, &c, 1); RC; } } } @@ -27423,11 +27256,11 @@ if( x ){ rc = fdb__out(b, "\n", 1); RC; } rc = fdb__outf(b, " %8u %.*s\n", - b->lnRHS, (int)lineRHS->n, lineRHS->z); + b->lnRHS, (int)pY->n, pY->z); RC; for(i=x=0; i x ){ - if( (lineRHS->z[x]&0xc0)!=0x80 ){ + if( (pY->z[x]&0xc0)!=0x80 ){ rc = fdb__out(b, " ", 1); RC; } x++; } for(j=0; jz[x]&0xc0)!=0x80 ){ + if( (pY->z[x]&0xc0)!=0x80 ){ rc = fdb__out(b, &c, 1); RC; } } } @@ -27455,41 +27288,23 @@ rc = fdb__out(b, "\n", 1); } end: #undef RC return rc; -#endif -} - -static int fdb__debug_finish(fsl_dibu * const b){ - DICOSTATE(sst); - if(1==b->passNumber){ - sst->lineCount[0] = b->lnLHS; - sst->lineCount[1] = b->lnRHS; - return 0; - } - int rc = fdb__outf(b, "END with %u LHS file lines " - "and %u RHS lines (max. %u display lines)\n", - b->lnLHS, b->lnRHS, sst->displayLines); - if(0==rc){ - rc = fdb__outf(b,"Col widths: num left=%u, col left=%u, " - "modifier=%u, num right=%u, col right=%u\n", - sst->maxWidths[0], sst->maxWidths[1], - sst->maxWidths[2], sst->maxWidths[3], - sst->maxWidths[4]); - } - return rc; -} - -void fsl_dibu_finalizer(fsl_dibu * const b){ - *b = fsl_dibu_empty; +} + +static int fdb__debug_finish(fsl_diff_builder * const b){ + return fdb__outf(b, "END with %u lines left and %u lines right\n", + b->lnLHS, b->lnRHS); +} + +static void fdb__generic_finalize(fsl_diff_builder * const b){ fsl_free(b); } -static fsl_dibu * fsl__diff_builder_debug(void){ - fsl_dibu * rc = - fsl_dibu_alloc((fsl_size_t)sizeof(DiffCounter)); +static fsl_diff_builder * fsl__diff_builder_debug(void){ + fsl_diff_builder * rc = fsl__diff_builder_alloc(0); if(rc){ rc->chunkHeader = fdb__debug_chunkHeader; rc->start = fdb__debug_start; rc->skip = fdb__debug_skip; rc->common = fdb__debug_common; @@ -27496,15 +27311,12 @@ rc->insertion = fdb__debug_insertion; rc->deletion = fdb__debug_deletion; rc->replacement = fdb__debug_replacement; rc->edit = fdb__debug_edit; rc->finish = fdb__debug_finish; - rc->finalize = fsl_dibu_finalizer; - rc->twoPass = true; - assert(0!=rc->pimpl); - DiffCounter * const sst = (DiffCounter*)rc->pimpl; - *sst = DiffCounter_empty; + rc->finalize = fdb__generic_finalize; + assert(!rc->pimpl); assert(0==rc->implFlags); assert(0==rc->lnLHS); assert(0==rc->lnRHS); assert(NULL==rc->opt); } @@ -27532,18 +27344,18 @@ ** represent common-text, left-text, and right-text. The last string ** in SUBARRAY is the common-suffix. Any string can be empty if it does ** not apply. */ -static int fdb__outj(fsl_dibu * const b, +static int fdb__outj(fsl_diff_builder * const b, char const *zJson, int n){ return n<0 ? fdb__outf(b, "%!j", zJson) : fdb__outf(b, "%!.*j", n, zJson); } -static int fdb__json1_start(fsl_dibu * const b){ +static int fdb__json1_start(fsl_diff_builder * const b){ int rc = fdb__outf(b, "{\"hashLHS\": %!j, \"hashRHS\": %!j, ", b->opt->hashLHS, b->opt->hashRHS); if(0==rc && b->opt->nameLHS){ rc = fdb__outf(b, "\"nameLHS\": %!j, ", b->opt->nameLHS); } @@ -27554,38 +27366,38 @@ rc = fdb__out(b, "\"diff\":[", 8); } return rc; } -static int fdb__json1_skip(fsl_dibu * const b, uint32_t n){ +static int fdb__json1_skip(fsl_diff_builder * const b, uint32_t n){ return fdb__outf(b, "1,%" PRIu32 ",\n", n); } -static int fdb__json1_common(fsl_dibu * const b, fsl_dline const * pLine){ +static int fdb__json1_common(fsl_diff_builder * const b, fsl_dline const * pLine){ int rc = fdb__out(b, "2,",2); if(!rc) { rc = fdb__outj(b, pLine->z, (int)pLine->n); if(!rc) rc = fdb__out(b, ",\n",2); } return rc; } -static int fdb__json1_insertion(fsl_dibu * const b, fsl_dline const * pLine){ +static int fdb__json1_insertion(fsl_diff_builder * const b, fsl_dline const * pLine){ int rc = fdb__out(b, "3,",2); if(!rc){ rc = fdb__outj(b, pLine->z, (int)pLine->n); if(!rc) rc = fdb__out(b, ",\n",2); } return rc; } -static int fdb__json1_deletion(fsl_dibu * const b, fsl_dline const * pLine){ +static int fdb__json1_deletion(fsl_diff_builder * const b, fsl_dline const * pLine){ int rc = fdb__out(b, "4,",2); if(!rc){ rc = fdb__outj(b, pLine->z, (int)pLine->n); if(!rc) rc = fdb__out(b, ",\n",2); } return rc; } -static int fdb__json1_replacement(fsl_dibu * const b, +static int fdb__json1_replacement(fsl_diff_builder * const b, fsl_dline const * lineLhs, fsl_dline const * lineRhs) { int rc = fdb__out(b, "5,[\"\",",6); if(!rc) rc = fdb__outf(b,"%!.*j", (int)lineLhs->n, lineLhs->z); if(!rc) rc = fdb__out(b, ",", 1); @@ -27592,47 +27404,44 @@ if(!rc) rc = fdb__outf(b,"%!.*j", (int)lineRhs->n, lineRhs->z); if(!rc) rc = fdb__out(b, ",\"\"],\n",6); return rc; } -static int fdb__json1_edit(fsl_dibu * const b, - fsl_dline const * lineLHS, - fsl_dline const * lineRHS){ +static int fdb__json1_edit(fsl_diff_builder * const b, + fsl_dline const * pX, + fsl_dline const * pY){ int rc = 0; int i,x; fsl_dline_change chng = fsl_dline_change_empty; #define RC if(rc) goto end rc = fdb__out(b, "5,[", 3); RC; - fsl_dline_change_spans(lineLHS, lineRHS, &chng); + fsl_dline_change_spans(pX, pY, &chng); for(i=x=0; i<(int)chng.n; i++){ - if(i>0){ - rc = fdb__out(b, ",", 1); RC; - } - rc = fdb__outj(b, lineLHS->z + x, (int)chng.a[i].iStart1 - x); RC; + rc = fdb__outj(b, pX->z + x, (int)chng.a[i].iStart1 - x); RC; x = chng.a[i].iStart1; rc = fdb__out(b, ",", 1); RC; - rc = fdb__outj(b, lineLHS->z + x, (int)chng.a[i].iLen1); RC; + rc = fdb__outj(b, pX->z + x, (int)chng.a[i].iLen1); RC; x += chng.a[i].iLen1; rc = fdb__out(b, ",", 1); RC; - rc = fdb__outj(b, lineRHS->z + chng.a[i].iStart2, + rc = fdb__outj(b, pY->z + chng.a[i].iStart2, (int)chng.a[i].iLen2); RC; } rc = fdb__out(b, ",", 1); RC; - rc = fdb__outj(b, lineLHS->z + x, (int)(lineLHS->n - x)); RC; + rc = fdb__outj(b, pX->z + x, (int)(pX->n - x)); RC; rc = fdb__out(b, "],\n",3); RC; end: return rc; #undef RC } -static int fdb__json1_finish(fsl_dibu * const b){ +static int fdb__json1_finish(fsl_diff_builder * const b){ return fdb__out(b, "0]}", 3); } -static fsl_dibu * fsl__diff_builder_json1(void){ - fsl_dibu * rc = fsl_dibu_alloc(0); +static fsl_diff_builder * fsl__diff_builder_json1(void){ + fsl_diff_builder * rc = fsl__diff_builder_alloc(0); if(rc){ rc->chunkHeader = NULL; rc->start = fdb__json1_start; rc->skip = fdb__json1_skip; rc->common = fdb__json1_common; @@ -27639,58 +27448,22 @@ rc->insertion = fdb__json1_insertion; rc->deletion = fdb__json1_deletion; rc->replacement = fdb__json1_replacement; rc->edit = fdb__json1_edit; rc->finish = fdb__json1_finish; - rc->finalize = fsl_dibu_finalizer; + rc->finalize = fdb__generic_finalize; assert(!rc->pimpl); assert(0==rc->implFlags); assert(0==rc->lnLHS); assert(0==rc->lnRHS); assert(NULL==rc->opt); } return rc; } -/** - State for the text-mode unified(-ish) diff builder. We do some - hoop-jumping here in order to combine runs of delete/insert pairs - into a group of deletes followed by a group of inserts. It's a - cosmetic detail only but it makes for more readable output. -*/ -struct DiBuUnified { - /** True if currently processing a block of deletes, else false. */ - bool deleting; - /** Buffer for insertion lines which are part of delete/insert - pairs. */ - fsl_buffer bufIns; -}; -typedef struct DiBuUnified DiBuUnified; - -#define UIMPL(V) DiBuUnified * const V = (DiBuUnified*)b->pimpl -/** - If utxt diff builder b has any INSERT lines to flush, this - flushes them. Sets b->impl->deleting to false. Returns non-0 - on output error. -*/ -static int fdb__utxt_flush_ins(fsl_dibu * const b){ - int rc = 0; - UIMPL(p); - p->deleting = false; - if(p->bufIns.used>0){ - rc = fdb__out(b, fsl_buffer_cstr(&p->bufIns), p->bufIns.used); - fsl_buffer_reuse(&p->bufIns); - } - return rc; -} - -static int fdb__utxt_start(fsl_dibu * const b){ - int rc = 0; - UIMPL(p); - p->deleting = false; - if(p->bufIns.mem) fsl_buffer_reuse(&p->bufIns); - else fsl_buffer_reserve(&p->bufIns, 1024 * 2); +static int fdb__utxt_start(fsl_diff_builder * const b){ + int rc = 0; if(0==(FSL_DIFF2_NOINDEX & b->opt->diffFlags)){ rc = fdb__outf(b,"Index: %s\n%.66c\n", b->opt->nameLHS/*RHS?*/, '='); } if(0==rc){ @@ -27698,252 +27471,144 @@ b->opt->nameLHS, b->opt->nameRHS); } return rc; } -static int fdb__utxt_chunkHeader(fsl_dibu* const b, +static int fdb__utxt_chunkHeader(fsl_diff_builder* const b, uint32_t lnnoLHS, uint32_t linesLHS, uint32_t lnnoRHS, uint32_t linesRHS ){ - /* - Annoying cosmetic bug: the libf impl of this diff will sometimes - render two directly-adjecent chunks with a separator, e.g.: - */ - - // $ f-vdiff --forat u 072d63965188 a725befe5863 -l '*vdiff*' | head -30 - // Index: f-apps/f-vdiff.c - // ================================================================== - // --- f-apps/f-vdiff.c - // +++ f-apps/f-vdiff.c - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // 36 36 fsl_buffer fname; - // 37 37 fsl_buffer fcontent1; - // 38 38 fsl_buffer fcontent2; - // 39 39 fsl_buffer fhash; - // 40 40 fsl_list globs; - // 41 + fsl_dibu_opt diffOpt; - // 42 + fsl_diff_builder * diffBuilder; - // 41 43 } VDiffApp = { - // 42 44 NULL/*glob*/, - // 43 45 5/*contextLines*/, - // 44 46 0/*sbsWidth*/, - // 45 47 0/*diffFlags*/, - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // 46 48 0/*brief*/, - // 47 49 fsl_buffer_empty_m/*fname*/, - // 48 50 fsl_buffer_empty_m/*fcontent1*/, - - /* - Note now the chunks before/after the second ~~~ line are - consecutive lines of code. In fossil(1) that case is accounted for - in the higher-level diff engine, which can not only collapse - adjacent blocks but also does the rendering of chunk headers in - that main algorithm (something we cannot do in the library because - we need the fsl_dibu to be able to output to arbitrary - distinations). We can only _partially_ account for it here, - eliminating the extraneous ~~~ line when we're in line-number - mode. In non-line-number mode we have to output the chunk header - as-is. If we skip it then the _previous_ chunk header, if any, - will contain incorrect numbers for the chunk, invaliding the diff - for purposes of tools which import unified-format diffs. - */ - int rc = fdb__utxt_flush_ins(b); - if(0==rc){ - if(FSL_DIFF2_LINE_NUMBERS & b->opt->diffFlags){ - rc = (lnnoLHS == b->lnLHS+1 && lnnoRHS == b->lnRHS+1) - ? 0 - : fdb__outf(b, "%.40c\n", '~'); - }else{ - rc = fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32 + if(FSL_DIFF2_LINE_NUMBERS & b->opt->diffFlags){ + return fdb__outf(b, "%.40c\n", '~'); + }else{ + return fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32 " +%" PRIu32 ",%" PRIu32 " @@\n", lnnoLHS, linesLHS, lnnoRHS, linesRHS); - } } - return rc; } -static int fdb__utxt_skip(fsl_dibu * const b, uint32_t n){ +static int fdb__utxt_skip(fsl_diff_builder * const b, uint32_t n){ //MARKER(("SKIP\n")); - int rc = fdb__utxt_flush_ins(b); b->lnLHS += n; b->lnRHS += n; - return rc; + return 0; } -/** - Outputs line numbers, if configured to, to b->opt->out. - - - 2 line numbers = common lines - - lnL only = deletion - - lnR only = insertion -*/ -static int fdb__utxt_lineno(fsl_dibu * const b, uint32_t lnL, uint32_t lnR){ +/** Outputs line numbers to b->opt->out. */ +static int fdb__utxt_lineno(fsl_diff_builder * const b, uint32_t lnL, uint32_t lnR){ int rc = 0; if(FSL_DIFF2_LINE_NUMBERS & b->opt->diffFlags){ - UIMPL(p); - if(lnL){ // common or delete - rc = fdb__outf(b, "%s%6" PRIu32 "%s ", - (lnR ? "" : b->opt->ansiColor.deletion), - lnL, - (lnR ? "" : b->opt->ansiColor.reset)); - }else if(p->deleting){ // insert during deletion grouping - rc = fsl_buffer_append(&p->bufIns, " ", 7); - }else{ // insert w/o deleting grouping - rc = fdb__out(b, " ", 7); - } - if(0==rc){ - if(!lnL && lnR && p->deleting){ // insert during deletion grouping - rc = fsl_buffer_appendf(&p->bufIns, "%s%6" PRIu32 "%s ", - b->opt->ansiColor.insertion, - lnR, b->opt->ansiColor.reset); - }else if(lnR){ // common or insert w/o deletion grouping. - rc = fdb__outf(b, "%s%6" PRIu32 "%s ", - (lnL ? "" : b->opt->ansiColor.insertion), - lnR, - (lnL ? "" : b->opt->ansiColor.reset)); - }else{ // deletion - rc = fdb__out(b, " ", 7); - } - } - } - return rc; -} - -static int fdb__utxt_common(fsl_dibu * const b, fsl_dline const * pLine){ - //MARKER(("COMMON\n")); - int rc = fdb__utxt_flush_ins(b); - if(0==rc){ - ++b->lnLHS; - ++b->lnRHS; - rc = fdb__utxt_lineno(b, b->lnLHS, b->lnRHS); - } + rc = lnL + ? fdb__outf(b, "%s%6" PRIu32 "%s ", + (lnR ? "" : b->opt->ansiColor.deletion), + lnL, + (lnR ? "" : b->opt->ansiColor.reset)) + : fdb__out(b, " ", 7); + if(0==rc){ + rc = lnR + ? fdb__outf(b, "%s%6" PRIu32 "%s ", + (lnL ? "" : b->opt->ansiColor.insertion), + lnR, + (lnL ? "" : b->opt->ansiColor.reset)) + : fdb__out(b, " ", 7); + } + } + return rc; +} + +static int fdb__utxt_common(fsl_diff_builder * const b, fsl_dline const * pLine){ + //MARKER(("COMMON\n")); + ++b->lnLHS; + ++b->lnRHS; + const int rc = fdb__utxt_lineno(b, b->lnLHS, b->lnRHS); return rc ? rc : fdb__outf(b, " %.*s\n", (int)pLine->n, pLine->z); } - -static int fdb__utxt_insertion(fsl_dibu * const b, fsl_dline const * pLine){ +static int fdb__utxt_insertion(fsl_diff_builder * const b, fsl_dline const * pLine){ //MARKER(("INSERT\n")); - int rc; ++b->lnRHS; - rc = fdb__utxt_lineno(b, 0, b->lnRHS); - if(0==rc){ - UIMPL(p); - if(p->deleting){ - rc = fsl_buffer_appendf(&p->bufIns, "%s+%.*s%s\n", - b->opt->ansiColor.insertion, - (int)pLine->n, pLine->z, - b->opt->ansiColor.reset); - }else{ - rc = fdb__outf(b, "%s+%.*s%s\n", - b->opt->ansiColor.insertion, - (int)pLine->n, pLine->z, - b->opt->ansiColor.reset); - } - } - return rc; -} -static int fdb__utxt_deletion(fsl_dibu * const b, fsl_dline const * pLine){ + const int rc = fdb__utxt_lineno(b, 0, b->lnRHS); + return rc ? rc : fdb__outf(b, "%s+%.*s%s\n", + b->opt->ansiColor.insertion, + (int)pLine->n, pLine->z, + b->opt->ansiColor.reset); +} +static int fdb__utxt_deletion(fsl_diff_builder * const b, fsl_dline const * pLine){ //MARKER(("DELETE\n")); - UIMPL(p); - int rc = p->deleting ? 0 : fdb__utxt_flush_ins(b); - if(0==rc){ - p->deleting = true; - ++b->lnLHS; - rc = fdb__utxt_lineno(b, b->lnLHS, 0); - } + ++b->lnLHS; + const int rc = fdb__utxt_lineno(b, b->lnLHS, 0); return rc ? rc : fdb__outf(b, "%s-%.*s%s\n", b->opt->ansiColor.deletion, (int)pLine->n, pLine->z, b->opt->ansiColor.reset); } -static int fdb__utxt_replacement(fsl_dibu * const b, +static int fdb__utxt_replacement(fsl_diff_builder * const b, fsl_dline const * lineLhs, fsl_dline const * lineRhs) { //MARKER(("REPLACE\n")); int rc = b->deletion(b, lineLhs); if(0==rc) rc = b->insertion(b, lineRhs); return rc; } -static int fdb__utxt_edit(fsl_dibu * const b, +static int fdb__utxt_edit(fsl_diff_builder * const b, fsl_dline const * lineLhs, fsl_dline const * lineRhs){ //MARKER(("EDIT\n")); int rc = b->deletion(b, lineLhs); if(0==rc) rc = b->insertion(b, lineRhs); return rc; } -static int fdb__utxt_finish(fsl_dibu * const b){ - int rc = fdb__utxt_flush_ins(b); - UIMPL(p); - fsl_buffer_reuse(&p->bufIns); - return rc; -} - -static void fdb__utxt_finalize(fsl_dibu * const b){ - UIMPL(p); - fsl_buffer_clear(&p->bufIns); +static void fdb__utxt_finalize(fsl_diff_builder * const b){ fsl_free(b); } -static fsl_dibu * fsl__diff_builder_utxt(void){ - const DiBuUnified DiBuUnified_empty = { - false, fsl_buffer_empty_m - }; - fsl_dibu * rc = fsl_dibu_alloc(sizeof(DiBuUnified)); +static fsl_diff_builder * fsl__diff_builder_utxt(void){ + fsl_diff_builder * rc = fsl__diff_builder_alloc(0); if(!rc) return NULL; - assert(NULL!=rc->pimpl); - assert(NULL==rc->finally); - *((DiBuUnified*)rc->pimpl) = DiBuUnified_empty; rc->chunkHeader = fdb__utxt_chunkHeader; rc->start = fdb__utxt_start; rc->skip = fdb__utxt_skip; rc->common = fdb__utxt_common; rc->insertion = fdb__utxt_insertion; rc->deletion = fdb__utxt_deletion; rc->replacement = fdb__utxt_replacement; rc->edit = fdb__utxt_edit; - rc->finish = fdb__utxt_finish; + rc->finish = NULL; rc->finalize = fdb__utxt_finalize; return rc; } -#undef UIMPL struct DiBuTcl { /** Buffer for TCL-format string conversion */ fsl_buffer str; }; typedef struct DiBuTcl DiBuTcl; static const DiBuTcl DiBuTcl_empty = {fsl_buffer_empty_m}; -#define BR_OPEN if(FSL_DIBU_TCL_BRACES & b->implFlags) \ +#define BR_OPEN if(FSL_DIFF2_TCL_BRACES & b->opt->diffFlags) \ rc = fdb__out(b, "{", 1) -#define BR_CLOSE if(FSL_DIBU_TCL_BRACES & b->implFlags) \ +#define BR_CLOSE if(FSL_DIFF2_TCL_BRACES & b->opt->diffFlags) \ rc = fdb__out(b, "}", 1) #define DTCL_BUFFER(B) &((DiBuTcl*)(B)->pimpl)->str -static int fdb__outtcl(fsl_dibu * const b, +static int fdb__outtcl(fsl_diff_builder * const b, char const *z, unsigned int n, char chAppend ){ int rc; fsl_buffer * const o = DTCL_BUFFER(b); fsl_buffer_reuse(o); - rc = fsl_buffer_append_tcl_literal(o, - (b->implFlags & FSL_DIBU_TCL_BRACES_ESC), - z, n); + rc = fsl_buffer_append_tcl_literal(o, z, n); if(0==rc) rc = fdb__out(b, (char const *)o->mem, o->used); if(chAppend && 0==rc) rc = fdb__out(b, &chAppend, 1); return rc; } -static int fdb__tcl_start(fsl_dibu * const b){ +static int fdb__tcl_start(fsl_diff_builder * const b){ int rc = 0; fsl_buffer_reuse(DTCL_BUFFER(b)); - if(1==++b->fileCount && - FSL_DIBU_TCL_TK==(b->implFlags & FSL_DIBU_TCL_TK)){ - rc = fdb__out(b, "set difftxt {\n", -1); - } - if(0==rc && b->fileCount>1) rc = fdb__out(b, "\n", 1); + BR_OPEN; + if(0==rc) rc = fdb__out(b, "\n", 1); if(0==rc && b->opt->nameLHS){ char const * zRHS = b->opt->nameRHS ? b->opt->nameRHS : b->opt->nameLHS; BR_OPEN; if(0==rc) rc = fdb__out(b, "FILE ", 5); @@ -27955,47 +27620,47 @@ if(0==rc) rc = fdb__out(b, "\n", 1); } return rc; } -static int fdb__tcl_skip(fsl_dibu * const b, uint32_t n){ +static int fdb__tcl_skip(fsl_diff_builder * const b, uint32_t n){ int rc = 0; BR_OPEN; if(0==rc) rc = fdb__outf(b, "SKIP %" PRIu32, n); if(0==rc) {BR_CLOSE;} if(0==rc) rc = fdb__outf(b, "\n", 1); return rc; } -static int fdb__tcl_common(fsl_dibu * const b, fsl_dline const * pLine){ +static int fdb__tcl_common(fsl_diff_builder * const b, fsl_dline const * pLine){ int rc = 0; BR_OPEN; if(0==rc) rc = fdb__out(b, "COM ", 5); if(0==rc) rc= fdb__outtcl(b, pLine->z, pLine->n, 0); if(0==rc) {BR_CLOSE;} if(0==rc) rc = fdb__outf(b, "\n", 1); return rc; } -static int fdb__tcl_insertion(fsl_dibu * const b, fsl_dline const * pLine){ +static int fdb__tcl_insertion(fsl_diff_builder * const b, fsl_dline const * pLine){ int rc = 0; BR_OPEN; if(0==rc) rc = fdb__out(b, "INS ", 5); if(0==rc) rc = fdb__outtcl(b, pLine->z, pLine->n, 0); if(0==rc) {BR_CLOSE;} if(0==rc) rc = fdb__outf(b, "\n", 1); return rc; } -static int fdb__tcl_deletion(fsl_dibu * const b, fsl_dline const * pLine){ +static int fdb__tcl_deletion(fsl_diff_builder * const b, fsl_dline const * pLine){ int rc = 0; BR_OPEN; if(0==rc) rc = fdb__out(b, "DEL ", 5); if(0==rc) rc = fdb__outtcl(b, pLine->z, pLine->n, 0); if(0==rc) {BR_CLOSE;} if(0==rc) rc = fdb__outf(b, "\n", 1); return rc; } -static int fdb__tcl_replacement(fsl_dibu * const b, +static int fdb__tcl_replacement(fsl_diff_builder * const b, fsl_dline const * lineLhs, fsl_dline const * lineRhs) { int rc = 0; BR_OPEN; if(0==rc) rc = fdb__out(b, "EDIT \"\" ", 8); @@ -28004,73 +27669,61 @@ if(0==rc) {BR_CLOSE;} if(0==rc) rc = fdb__outf(b, "\n", 1); return rc; } -static int fdb__tcl_edit(fsl_dibu * const b, - fsl_dline const * lineLHS, - fsl_dline const * lineRHS){ +static int fdb__tcl_edit(fsl_diff_builder * const b, + fsl_dline const * pX, + fsl_dline const * pY){ int rc = 0; int i, x; fsl_dline_change chng = fsl_dline_change_empty; #define RC if(rc) goto end BR_OPEN; rc = fdb__out(b, "EDIT", 4); RC; - fsl_dline_change_spans(lineLHS, lineRHS, &chng); + fsl_dline_change_spans(pX, pY, &chng); for(i=x=0; iz + x, chng.a[i].iStart1 - x, ' '); RC; + rc = fdb__outtcl(b, pX->z + x, chng.a[i].iStart1 - x, ' '); RC; x = chng.a[i].iStart1; - rc = fdb__outtcl(b, lineLHS->z + x, chng.a[i].iLen1, ' '); RC; + rc = fdb__outtcl(b, pX->z + x, chng.a[i].iLen1, ' '); RC; x += chng.a[i].iLen1; - rc = fdb__outtcl(b, lineRHS->z + chng.a[i].iStart2, + rc = fdb__outtcl(b, pY->z + chng.a[i].iStart2, chng.a[i].iLen2, 0); RC; } assert(0==rc); - if( x < lineLHS->n ){ + if( x < pX->n ){ rc = fdb__out(b, " ", 1); RC; - rc = fdb__outtcl(b, lineLHS->z + x, lineLHS->n - x, 0); RC; + rc = fdb__outtcl(b, pX->z + x, pX->n - x, 0); RC; } BR_CLOSE; RC; rc = fdb__out(b, "\n", 1); end: #undef RC return rc; } -static int fdb__tcl_finish(fsl_dibu * const b){ +static int fdb__tcl_finish(fsl_diff_builder * const b){ int rc = 0; -#if 0 BR_CLOSE; - if(0==rc && FSL_DIBU_TCL_BRACES & b->implFlags){ + if(0==rc && FSL_DIFF2_TCL_BRACES & b->opt->diffFlags){ rc = fdb__out(b, "\n", 1); } -#endif return rc; } -static int fdb__tcl_finally(fsl_dibu * const b){ - int rc = 0; - if(FSL_DIBU_TCL_TK==(b->implFlags & FSL_DIBU_TCL_TK)){ - extern char const * fsl_difftk_cstr; - rc = fdb__out(b, "}\nset fossilcmd {}\n", -1); - if(0==rc) fdb__out(b, fsl_difftk_cstr, -1); - } - return rc; -} - #undef BR_OPEN #undef BR_CLOSE -static void fdb__tcl_finalize(fsl_dibu * const b){ +static void fdb__tcl_finalize(fsl_diff_builder * const b){ fsl_buffer_clear( &((DiBuTcl*)b->pimpl)->str ); - *b = fsl_dibu_empty; + *b = fsl_diff_builder_empty; fsl_free(b); } -static fsl_dibu * fsl__diff_builder_tcl(void){ - fsl_dibu * rc = - fsl_dibu_alloc((fsl_size_t)sizeof(DiBuTcl)); +static fsl_diff_builder * fsl__diff_builder_tcl(void){ + fsl_diff_builder * rc = + fsl__diff_builder_alloc((fsl_size_t)sizeof(DiBuTcl)); if(rc){ rc->chunkHeader = NULL; rc->start = fdb__tcl_start; rc->skip = fdb__tcl_skip; rc->common = fdb__tcl_common; @@ -28077,11 +27730,10 @@ rc->insertion = fdb__tcl_insertion; rc->deletion = fdb__tcl_deletion; rc->replacement = fdb__tcl_replacement; rc->edit = fdb__tcl_edit; rc->finish = fdb__tcl_finish; - rc->finally = fdb__tcl_finally; rc->finalize = fdb__tcl_finalize; assert(0!=rc->pimpl); DiBuTcl * const dbt = (DiBuTcl*)rc->pimpl; *dbt = DiBuTcl_empty; if(fsl_buffer_reserve(&dbt->str, 120)){ @@ -28090,38 +27742,100 @@ } } return rc; } -static int fdb__splittxt_mod(fsl_dibu * const b, char ch){ +/** + Column indexes for SplitText::cols. +*/ +enum SplitTextCols { +STC_NUM1 = 0, STC_TEXT1, +STC_MOD, +STC_NUM2, STC_TEXT2, +STC_count +}; +/** + Internal state for the text-mode split diff builder. + + This builder buffers its contents in 5 buffers: 2 each for the + LHS/RHS line numbers and content and one for the "change marker" (a + center column). Each of the STC_NUM1, STC_NUM2, STC_TEXT1, and + STC_TEXT2 columns is stored as one NUL-delimited string in each of + the corresponding column buffers. STC_MOD is a simple byte array, + with each byte corresponding two one line of the diff and marking + what type of linle it is (common, insertion, deletion, or + edit/replacement). + + The STC_SKIP column is managed differently. It is zero-filled, + with a non-0 value at each line of the diff which represents a + skipped gap. Potential TODO: combine this and STC_MOD. +*/ +struct SplitTxt { + /** + Largest column width we've yet seen. These are only updated for + STC_TEXT1 and STC_TEXT2. The others currently have fixed widths. + + FIXME: these are in bytes, not text columns. The current code may + truncate multibyte characters. + */ + uint32_t maxWidths[STC_count]; +}; +typedef struct SplitTxt SplitTxt; +static const SplitTxt SplitTxt_empty = {{1,10,3,1,10}}; +#define SPLITSTATE(VNAME) SplitTxt * const VNAME = (SplitTxt *)b->pimpl + +static int maxColWidth(fsl_diff_builder const * const b, + SplitTxt const * const sst, + int mwIndex){ + static const short minColWidth = + 10/*b->opt.columnWidth values smaller than this are treated as + this value*/; + switch(mwIndex){ + case STC_NUM1: + case STC_NUM2: + case STC_MOD: return sst->maxWidths[mwIndex]; + case STC_TEXT1: case STC_TEXT2: break; + default: + assert(!"internal API misuse: invalid column index."); + break; + } + int const y = + (b->opt->columnWidth>0 + && b->opt->columnWidth<=sst->maxWidths[mwIndex]) + ? (int)b->opt->columnWidth + : (int)sst->maxWidths[mwIndex]; + return minColWidth > y ? minColWidth : y; +} + +static int fdb__splittxt_mod(fsl_diff_builder * const b, char ch){ assert(2==b->passNumber); return fdb__outf(b, " %c ", ch); } -static int fdb__splittxt_lineno(fsl_dibu * const b, - DiffCounter const * const sst, +static int fdb__splittxt_lineno(fsl_diff_builder * const b, + SplitTxt const * const sst, bool isLeft, uint32_t n){ assert(2==b->passNumber); - int const col = isLeft ? DICO_NUM1 : DICO_NUM2; + int const col = isLeft ? STC_NUM1 : STC_NUM2; return n ? fdb__outf(b, "%*" PRIu32 " ", sst->maxWidths[col], n) : fdb__outf(b, "%.*c ", sst->maxWidths[col], ' '); } -static int fdb__splittxt_start(fsl_dibu * const b){ +static int fdb__splittxt_start(fsl_diff_builder * const b){ int rc = 0; if(1==b->passNumber){ - DICOSTATE(sst); - *sst = DiffCounter_empty; + SPLITSTATE(sst); + *sst = SplitTxt_empty; ++b->fileCount; return rc; } if(b->fileCount>1){ rc = fdb__out(b, "\n", 1); } if(0==rc){ - fsl_dibu_opt const * const o = b->opt; + fsl_diff_opt const * const o = b->opt; if(o->nameLHS || o->nameRHS || o->hashLHS || o->hashRHS){ rc = fdb__outf(b, "--- %s%s%s\n+++ %s%s%s\n", o->nameLHS ? o->nameLHS : "", (o->nameLHS && o->hashLHS) ? " " : "", @@ -28132,25 +27846,25 @@ } } return rc; } -static int fdb__splittxt_skip(fsl_dibu * const b, uint32_t n){ +static int fdb__splittxt_skip(fsl_diff_builder * const b, uint32_t n){ b->lnLHS += n; b->lnRHS += n; if(1==b->passNumber) return 0; - DICOSTATE(sst); - int const maxWidth1 = maxColWidth(b, sst, DICO_TEXT1); - int const maxWidth2 = maxColWidth(b, sst, DICO_TEXT2); + SPLITSTATE(sst); + int const maxWidth1 = maxColWidth(b, sst, STC_TEXT1); + int const maxWidth2 = maxColWidth(b, sst, STC_TEXT2); return fdb__outf(b, "%.*c %.*c %.*c %.*c\n", - sst->maxWidths[DICO_NUM1], '~', + sst->maxWidths[STC_NUM1], '~', maxWidth1, '~', - sst->maxWidths[DICO_NUM2], '~', + sst->maxWidths[STC_NUM2], '~', maxWidth2, '~'); } -static int fdb__splittxt_color(fsl_dibu * const b, +static int fdb__splittxt_color(fsl_diff_builder * const b, int modType){ char const *z = 0; switch(modType){ case (int)'i': z = b->opt->ansiColor.insertion; break; case (int)'d': z = b->opt->ansiColor.deletion; break; @@ -28161,18 +27875,18 @@ assert(!"invalid color op!"); } return z&&*z ? fdb__outf(b, "%s", z) : 0; } -static int fdb__splittxt_side(fsl_dibu * const b, - DiffCounter * const sst, +static int fdb__splittxt_side(fsl_diff_builder * const b, + SplitTxt * const sst, bool isLeft, fsl_dline const * const pLine){ int rc = fdb__splittxt_lineno(b, sst, isLeft, pLine ? (isLeft ? b->lnLHS : b->lnRHS) : 0U); if(0==rc){ - uint32_t const w = maxColWidth(b, sst, isLeft ? DICO_TEXT1 : DICO_TEXT2); + uint32_t const w = maxColWidth(b, sst, isLeft ? STC_TEXT1 : STC_TEXT2); if(pLine){ fsl_size_t const nU = /* Measure column width in UTF8 characters, not bytes! */ fsl_strlen_utf8(pLine->z, (fsl_int_t)pLine->n); rc = fdb__outf(b, "%#.*s", (int)(w < nU ? w : nU), pLine->z); @@ -28185,34 +27899,48 @@ if(0==rc && !isLeft) rc = fdb__out(b, "\n", 1); } return rc; } -static int fdb__splittxt_common(fsl_dibu * const b, +static void fdb__splittext_update_maxlen(SplitTxt * const sst, + int col, + char const * const z, + uint32_t n){ + if(sst->maxWidths[col]maxWidths[col] = n; +#else + n = (uint32_t)fsl_strlen_utf8(z, (fsl_int_t)n); + if(sst->maxWidths[col]maxWidths[col] = n; +#endif + } +} + +static int fdb__splittxt_common(fsl_diff_builder * const b, fsl_dline const * const pLine){ int rc = 0; - DICOSTATE(sst); + SPLITSTATE(sst); ++b->lnLHS; ++b->lnRHS; if(1==b->passNumber){ - fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n); - fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n); + fdb__splittext_update_maxlen(sst, STC_TEXT1, pLine->z, pLine->n); + fdb__splittext_update_maxlen(sst, STC_TEXT2, pLine->z, pLine->n); return 0; } rc = fdb__splittxt_side(b, sst, true, pLine); if(0==rc) rc = fdb__splittxt_mod(b, ' '); if(0==rc) rc = fdb__splittxt_side(b, sst, false, pLine); return rc; } -static int fdb__splittxt_insertion(fsl_dibu * const b, +static int fdb__splittxt_insertion(fsl_diff_builder * const b, fsl_dline const * const pLine){ int rc = 0; - DICOSTATE(sst); + SPLITSTATE(sst); ++b->lnRHS; if(1==b->passNumber){ - fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n); + fdb__splittext_update_maxlen(sst, STC_TEXT1, pLine->z, pLine->n); return rc; } rc = fdb__splittxt_color(b, 'i'); if(0==rc) rc = fdb__splittxt_side(b, sst, true, NULL); if(0==rc) rc = fdb__splittxt_mod(b, '>'); @@ -28219,17 +27947,17 @@ if(0==rc) rc = fdb__splittxt_side(b, sst, false, pLine); if(0==rc) rc = fdb__splittxt_color(b, 0); return rc; } -static int fdb__splittxt_deletion(fsl_dibu * const b, +static int fdb__splittxt_deletion(fsl_diff_builder * const b, fsl_dline const * const pLine){ int rc = 0; - DICOSTATE(sst); + SPLITSTATE(sst); ++b->lnLHS; if(1==b->passNumber){ - fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n); + fdb__splittext_update_maxlen(sst, STC_TEXT2, pLine->z, pLine->n); return rc; } rc = fdb__splittxt_color(b, 'd'); if(0==rc) rc = fdb__splittxt_side(b, sst, true, pLine); if(0==rc) rc = fdb__splittxt_mod(b, '<'); @@ -28236,25 +27964,25 @@ if(0==rc) rc = fdb__splittxt_side(b, sst, false, NULL); if(0==rc) rc = fdb__splittxt_color(b, 0); return rc; } -static int fdb__splittxt_replacement(fsl_dibu * const b, +static int fdb__splittxt_replacement(fsl_diff_builder * const b, fsl_dline const * const lineLhs, fsl_dline const * const lineRhs) { #if 0 int rc = b->deletion(b, lineLhs); if(0==rc) rc = b->insertion(b, lineRhs); return rc; #else int rc = 0; - DICOSTATE(sst); + SPLITSTATE(sst); ++b->lnLHS; ++b->lnRHS; if(1==b->passNumber){ - fdb__dico_update_maxlen(sst, DICO_TEXT1, lineLhs->z, lineLhs->n); - fdb__dico_update_maxlen(sst, DICO_TEXT2, lineRhs->z, lineRhs->n); + fdb__splittext_update_maxlen(sst, STC_TEXT1, lineLhs->z, lineLhs->n); + fdb__splittext_update_maxlen(sst, STC_TEXT2, lineRhs->z, lineRhs->n); return 0; } rc = fdb__splittxt_color(b, 'e'); if(0==rc) rc = fdb__splittxt_side(b, sst, true, lineLhs); if(0==rc) rc = fdb__splittxt_mod(b, '|'); @@ -28261,33 +27989,33 @@ if(0==rc) rc = fdb__splittxt_side(b, sst, false, lineRhs); if(0==rc) rc = fdb__splittxt_color(b, 0); return rc; #endif } - -static int fdb__splittxt_finish(fsl_dibu * const b){ + +static int fdb__splittxt_finish(fsl_diff_builder * const b){ int rc = 0; if(1==b->passNumber){ - DICOSTATE(sst); + SPLITSTATE(sst); uint32_t ln = b->lnLHS; /* Calculate width of line number columns. */ - sst->maxWidths[DICO_NUM1] = sst->maxWidths[DICO_NUM2] = 1; - for(; ln>=10; ln/=10) ++sst->maxWidths[DICO_NUM1]; + sst->maxWidths[STC_NUM1] = sst->maxWidths[STC_NUM2] = 1; + for(; ln>=10; ln/=10) ++sst->maxWidths[STC_NUM1]; ln = b->lnRHS; - for(; ln>=10; ln/=10) ++sst->maxWidths[DICO_NUM2]; + for(; ln>=10; ln/=10) ++sst->maxWidths[STC_NUM2]; } return rc; } -static void fdb__splittxt_finalize(fsl_dibu * const b){ - *b = fsl_dibu_empty; +static void fdb__splittxt_finalize(fsl_diff_builder * const b){ + *b = fsl_diff_builder_empty; fsl_free(b); } -static fsl_dibu * fsl__diff_builder_splittxt(void){ - fsl_dibu * rc = - fsl_dibu_alloc((fsl_size_t)sizeof(DiffCounter)); +static fsl_diff_builder * fsl__diff_builder_splittxt(void){ + fsl_diff_builder * rc = + fsl__diff_builder_alloc((fsl_size_t)sizeof(SplitTxt)); if(rc){ rc->twoPass = true; rc->chunkHeader = NULL; rc->start = fdb__splittxt_start; rc->skip = fdb__splittxt_skip; @@ -28297,37 +28025,36 @@ rc->replacement = fdb__splittxt_replacement; rc->edit = fdb__splittxt_replacement; rc->finish = fdb__splittxt_finish; rc->finalize = fdb__splittxt_finalize; assert(0!=rc->pimpl); - DiffCounter * const sst = (DiffCounter*)rc->pimpl; - *sst = DiffCounter_empty; + SplitTxt * const sst = (SplitTxt*)rc->pimpl; + *sst = SplitTxt_empty; } return rc; } -int fsl_dibu_factory( fsl_dibu_e type, - fsl_dibu **pOut ){ +int fsl_diff_builder_factory( fsl_diff_builder_e type, + fsl_diff_builder **pOut ){ int rc = FSL_RC_TYPE; - fsl_dibu * (*factory)(void) = NULL; + fsl_diff_builder * (*factory)(void) = NULL; switch(type){ - case FSL_DIBU_DEBUG: + case FSL_DIFF_BUILDER_DEBUG: factory = fsl__diff_builder_debug; break; - case FSL_DIBU_JSON1: + case FSL_DIFF_BUILDER_JSON1: factory = fsl__diff_builder_json1; break; - case FSL_DIBU_UNIFIED_TEXT: + case FSL_DIFF_BUILDER_UNIFIED_TEXT: factory = fsl__diff_builder_utxt; break; - case FSL_DIBU_TCL: + case FSL_DIFF_BUILDER_TCL: factory = fsl__diff_builder_tcl; break; - case FSL_DIBU_SPLIT_TEXT: + case FSL_DIFF_BUILDER_SPLIT_TEXT: factory = fsl__diff_builder_splittxt; break; - case FSL_DIBU_INVALID: break; } if(NULL!=factory){ *pOut = factory(); rc = *pOut ? 0 : FSL_RC_OOM; } @@ -28341,14 +28068,13 @@ #undef DIFF_WHITESPACE_ONLY #undef fsl_dline_empty_m #undef MARKER #undef DTCL_BUFFER #undef blob_to_utf8_no_bom -#undef DICOSTATE -#undef FSL_DIFF_SMALL_GAP -/* end of file ./src/diff2.c */ -/* start of file ./src/encode.c */ +#undef SPLITSTATE +/* end of file diff2.c */ +/* start of file encode.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -28623,12 +28349,12 @@ fsl_buffer_clear(&b); return NULL; } } -/* end of file ./src/encode.c */ -/* start of file ./src/event.c */ +/* end of file encode.c */ +/* start of file event.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -28670,12 +28396,12 @@ } } #undef MARKER -/* end of file ./src/event.c */ -/* start of file ./src/fs.c */ +/* end of file event.c */ +/* start of file fs.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -28694,11 +28420,11 @@ #include /* strlen() */ #include /* NULL on linux */ #include #include #include -#if FSL_PLATFORM_IS_WINDOWS +#ifdef _WIN32 # define DIR _WDIR # define dirent _wdirent # define opendir _wopendir # define readdir _wreaddir # define closedir _wclosedir @@ -28707,11 +28433,11 @@ # include # if !defined(ELOOP) # define ELOOP 114 /* Missing in MinGW */ # endif #else -# include /* access(2), readlink(2) */ +# include /* access(2) */ # include # include #endif #include @@ -28810,11 +28536,12 @@ if(outLen) *outLen = nPwd; return 0; #else if(!zBuf) return FSL_RC_MISUSE; else if(!nBuf) return FSL_RC_RANGE; - else if( NULL==getcwd(zBuf,nBuf) ){ + else if( getcwd(zBuf, + nBuf /*-1 not necessary: getcwd() NUL-terminates*/)==0 ){ return fsl_errno_to_rc(errno, FSL_RC_IO); }else{ if(outLen) *outLen = fsl_strlen(zBuf); return 0; } @@ -28839,11 +28566,11 @@ #endif /* Reminder: the semantics of the 3rd parameter are reversed from v1's fossil_stat(). */ -int fsl_stat(const char *zFilename, fsl_fstat * const fst, +int fsl_stat(const char *zFilename, fsl_fstat * fst, bool derefSymlinks){ /* FIXME: port in fossil(1) win32_stat() */ if(!zFilename) return FSL_RC_MISUSE; else if(!*zFilename) return FSL_RC_RANGE; else{ @@ -28938,19 +28665,14 @@ ? false : (FSL_FSTAT_TYPE_FILE == fst.type); } bool fsl_is_symlink(const char *zFilename){ -#if FSL_PLATFORM_IS_WINDOWS - if(zFilename){/*unused var*/} - return false; -#else fsl_fstat fst; - return (0 == fsl_stat(zFilename, &fst, 0)) - ? (FSL_FSTAT_TYPE_LINK == fst.type) - : false; -#endif + return ( 0 != fsl_stat(zFilename, &fst, 0) ) + ? false + : (FSL_FSTAT_TYPE_LINK == fst.type); } /* Return true if zPath is an absolute pathname. Return false if it is relative. @@ -29057,19 +28779,20 @@ fsl_size_t fsl_file_simplify_name(char *z, fsl_int_t n_, bool slash){ fsl_size_t i; fsl_size_t n = (n_<0) ? fsl_strlen(z) : (fsl_size_t)n_; fsl_int_t j; - bool const hadSlash = n && (z[n-1]=='/'); /* On windows and cygwin convert all \ characters to / */ #if defined(_WIN32) || defined(__CYGWIN__) for(i=0; i1 && z[n-1]=='/' ){--n;} + if( !slash ){ + while( n>1 && z[n-1]=='/' ){ n--; } + } /* Remove duplicate '/' characters. Except, two // at the beginning of a pathname is allowed since this is important on windows. */ for(i=j=1; i=0 ) z[j] = z[i]; j++; } if( j==0 ) z[j++] = '.'; - if(slash && hadSlash && '/'!=z[j-1]) z[j++] = '/'; z[j] = 0; return (fsl_size_t)j; } int fsl_file_canonical_name2(const char *zRoot, const char *zOrigName, - fsl_buffer * const pOut, bool slash){ + fsl_buffer *pOut, bool slash){ int rc; if(!zOrigName || !pOut) return FSL_RC_MISUSE; else if( fsl_is_absolute_path(zOrigName) || (zRoot && !*zRoot)){ rc = fsl_buffer_append( pOut, zOrigName, -1 ); #if defined(_WIN32) || defined(__CYGWIN__) @@ -29160,18 +28882,17 @@ return rc; } int fsl_file_canonical_name(const char *zOrigName, - fsl_buffer * const pOut, - bool slash){ + fsl_buffer *pOut, bool slash){ return fsl_file_canonical_name2(NULL, zOrigName, pOut, slash); } int fsl_file_dirpart(char const * zFilename, fsl_int_t nLen, - fsl_buffer * const pOut, + fsl_buffer * pOut, bool leaveSlash){ if(!zFilename || !*zFilename || !pOut) return FSL_RC_MISUSE; else if(!nLen) return FSL_RC_RANGE; else{ fsl_size_t n = (nLen>0) ? (fsl_size_t)nLen : fsl_strlen(zFilename); @@ -29447,16 +29168,10 @@ return dwAttributes==FILE_ATTRIBUTE_DIRECTORY; } #endif -bool fsl_file_isexec(const char *zFilename){ - fsl_fstat st = fsl_fstat_empty; - int const s = fsl_stat(zFilename, &st, true); - return 0==s ? (st.perm & FSL_FSTAT_PERM_EXE) : false; -} - int fsl_rmdir(const char *zFilename){ int rc = fsl_dir_check(zFilename); if(rc<1) return rc ? FSL_RC_TYPE : FSL_RC_NOT_FOUND; #ifdef _WIN32 wchar_t *z = (wchar_t*)fsl_utf8_to_filename(zFilename); @@ -29804,17 +29519,13 @@ if(err) rc = fsl_errno_to_rc(errno, FSL_RC_IO); return rc; #endif } -/** - fsl_dircrawl() part for handling a single directory. fst must be - valid state from a freshly-fsl_fstat()'d DIRECTORY. -*/ -static int fsl_dircrawl_impl(fsl_buffer * const dbuf, fsl_fstat * const fst, - fsl_dircrawl_f cb, void * const cbState, - fsl_dircrawl_state * const dst, +static int fsl_dircrawl_impl(fsl_buffer * dbuf, fsl_fstat * fst, + fsl_dircrawl_f cb, void * cbState, + fsl_dircrawl_state * dst, unsigned int depth){ int rc = 0; DIR *dir = opendir(fsl_buffer_cstr(dbuf)); struct dirent * dent = 0; fsl_size_t const dPos = dbuf->used; @@ -29858,12 +29569,10 @@ dbuf->mem[dbuf->used] = '/'; dbuf->used = newLen; if(FSL_FSTAT_TYPE_DIR==fst->type){ rc = fsl_dircrawl_impl( dbuf, fst, cb, cbState, dst, depth+1 ); } - }else if(FSL_RC_NOOP == rc){ - rc = 0; } } closedir(dir); return rc; } @@ -29894,14 +29603,13 @@ return rc; } bool fsl_is_file_or_link(const char *zFilename){ fsl_fstat fst = fsl_fstat_empty; - return fsl_stat(zFilename, &fst, false) - ? false - : (fst.type==FSL_FSTAT_TYPE_FILE - || fst.type==FSL_FSTAT_TYPE_LINK); + if(fsl_stat(zFilename, &fst, false)) return false; + return fst.type==FSL_FSTAT_TYPE_FILE + || fst.type==FSL_FSTAT_TYPE_LINK; } fsl_size_t fsl_strip_trailing_slashes(char * name, fsl_int_t nameLen){ fsl_size_t rc = 0; if(nameLen < 0) nameLen = (fsl_int_t)fsl_strlen(name); @@ -29922,235 +29630,30 @@ int fsl_file_rename(const char *zFrom, const char *zTo){ int rc; #if defined(_WIN32) /** 2021-03-24: fossil's impl of this routine has 2 additional - params (bool isFromDir, bool isToDir), which are passed on to - fsl_utf8_to_filename(), only used on Windows platforms, and are - only to allow for 12 bytes of edge case in MAX_PATH handling. - We don't need them. */ + params (bool isFromDir, bool isToDir), which are only used on + Windows platforms and are only to allow for 12 bytes of edge + case in MAX_PATH handling. We don't need them. */ wchar_t *zMbcsFrom = fsl_utf8_to_filename(zFrom); wchar_t *zMbcsTo = zMbcsFrom ? fsl_utf8_to_filename(zTo) : 0; - rc = zMbcsTo ? _wrename(zMbcsFrom, zMbcsTo) : FSL_RC_OOM; + rc = zMbcsTo + ? _wrename(zMbcsFrom, zMbcsTo) + : FSL_RC_OOM; #else char *zMbcsFrom = fsl_utf8_to_filename(zFrom); char *zMbcsTo = zMbcsFrom ? fsl_utf8_to_filename(zTo) : 0; - rc = zMbcsTo ? rename(zMbcsFrom, zMbcsTo) : FSL_RC_OOM; + rc = zMbcsTo + ? rename(zMbcsFrom, zMbcsTo) + : FSL_RC_OOM; #endif fsl_filename_free(zMbcsTo); fsl_filename_free(zMbcsFrom); - return -1==rc ? fsl_errno_to_rc(errno, FSL_RC_IO) : rc; -} - -char ** fsl_temp_dirs_get(void){ -#if FSL_PLATFORM_IS_WINDOWS - const char *azDirs[] = { - ".", - NULL - }; - unsigned int const nDirs = 4 - /* GetTempPath(), $TEMP, $TMP, azDirs */; -#else - const char *azDirs[] = { - "/var/tmp", - "/usr/tmp", - "/tmp", - "/temp", - ".", NULL - }; - unsigned int const nDirs = 6 - /* $TMPDIR, azDirs */; -#endif - char *z; - char const *zC; - char ** zDirs = NULL; - unsigned int i, n = 0; - - zDirs = (char **)fsl_malloc(sizeof(char*) * (nDirs + 1)); - if(!zDirs) return NULL; - for(i = 0; i<=nDirs; ++i) zDirs[i] = NULL; -#define DOZ \ - if(z && fsl_dir_check(z)>0) zDirs[n++] = z; \ - else if(z) fsl_filename_free(z) - -#if FSL_PLATFORM_IS_WINDOWS - wchar_t zTmpPath[MAX_PATH]; - - if( GetTempPathW(MAX_PATH, zTmpPath) ){ - z = fsl_filename_to_utf8(zTmpPath); - DOZ; - } - z = fsl_getenv("TEMP"); - DOZ; - z = fsl_getenv("TMP"); - DOZ; -#else /* Unix-like */ - z = fsl_getenv("TMPDIR"); - DOZ; -#endif - for( i = 0; (zC = azDirs[i]); ++i ){ - z = fsl_filename_to_utf8(azDirs[i]); - DOZ; - } -#undef DOZ - /* Strip any trailing slashes unless the only character is a - slash. Note that we ignore the root-dir case on Windows here, - mainly because this developer can't test it and secondarily - because it's a highly unlikely case. */ - for(i = 0; i < n; ++i ){ - fsl_size_t len; - z = zDirs[i]; - len = fsl_strlen(z); - while(len>1 && (z[len-1]=='/' || z[len-1]=='\\')){ - z[--len] = 0; - } - } - return zDirs; -} - -void fsl_temp_dirs_free(char **aDirs){ - if(aDirs){ - char * z; - for(unsigned i = 0; (z = aDirs[i]); ++i){ - fsl_filename_free(z); - aDirs[i] = NULL; - } - fsl_free(aDirs); - } -} - -int fsl_file_tempname(fsl_buffer * const tgt, char const *zPrefix, - char * const * const dirs){ - int rc = 0; - unsigned int tries = 0; - const unsigned char zChars[] = - "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789_"; - enum { RandSize = 24 }; - char zRand[RandSize + 1]; - int i; - char const * zDir = ""; - if(dirs){ - for(i = 0; (zDir=dirs[i++]); ){ - /* We repeat this check, performed in fsl_temp_dirs_get(), for the - sake of long-lived apps where a given temp dir might disappear - at some point. */ - if(fsl_dir_check(zDir)>0) break; - } - if(!zDir) return FSL_RC_NOT_FOUND; - } - if(!zPrefix) zPrefix = "libfossil"; - fsl_buffer_reuse(tgt); - /* Pre-fill buffer to allocate it in advance and remember the length - of the base filename part so that we don't have to re-write the - prefix each iteration below. */ - rc = fsl_buffer_appendf(tgt, "%/%s%s%s%.*cZ", - zDir, *zDir ? "/" : "", - zPrefix, *zPrefix ? "~" : "", - (int)RandSize, 'X'); - fsl_size_t const baseLen = rc ? 0 : (tgt->used - RandSize - 1); - do{ - if(++tries == 20){ - rc = FSL_RC_RANGE; - break; - } - fsl_randomness(RandSize, zRand); - for( i=0; i < RandSize; ++i ){ - zRand[i] = (char)zChars[ ((unsigned char)zRand[i])%(sizeof(zChars)-1) ]; - } - zRand[RandSize] = 0; - tgt->used = baseLen; - rc = fsl_buffer_append(tgt, zRand, (fsl_int_t)RandSize); - assert(0==rc && "We pre-allocated the buffer above."); - }while(0==rc && fsl_file_size(fsl_buffer_cstr(tgt)) >= 0); - return rc; -} - -int fsl_file_copy(char const *zFrom, char const *zTo){ - FILE * in = 0, *out = 0; - int rc; - in = fsl_fopen(zFrom, "rb"); - if(!in) return fsl_errno_to_rc(errno, FSL_RC_IO); - rc = fsl_mkdir_for_file(zTo, false); - if(rc) goto end; - out = fsl_fopen(zTo, "wb"); - rc = out - ? fsl_stream(fsl_input_f_FILE, in, fsl_output_f_FILE, out) - : fsl_errno_to_rc(errno, FSL_RC_IO); - end: - if(in) fsl_fclose(in); - if(out) fsl_fclose(out); - if(0==rc && fsl_file_isexec(zFrom)){ - fsl_file_exec_set(zTo, true); - } - return rc; -} - -int fsl_symlink_read(fsl_buffer * const tgt, char const * zFilename){ -#if FSL_PLATFORM_IS_WINDOWS - fsl_buffer_reuse(tgt); - return 0; -#else - enum { BufLen = 1024 * 2 }; - char buf[BufLen]; - int rc; - ssize_t const len = readlink(zFilename, buf, BufLen-1); - if(len<0) rc = fsl_errno_to_rc(errno, FSL_RC_IO); - else{ - fsl_buffer_reuse(tgt); - rc = fsl_buffer_append(tgt, buf, (fsl_size_t)len); - } - return rc; -#endif -} - -int fsl_symlink_create(const char *zTargetFile, const char *zLinkFile, - bool realLink){ - int rc; -#if !FSL_PLATFORM_IS_WINDOWS - if( realLink ){ - char *zName, zBuf[1024 * 2]; - fsl_size_t nName = fsl_strlen(zLinkFile); - if( nName>=sizeof(zBuf) ){ - zName = fsl_mprintf("%s", zLinkFile); - if(!zName) return FSL_RC_OOM; - }else{ - zName = zBuf; - memcpy(zName, zLinkFile, nName+1); - } - nName = fsl_file_simplify_name(zName, (fsl_int_t)nName, false); - rc = fsl_mkdir_for_file(zName, false); - if(0==rc && 0!=symlink(zTargetFile, zName) ){ - rc = fsl_errno_to_rc(errno, FSL_RC_IO); - } - if( zName!=zBuf ) fsl_free(zName); - }else -#endif - { - rc = fsl_mkdir_for_file(zLinkFile, false); - if(0==rc){ - fsl_buffer content = fsl_buffer_empty; - fsl_buffer_external(&content, zTargetFile, -1); - fsl_file_unlink(zLinkFile) - /* in case it's already a symlink, we don't want the following - to overwrite the symlinked-to file */; - rc = fsl_buffer_to_filename(&content, zLinkFile); - } - } - return rc; -} - -int fsl__symlink_copy(char const *zFrom, char const *zTo, bool realLink){ - int rc; - fsl_buffer b = fsl_buffer_empty; - rc = fsl_symlink_read(&b, zFrom); - if(0==rc){ - rc = fsl_symlink_create(fsl_buffer_cstr(&b), zTo, realLink); - } - fsl_buffer_clear(&b); - return rc; + return rc + ? (FSL_RC_OOM==rc ? rc : fsl_errno_to_rc(errno, FSL_RC_IO)) + : 0; } #if 0 int fsl_file_relative_name( char const * zRoot, char const * zPath, fsl_buffer * pOut, char retainSlash ){ @@ -30171,12 +29674,12 @@ # undef dirent # undef opendir # undef readdir # undef closedir #endif -/* end of file ./src/fs.c */ -/* start of file ./src/forum.c */ +/* end of file fs.c */ +/* start of file forum.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -30217,12 +29720,12 @@ } #undef MARKER -/* end of file ./src/forum.c */ -/* start of file ./src/glob.c */ +/* end of file forum.c */ +/* start of file glob.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -30306,12 +29809,12 @@ return *z==0; #endif } -int fsl_glob_list_parse( fsl_list * const tgt, char const * zPatternList ){ - fsl_size_t i; /* Loop counter */ +int fsl_glob_list_parse( fsl_list * tgt, char const * zPatternList ){ + fsl_size_t i; /* Loop counters */ char const *z = zPatternList; char * cp; char delimiter; /* '\'' or '\"' or 0 */ int rc = 0; char const * end; @@ -30363,11 +29866,11 @@ } return NULL; } } -int fsl_glob_list_append( fsl_list * const tgt, char const * zGlob ){ +int fsl_glob_list_append( fsl_list * tgt, char const * zGlob ){ if(!tgt || !zGlob || !*zGlob) return FSL_RC_MISUSE; else{ char * cp = fsl_strdup(zGlob); int rc = cp ? 0 : FSL_RC_OOM; if(!rc){ @@ -30381,12 +29884,12 @@ void fsl_glob_list_clear( fsl_list * const globList ){ if(globList) fsl_list_visit_free(globList, 1); } -/* end of file ./src/glob.c */ -/* start of file ./src/io.c */ +/* end of file glob.c */ +/* start of file io.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -30522,12 +30025,12 @@ } return rc; } #undef MARKER -/* end of file ./src/io.c */ -/* start of file ./src/leaf.c */ +/* end of file io.c */ +/* start of file leaf.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -30549,13 +30052,13 @@ #define MARKER(pfexp) \ do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ printf pfexp; \ } while(0) -int fsl_repo_leaves_rebuild(fsl_cx * const f){ - fsl_db * const db = fsl_cx_db_repo(f); - int rc = fsl_db_exec_multi(db, +int fsl_repo_leaves_rebuild(fsl_cx * f){ + fsl_db * db = f ? fsl_cx_db_repo(f) : NULL; + return !db ? FSL_RC_MISUSE : fsl_db_exec_multi(db, "DELETE FROM leaf;" "INSERT OR IGNORE INTO leaf" " SELECT cid FROM plink" " EXCEPT" " SELECT pid FROM plink" @@ -30563,11 +30066,10 @@ " WHERE tagid=%d AND rid=plink.pid),'trunk')" " == coalesce((SELECT value FROM tagxref" " WHERE tagid=%d AND rid=plink.cid),'trunk')", FSL_TAGID_BRANCH, FSL_TAGID_BRANCH ); - return rc ? fsl_cx_uplift_db_error2(f, db, rc) : 0; } fsl_int_t fsl_count_nonbranch_children(fsl_cx * const f, fsl_id_t rid){ int32_t rv = 0; int rc; @@ -30701,11 +30203,11 @@ } fsl_id_bag_reset(&f->cache.leafCheck); return rc; } -int fsl_leaves_compute(fsl_cx * const f, fsl_id_t vid, +int fsl_leaves_compute(fsl_cx * f, fsl_id_t vid, fsl_leaves_compute_e closeMode){ fsl_db * const db = fsl_needs_repo(f); if(!db) return FSL_RC_NOT_A_REPO; int rc = 0; @@ -30843,16 +30345,16 @@ assert(rc); rc = fsl_cx_uplift_db_error2(f, db, rc); goto end; } -bool fsl_leaves_computed_has(fsl_cx * const f){ +bool fsl_leaves_computed_has(fsl_cx * f){ return fsl_db_exists(fsl_cx_db_repo(f), "SELECT 1 FROM leaves"); } -fsl_int_t fsl_leaves_computed_count(fsl_cx * const f){ +fsl_int_t fsl_leaves_computed_count(fsl_cx * f){ int32_t rv = -1; fsl_db * const db = fsl_cx_db_repo(f); int const rc = fsl_db_get_int32(db, &rv, "SELECT COUNT(*) FROM leaves"); if(rc){ @@ -30862,39 +30364,34 @@ assert(rv>=0); } return rv; } -fsl_id_t fsl_leaves_computed_latest(fsl_cx * const f){ +fsl_id_t fsl_leaves_computed_latest(fsl_cx * f){ fsl_id_t rv = 0; fsl_db * const db = fsl_cx_db_repo(f); int const rc = fsl_db_get_id(db, &rv, - "SELECT rid FROM leaves, event" - " WHERE event.objid=leaves.rid" - " ORDER BY event.mtime DESC"); + "SELECT rid FROM leaves, event" + " WHERE event.objid=leaves.rid" + " ORDER BY event.mtime DESC"); if(rc){ fsl_cx_uplift_db_error2(f, db, rc); assert(!rv); }else{ assert(rv>=0); } return rv; } -void fsl_leaves_computed_cleanup(fsl_cx * const f){ - if(fsl_cx_exec(f, "DROP TABLE IF EXISTS temp.leaves")){ - /** - Naively assume that locking is keeping us from dropping it, - and simply empty it instead. */ - fsl_cx_exec(f, "DELETE FROM temp.leaves"); - } +void fsl_leaves_computed_cleanup(fsl_cx * f){ + fsl_db_exec(fsl_cx_db_repo(f), "DROP TABLE IF EXISTS leaves"); } #undef MARKER -/* end of file ./src/leaf.c */ -/* start of file ./src/list.c */ +/* end of file leaf.c */ +/* start of file list.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -30910,11 +30407,11 @@ */ #include #include /* malloc() and friends, qsort() */ #include /* memset() */ -int fsl_list_reserve( fsl_list * const self, fsl_size_t n ) +int fsl_list_reserve( fsl_list * self, fsl_size_t n ) { if( !self ) return FSL_RC_MISUSE; else if(0 == n){ if(0 == self->capacity) return 0; fsl_free(self->list); @@ -30933,17 +30430,17 @@ self->list = m; return 0; } } -void fsl_list_swap( fsl_list * const lhs, fsl_list * const rhs ){ +void fsl_list_swap( fsl_list * lhs, fsl_list * rhs ){ fsl_list tmp = *lhs; *rhs = *lhs; *lhs = tmp; } -int fsl_list_append( fsl_list * const self, void* cp ){ +int fsl_list_append( fsl_list * self, void* cp ){ if( !self ) return FSL_RC_MISUSE; assert(self->used <= self->capacity); if(self->used == self->capacity){ int rc; fsl_size_t const cap = self->capacity @@ -30960,11 +30457,11 @@ int fsl_list_v_fsl_free(void * obj, void * visitorState ){ if(obj) fsl_free( obj ); return 0; } -int fsl_list_clear( fsl_list * const self, fsl_list_visitor_f childFinalizer, +int fsl_list_clear( fsl_list * self, fsl_list_visitor_f childFinalizer, void * finalizerState ){ /* TODO: manually traverse the list and set each list entry for which the finalizer succeeds to NULL, so that we can provide well-defined behaviour if childFinalizer() fails and we abort the @@ -30973,11 +30470,11 @@ int rc = fsl_list_visit(self, 0, childFinalizer, finalizerState ); if(!rc) fsl_list_reserve(self, 0); return rc; } -void fsl_list_visit_free( fsl_list * const self, bool freeListMem ){ +void fsl_list_visit_free( fsl_list * self, bool freeListMem ){ fsl_list_visit(self, 0, fsl_list_v_fsl_free, NULL ); if(freeListMem) fsl_list_reserve(self, 0); else self->used = 0; } @@ -31002,11 +30499,11 @@ } return rc; } -int fsl_list_visit_p( fsl_list * const self, int order, +int fsl_list_visit_p( fsl_list * self, int order, bool shiftIfNulled, fsl_list_visitor_f visitor, void * visitorState ) { int rc = FSL_RC_OK; if( self && self->used && visitor ){ @@ -31034,11 +30531,11 @@ } } return rc; } -void fsl_list_sort( fsl_list * const li, +void fsl_list_sort( fsl_list * li, fsl_generic_cmp_f cmp){ if(li && li->used>1){ qsort( li->list, li->used, sizeof(void*), cmp ); } } @@ -31066,12 +30563,12 @@ fsl_int_t fsl_list_index_of_cstr( fsl_list const * li, char const * key ){ return fsl_list_index_of(li, key, fsl_strcmp_cmp); } -/* end of file ./src/list.c */ -/* start of file ./src/lookslike.c */ +/* end of file list.c */ +/* start of file lookslike.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -31125,15 +30622,10 @@ #undef US4A #undef US4B #undef US4C #undef US0A -bool fsl_looks_like_binary(fsl_buffer const * const b){ - return (fsl_looks_like_utf8(b, FSL_LOOKSLIKE_BINARY) & FSL_LOOKSLIKE_BINARY) - != FSL_LOOKSLIKE_NONE; -} - int fsl_looks_like_utf8(fsl_buffer const * const b, int stopFlags){ fsl_size_t n = 0; const char *z = fsl_buffer_cstr2(b, &n); int j, c, flags = FSL_LOOKSLIKE_NONE; /* Assume UTF-8 text, prove otherwise */ @@ -31219,12 +30711,12 @@ c = *++z; } } return c<0x80 /* Final lead byte must be ASCII. */; } -/* end of file ./src/lookslike.c */ -/* start of file ./src/md5.c */ +/* end of file lookslike.c */ +/* start of file md5.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* The code is modified for use in fossil (then libfossil). The original header comment follows: */ @@ -31662,1285 +31154,12 @@ #undef F2 #undef F3 #undef F4 #undef MD5STEP #undef byteReverse -/* end of file ./src/md5.c */ -/* start of file ./src/merge.c */ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -/* - Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt - - SPDX-License-Identifier: BSD-2-Clause-FreeBSD - SPDX-FileCopyrightText: 2021 The Libfossil Authors - SPDX-ArtifactOfProjectName: Libfossil - SPDX-FileType: Code - - Heavily indebted to the Fossil SCM project (https://fossil-scm.org). -*/ -#include -#include -#include -#include /* memmove()/strlen() */ - -#define MARKER(pfexp) \ - do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ - printf pfexp; \ - } while(0) - -#define FSL__TABLE_PIVOT "aqueue" - -/** - Sets the primary version of a merge. The primary version is - one of the two files that have a common ancestor. The other file - is the secondary. There can be multiple secondaries but only a - single primary. The primary must be set first. - - In the merge algorithm, the file being merged in is the primary. - The current check-out or other files that have been merged into - the current checkout are the secondaries. - - The act of setting the primary resets the pivot-finding algorithm. - - Returns 0 on success, non-0 on serious error. - - This works using a TEMP db, so does not strictly require - a repo or checkout. - - @see fsl__pivot_set_secondary() - @see fsl__pivot_find() -*/ -static int fsl__pivot_set_primary(fsl_cx * const f, fsl_id_t rid){ - /* Set up table used to do the search */ - int rc = fsl_cx_exec_multi(f, - "CREATE TEMP TABLE IF NOT EXISTS " FSL__TABLE_PIVOT "(" - " rid INTEGER," /* The record id for this version */ - " mtime REAL," /* Time when this version was created */ - " pending BOOLEAN," /* True if we have not check this one yet */ - " src BOOLEAN," /* 1 for primary. 0 for others */ - " PRIMARY KEY(rid,src)" - ") WITHOUT ROWID;" - "DELETE FROM " FSL__TABLE_PIVOT ";" - "CREATE INDEX IF NOT EXISTS " FSL__TABLE_PIVOT "_idx1 ON " FSL__TABLE_PIVOT "(pending, mtime);" - ); - if(0==rc){ - /* Insert the primary record */ - rc = fsl_cx_exec(f, - "INSERT INTO " FSL__TABLE_PIVOT "(rid, mtime, pending, src)" - " SELECT %" FSL_ID_T_PFMT ", mtime, 1, 1 " - " FROM event WHERE objid=%" FSL_ID_T_PFMT - " AND type='ci' LIMIT 1", - rid, rid ); - } - return rc; -} - -/** - Set a secondary file of a merge. The primary file must be set - first. There must be at least one secondary but there can be more - than one if desired. - - Returns 0 on success, non-0 on db error. - - @see fsl__pivot_set_primary() - @see fsl__pivot_find() -*/ -static int fsl__pivot_set_secondary(fsl_cx * const f, fsl_id_t rid){ - return fsl_cx_exec(f, - "INSERT OR IGNORE INTO " FSL__TABLE_PIVOT "(rid, mtime, pending, src)" - " SELECT %" FSL_ID_T_PFMT ", mtime, 1, 0 " - "FROM event WHERE objid=%" FSL_ID_T_PFMT " AND type='ci'", - rid, rid - ); -} - - -/** - Searches for the most recent common ancestor of the primary and one of - the secondaries in a merge. - - On success, *outRid is set to its value and 0 is returned. If no - match is found, *outRid is set to 0 and 0 is returned. Returns - non-0 on error, indicating either a lower-level db error or an - allocation error. - - If ignoreMerges is true, it follows only "primary" parent links. - - @see fsl__pivot_set_primary() - @see fsl__pivot_set_secondary() -*/ -static int fsl__pivot_find(fsl_cx * const f, bool ignoreMerges, fsl_id_t *outRid){ - fsl_db * const db = fsl_cx_db(f); - int rc; - fsl_stmt q1 = fsl_stmt_empty, q2 = fsl_stmt_empty, - u1 = fsl_stmt_empty, i1 = fsl_stmt_empty; - fsl_id_t rid = 0; - if(fsl_db_g_int32(db, 0, "SELECT COUNT(distinct src) FROM " FSL__TABLE_PIVOT "")<2){ - return fsl_cx_err_set(f, FSL_RC_MISUSE, - "Pivot list [" FSL__TABLE_PIVOT "] contains neither primary " - "nor secondary entries."); - } - /* Prepare queries we will be needing - ** - ** The first query finds the oldest pending version on the - ** FSL__TABLE_PIVOT. This will be next one searched. - */ - rc = fsl_cx_prepare(f, &q1, - "SELECT rid FROM " FSL__TABLE_PIVOT " WHERE pending" - " ORDER BY pending DESC, mtime DESC"); - if(rc) goto end; - - /* Check to see if the record :rid is a common ancestor. The result - ** set contains one or more rows if it is and is the empty set if it - ** is not. - */ - rc = fsl_cx_prepare(f, &q2, - "SELECT 1 FROM " FSL__TABLE_PIVOT " A, plink, " FSL__TABLE_PIVOT " B" - " WHERE plink.pid=?1" - " AND plink.cid=B.rid" - " AND A.rid=?1" - " AND A.src!=B.src %s", - ignoreMerges ? "AND plink.isprim" : "" - ); - if(rc) goto end; - - /* Mark the :rid record has having been checked. It is not the - ** common ancestor. - */ - rc = fsl_cx_prepare(f, &u1, - "UPDATE " FSL__TABLE_PIVOT " SET pending=0 WHERE rid=?1" - ); - if(rc) goto end; - - /* Add to the queue all ancestors of :rid. - */ - rc = fsl_cx_prepare(f, &i1, - "REPLACE INTO " FSL__TABLE_PIVOT " " - "SELECT plink.pid," - " coalesce((SELECT mtime FROM event X WHERE X.objid=plink.pid), 0.0)," - " 1," - " " FSL__TABLE_PIVOT ".src " - " FROM plink, " FSL__TABLE_PIVOT - " WHERE plink.cid=?1" - " AND " FSL__TABLE_PIVOT ".rid=?1 %s", - ignoreMerges ? "AND plink.isprim" : "" - ); - if(rc) goto end; - while(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q1))){ - rid = fsl_stmt_g_id(&q1, 0); - fsl_stmt_reset(&q1); - rc = fsl_stmt_bind_step(&q2, "R", rid); - if(rc) break/*error or found match*/; - rc = fsl_stmt_bind_step(&i1, "R", rid); - assert(FSL_RC_STEP_ROW!=rc); - if(0==rc) rc = fsl_stmt_bind_step(&u1, "R", rid); - if(rc) break; - assert(FSL_RC_STEP_ROW!=rc); - rid = 0; - } - switch(rc){ - case 0: break; - case FSL_RC_STEP_ROW: - case FSL_RC_STEP_DONE: rc = 0; break; - default: - rc = fsl_cx_uplift_db_error2(f, NULL, rc); - break; - } - end: - fsl_stmt_finalize(&q1); - fsl_stmt_finalize(&q2); - fsl_stmt_finalize(&u1); - fsl_stmt_finalize(&i1); - if(0==rc && rid) *outRid = rid; - return rc; -} - -/** - Searches f's current repository for the nearest fork related to - version vid. - - More specifically: this looks for the most recent leaf that is (1) - not equal to vid and (2) has not already been merged into vid and - (3) the leaf is not closed and (4) the leaf is in the same branch - as vid. - - If checkVmerge is true then the current checkout - database is also checked (via the vmerge table), in which case a - checkout must be opened. - - On success, returns 0 and assigns *outRid to the resulting RID. - - On error: - - - FSL_RC_NOT_A_REPO or FSL_RC_NOT_A_CKOUT if called when no repo or - (if checkVmerge is true) no checkout. - - - FSL_RC_NOT_FOUND: no closest merge was found. - - - FSL_RC_OOM: on allocation error - - - Any number of potential other errors from the db layer. - - f's error state will contain more information about errors reported - here. -*/ -/*static*/ int fsl__find_nearest_fork(fsl_cx * const f, - fsl_id_t vid, bool checkVmerge, - fsl_id_t * outRid){ - fsl_db * const db = checkVmerge - ? fsl_needs_ckout(f) : fsl_needs_repo(f); - fsl_buffer * const sql = fsl__cx_scratchpad(f); - fsl_stmt q; - if(!db){ - return checkVmerge ? FSL_RC_NOT_A_CKOUT : FSL_RC_NOT_A_REPO; - } - q = fsl_stmt_empty; - int rc = fsl_buffer_appendf(sql, - "SELECT leaf.rid" - " FROM leaf, event" - " WHERE leaf.rid=event.objid" - " AND leaf.rid!=%" FSL_ID_T_PFMT, /* Constraint (1) */ - vid - ); - if(rc) goto end; - if( checkVmerge ){ - rc = fsl_buffer_append(sql, - " AND leaf.rid NOT IN (SELECT merge FROM vmerge)" - /* Constraint (2) */, -1 ); - if(rc) goto end; - } - rc = fsl_buffer_appendf(sql, - " AND NOT EXISTS(SELECT 1 FROM tagxref" /* Constraint (3) */ - " WHERE rid=leaf.rid" - " AND tagid=%d" - " AND tagtype>0)" - " AND (SELECT value FROM tagxref" /* Constraint (4) */ - " WHERE tagid=%d AND rid=%" FSL_ID_T_PFMT " AND tagtype>0) =" - " (SELECT value FROM tagxref" - " WHERE tagid=%d AND rid=leaf.rid AND tagtype>0)" - " ORDER BY event.mtime DESC LIMIT 1", - FSL_TAGID_CLOSED, - FSL_TAGID_BRANCH, - vid, FSL_TAGID_BRANCH - ); - if(rc) goto end; - rc = fsl_db_prepare(db, &q, "%b", sql); - if(rc){ - rc = fsl_cx_uplift_db_error2(f, db, rc); - goto end; - } - rc = fsl_stmt_step(&q); - switch(rc){ - case FSL_RC_STEP_ROW: - rc = 0; - *outRid = fsl_stmt_g_id(&q, 0); - assert(*outRid>0); - break; - case FSL_RC_STEP_DONE: - rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, - "Cannot find nearest fork of RID #%" - FSL_ID_T_PFMT ".", vid); - break; - default: - rc = fsl_cx_uplift_db_error2(f, db, rc); - break; - } - end: - fsl_stmt_finalize(&q); - fsl__cx_scratchpad_yield(f, sql); - return rc; -} - -/** - Name for the merge algo's version of the fv table, noting that it - differs enough from the update algo's version that they do not - map 1-to-1 without some degree of pain which might make sense - once merge is in the library and working. -*/ -#define FSL__TABLE_FVM "fvm" - -static int fsl__renames_init(fsl_cx * const f){ - char const * const coll = fsl_cx_filename_collation(f); - return fsl_cx_exec_multi(f, - "CREATE TEMP TABLE IF NOT EXISTS " FSL__TABLE_FVM "(\n" - " fn TEXT UNIQUE %s,\n" /* The filename */ - " idv INTEGER DEFAULT 0,\n" /* VFILE entry for current version */ - " idp INTEGER DEFAULT 0,\n" /* VFILE entry for the pivot */ - " idm INTEGER DEFAULT 0,\n" /* VFILE entry for version merging in */ - " chnged BOOLEAN,\n" /* True if current version has been edited */ - " ridv INTEGER DEFAULT 0,\n" /* Record ID for current version */ - " ridp INTEGER DEFAULT 0,\n" /* Record ID for pivot */ - " ridm INTEGER DEFAULT 0,\n" /* Record ID for merge */ - " isexe BOOLEAN,\n" /* Execute permission enabled */ - " fnp TEXT UNIQUE %s,\n" /* The filename in the pivot */ - " fnm TEXT UNIQUE %s,\n" /* The filename in the merged version */ - " fnn TEXT UNIQUE %s,\n" /* The filename in the name pivot */ - " islinkv BOOLEAN,\n" /* True if current version is a symlink */ - " islinkm BOOLEAN\n" /* True if merged version in is a symlink */ - ");" - "DELETE FROM " FSL__TABLE_FVM ";", - coll, coll, coll, coll); -} - -static int fsl__renames_finalize(fsl_cx * const f){ - return fsl_cx_exec(f, - //"DROP TABLE IF EXISTS " FSL__TABLE_FVM - "DELETE FROM " FSL__TABLE_FVM); -} - -static int fsl__renames_add(fsl_cx * const f, - char const * zFnCol, - fsl_id_t vid, fsl_id_t nid, - bool reverseOk){ - int rc; - uint32_t i; /* loop counter */ - uint32_t nChng; /* # of entries in aChng */ - fsl_id_t * aChng = 0; /* Array of filename changes */ - fsl_stmt q1 = fsl_stmt_empty, q2 = fsl_stmt_empty; - fsl_db * const db = fsl_cx_db_repo(f); - rc = fsl__find_filename_changes(f, nid, vid, reverseOk, &nChng, &aChng); - if(rc) goto end; - else if(0==nChng) return 0; - rc = fsl_cx_prepare(f, &q1, - "SELECT name FROM filename WHERE fnid=?1"); - if(0==rc){ - rc = fsl_cx_prepare(f, &q2, - "SELECT name FROM filename WHERE fnid=?1"); - } - for(i=0; 0==rc && i < nChng; ++i){ - char const *zN; - char const *zV; - rc = fsl_stmt_bind_step(&q1, "R", aChng[i*2]); - if(FSL_RC_STEP_ROW==rc){ - rc = fsl_stmt_bind_step(&q2, "R", aChng[i*2+1]); - if(FSL_RC_STEP_ROW==rc) rc = 0; - } - if(rc){ - rc = fsl_cx_uplift_db_error2(f, NULL, rc); - break; - } - rc = fsl_stmt_get_text(&q1, 0, &zN, NULL); - if(0==rc) rc = fsl_stmt_get_text(&q2, 0, &zV, NULL); - if(rc){ - rc = fsl_cx_uplift_db_error2(f, db, rc); - break; - } - rc = fsl_cx_exec(f,"INSERT OR IGNORE INTO " FSL__TABLE_FVM - "(%s,fnn) VALUES(%Q,%Q)", - zFnCol, zV, zN); - if(0==rc && 0==fsl_db_changes_recent(db)){ - rc = fsl_cx_exec_multi(f, "UPDATE " FSL__TABLE_FVM - " SET %s=%Q WHERE fnn=%Q", - zFnCol, zV, zN); - } - } - end: - fsl_stmt_finalize(&q1); - fsl_stmt_finalize(&q2); - fsl_free(aChng); - return rc; -} - -/** - Part of fsl_ckout_merge() related to collecting filenames and - setting up renames. Returns 0 on success. -*/ -static int fsl__renames_tweak(fsl_cx * const f, fsl_id_t mid, - fsl_id_t pid, fsl_id_t vid, - fsl_id_t nid, - fsl_merge_opt const * const mOpt){ - int rc = 0; - char vAncestor = 'p'; /* If P is an ancestor of V then 'p', else 'n' */ - - rc = fsl__renames_init(f); - if(0==rc) rc = fsl__renames_add(f, "fn", vid, nid, false); - if(0==rc) rc = fsl__renames_add(f, "fnp", pid, nid, false); - if(0==rc) rc = fsl__renames_add(f, "fnm", mid, nid, - FSL_MERGE_TYPE_BACKOUT==mOpt->mergeType); - /* - It goes without saying that all of the SQL wizardry which follows - was implemented by D. Richard Hipp. Its usage here does not imply - any real understanding of it on the fossil-to-libfossil porter's - part. - */ - if(rc) goto end; - else if(nid!=pid){ - /* See forum thread https://fossil-scm.org/forum/forumpost/549700437b - ** - ** If a filename changes between nid and one of the other check-ins - ** pid, vid, or mid, then it might not have changed for all of them. - ** try to fill in the appropriate filename in all slots where the - ** name is missing. - ** - ** This does not work if - ** (1) The filename changes more than once in between nid and vid/mid - ** (2) Two or more filenames swap places - for example if A is renamed - ** to B and B is renamed to A. - ** The Fossil merge algorithm breaks down in those cases. It will need - ** to be completely rewritten to handle such complex cases. Such cases - ** appear to be rare, and also confusing to humans. - */ - rc = fsl_cx_exec(f, - "UPDATE OR IGNORE " FSL__TABLE_FVM - " SET fnp=vfile.pathname FROM vfile" - " WHERE fnp IS NULL" - " AND vfile.pathname = " FSL__TABLE_FVM ".fnn" - " AND vfile.vid=%" FSL_ID_T_PFMT, - pid - ); - if(rc) goto end; - rc = fsl_cx_exec(f, - "UPDATE OR IGNORE " FSL__TABLE_FVM - " SET fn=vfile.pathname FROM vfile" - " WHERE fn IS NULL" - " AND vfile.pathname = " - " coalesce(" FSL__TABLE_FVM ".fnp," FSL__TABLE_FVM ".fnn)" - " AND vfile.vid=%" FSL_ID_T_PFMT, - vid - ); - if(rc) goto end; - rc = fsl_cx_exec(f, - "UPDATE OR IGNORE " FSL__TABLE_FVM - " SET fnm=vfile.pathname FROM vfile" - " WHERE fnm IS NULL" - " AND vfile.pathname =" - " coalesce(" FSL__TABLE_FVM ".fnp," FSL__TABLE_FVM ".fnn)" - " AND vfile.vid=%" FSL_ID_T_PFMT, - mid - ); - if(rc) goto end; - rc = fsl_cx_exec(f, - "UPDATE OR IGNORE " FSL__TABLE_FVM - " SET fnp=vfile.pathname FROM vfile" - " WHERE fnp IS NULL" - " AND vfile.pathname" - " IN (" FSL__TABLE_FVM ".fnm," FSL__TABLE_FVM ".fn)" - " AND vfile.vid=%" FSL_ID_T_PFMT, - pid - ); - if(rc) goto end; - rc = fsl_cx_exec(f, - "UPDATE OR IGNORE " FSL__TABLE_FVM - " SET fn=vfile.pathname FROM vfile" - " WHERE fn IS NULL" - " AND vfile.pathname = " FSL__TABLE_FVM ".fnm" - " AND vfile.vid=%" FSL_ID_T_PFMT, - vid - ); - if(rc) goto end; - rc = fsl_cx_exec(f, - "UPDATE OR IGNORE " FSL__TABLE_FVM - " SET fnm=vfile.pathname FROM vfile" - " WHERE fnm IS NULL" - " AND vfile.pathname = " FSL__TABLE_FVM ".fn" - " AND vfile.vid=%" FSL_ID_T_PFMT, - mid - ); - if(rc) goto end; - } - assert(0==rc); - if(mOpt->baselineRid>0){ - fsl_db * const db = fsl_cx_db_repo(f); - fsl_db_err_reset(db); - vAncestor = fsl_db_exists(db, - "WITH RECURSIVE ancestor(id) AS (" - " VALUES(%" FSL_ID_T_PFMT ")" - " UNION" - " SELECT pid FROM plink, ancestor" - " WHERE cid=ancestor.id" - " AND pid!=%" FSL_ID_T_PFMT - " AND cid!=%" FSL_ID_T_PFMT ")" - "SELECT 1 FROM ancestor" - " WHERE id=%" FSL_ID_T_PFMT " LIMIT 1", - vid, nid, pid, pid - ) ? 'p' : 'n'; - assert(0==fsl_db_err_get(db, NULL, NULL)); - } - - /* - ** Add files found in V - */ - rc = fsl_cx_exec_multi(f, - "UPDATE OR IGNORE " FSL__TABLE_FVM - " SET fn=coalesce(fn%c,fnn) WHERE fn IS NULL;" - "REPLACE INTO " - FSL__TABLE_FVM "(fn,fnp,fnm,fnn,idv,ridv,islinkv,isexe,chnged)" - " SELECT pathname, fnp, fnm, fnn, id, rid, islink, vf.isexe, vf.chnged" - " FROM vfile vf" - " LEFT JOIN " FSL__TABLE_FVM " ON fn=coalesce(origname,pathname)" - " AND rid>0 AND vf.chnged NOT IN (3,5)" - " WHERE vid=%" FSL_ID_T_PFMT ";", - vAncestor, vid - ); - if(rc) goto end; - /* - ** Add files found in P - */ - rc = fsl_cx_exec_multi(f, - "UPDATE OR IGNORE " FSL__TABLE_FVM " SET fnp=coalesce(fnn," - " (SELECT coalesce(origname,pathname) FROM vfile WHERE id=idv))" - " WHERE fnp IS NULL;" - "INSERT OR IGNORE INTO " FSL__TABLE_FVM "(fnp)" - " SELECT coalesce(origname,pathname) FROM vfile WHERE vid=%" FSL_ID_T_PFMT ";", - pid - ); - if(rc) goto end; - - /* - ** Add files found in M - */ - rc = fsl_cx_exec_multi(f, - "UPDATE OR IGNORE " FSL__TABLE_FVM " SET fnm=fnp WHERE fnm IS NULL;" - "INSERT OR IGNORE INTO " FSL__TABLE_FVM "(fnm)" - " SELECT pathname FROM vfile WHERE vid=%" FSL_ID_T_PFMT ";", - mid - ); - if(rc) goto end; - - /* - ** Compute the file version ids for P and M - */ - if( pid==vid ){ - rc = fsl_cx_exec_multi(f, - "UPDATE " FSL__TABLE_FVM " SET idp=idv, ridp=ridv" - " WHERE ridv>0 AND chnged NOT IN (3,5)" - ); - }else{ - rc = fsl_cx_exec_multi(f, - "UPDATE " FSL__TABLE_FVM - " SET idp=coalesce(vfile.id,0), ridp=coalesce(vfile.rid,0)" - " FROM vfile" - " WHERE vfile.vid=%" FSL_ID_T_PFMT - " AND " FSL__TABLE_FVM ".fnp=vfile.pathname", - pid - ); - } - if(rc) goto end; - rc = fsl_cx_exec_multi(f, - "UPDATE " FSL__TABLE_FVM " SET" - " idm=coalesce(vfile.id,0)," - " ridm=coalesce(vfile.rid,0)," - " islinkm=coalesce(vfile.islink,0)," - " isexe=coalesce(vfile.isexe," FSL__TABLE_FVM ".isexe)" - " FROM vfile" - " WHERE vid=%" FSL_ID_T_PFMT " AND fnm=pathname", - mid - ); - if(rc) goto end; - - /* - ** Update the execute bit on files where it's changed from P->M but - ** not P->V - */ - if(!mOpt->dryRun){ - fsl_stmt q = fsl_stmt_empty; - rc = fsl_cx_prepare(f, &q, - "SELECT idv, fn, " FSL__TABLE_FVM ".isexe " - "FROM " FSL__TABLE_FVM ", vfile p, vfile v" - " WHERE p.id=idp AND v.id=idv AND " FSL__TABLE_FVM ".isexe!=p.isexe" - " AND v.isexe=p.isexe" - ); - if(rc) goto end; - fsl_buffer * const fnAbs = - fsl__cx_scratchpad(f)/*absolute filenames*/; - rc = fsl_buffer_reserve(fnAbs, f->ckout.dirLen + 256); - if(0==rc){ - rc = fsl_buffer_append(fnAbs, f->ckout.dir, f->ckout.dirLen); - } - while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){ - fsl_id_t const idv = fsl_stmt_g_id(&q, 0); - int const isExe = fsl_stmt_g_int32(&q, 2); - fsl_size_t nName = 0; - const char *zName = 0; - rc = fsl_stmt_get_text(&q, 1, &zName, &nName); - if(rc) break; - fnAbs->mem[f->ckout.dirLen] = 0; - fnAbs->used = f->ckout.dirLen; - rc = fsl_buffer_append(fnAbs, zName, (fsl_int_t)nName); - if(rc) break; - fsl_file_exec_set( fsl_buffer_cstr(fnAbs), !!isExe ) - /* Ignoring error */; - rc = fsl_cx_exec(f, "UPDATE vfile SET isexe=%d " - "WHERE id=%" FSL_ID_T_PFMT, - isExe, idv); - } - fsl__cx_scratchpad_yield(f, fnAbs); - fsl_stmt_finalize(&q); - } - end: - return rc; -}/*fsl__renames_tweak()*/ - -/** - Adds an an entry in the vmerge table for the given id and rid. - Returns 0 on success, uplifts any db error into f's error state. -*/ -static int fsl__vmerge_insert(fsl_cx * const f, fsl_id_t id, fsl_id_t rid){ - return fsl_cx_exec(f, - "INSERT OR IGNORE INTO vmerge(id,merge,mhash)" - "VALUES(%" FSL_ID_T_PFMT ",%" FSL_ID_T_PFMT - ",(SELECT uuid FROM blob WHERE rid=%" FSL_ID_T_PFMT "))", - id, rid, rid - ); -} - -#define fsl_merge_state_empty_m { \ - NULL/*f*/, \ - NULL/*opt*/, \ - NULL/*filename*/, \ - NULL/*prevName*/, \ - FSL_MERGE_FCHANGE_NONE/*fileChangeType*/ \ -} -/** - Initialized-with-defaults fsl_merge_state instance, - intended for use in non-const copy initialization. -*/ -const fsl_merge_state fsl_merge_state_empty = fsl_merge_state_empty_m; - -int fsl_ckout_merge(fsl_cx * const f, fsl_merge_opt const * const opt){ - /** - Notation: - - V (vid) The current checkout - M (mid) The version being merged in - P (pid) The "pivot" - the most recent common ancestor of V and M. - N (nid) The "name pivot" - for detecting renames - - What follows was initially based on: - - https://fossil-scm.org/home/file/src/merge.c?ci=e340af58a249dc09&ln=331-1065 - */ - int rc = 0; - fsl_db * const db = fsl_needs_ckout(f); - bool inTrans = false; - fsl_id_t const vid = f->ckout.rid /* current checkout (V) */; - fsl_id_t pid = 0 /* pivot RID (P): most recent common ancestor of V and M*/; - fsl_id_t mid = opt->mergeRid /* merge-in version (M) */; - fsl_id_t nid = 0 /* "name pivot" version (N) */; - bool doIntegrate = FSL_MERGE_TYPE_INTEGRATE==opt->mergeType; - fsl_stmt q = fsl_stmt_empty; - fsl_buffer * const absPath = fsl__cx_scratchpad(f); - fsl_merge_state mState = fsl_merge_state_empty; - if(!db) rc = FSL_RC_NOT_A_CKOUT; - else if(0==vid){ - rc = fsl_cx_err_set(f, FSL_RC_MISUSE, - "Cannot merge into empty top-level checkin."); - }else if(FSL_MERGE_TYPE_CHERRYPICK==opt->mergeType - && opt->baselineRid>0){ - rc = fsl_cx_err_set(f, FSL_RC_MISUSE, - "Cannot use the baselineRid option " - "with a cherry-pick merge."); - } - if(!rc) rc = fsl_cx_transaction_begin(f); - if(rc) goto end; - inTrans = true; - if((pid = opt->baselineRid)>0){ - if(!fsl_rid_is_version(f, pid)){ - rc = fsl_cx_err_set(f, FSL_RC_TYPE, - "Baseline RID #%" FSL_ID_T_PFMT - " does not refer to a checkin version."); - goto end; - } - } - if(FSL_MERGE_TYPE_CHERRYPICK==opt->mergeType - || FSL_MERGE_TYPE_BACKOUT==opt->mergeType){ - pid = fsl_db_g_id(db, 0, "SELECT pid FROM plink WHERE cid=%" - FSL_ID_T_PFMT " AND isprim", - mid); - if(0==pid){ - rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "Cannot find an ancestor " - "for to-merge RID #%" FSL_ID_T_PFMT ".", - mid); - goto end; - } - }else{ - if(opt->baselineRid<=0){ - fsl_stmt q = fsl_stmt_empty; - rc = fsl__pivot_set_primary(f, mid); - if(0==rc) rc = fsl__pivot_set_secondary(f, vid); - if(rc) goto end; - rc = fsl_cx_prepare(f, &q, "SELECT merge FROM vmerge WHERE id=0"); - while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){ - rc = fsl__pivot_set_secondary(f, fsl_stmt_g_id(&q, 0)); - } - fsl_stmt_finalize(&q); - if(0==rc) rc = fsl__pivot_find(f, false, &pid); - if(rc) goto end; - else if( pid<=0 ){ - rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, - "Cannot find a common ancestor between " - "RID #%" FSL_ID_T_PFMT - " and RID #%" FSL_ID_T_PFMT ".", - pid, vid); - goto end; - } - } - rc = fsl__pivot_set_primary(f, mid); - if(0==rc) rc = fsl__pivot_set_secondary(f, vid); - if(0==rc) rc = fsl__pivot_find(f, true, &nid); - if(rc) goto end; - else if( nid!=pid ){ - rc = fsl__pivot_set_primary(f, nid); - if(0==rc) rc = fsl__pivot_set_secondary(f, pid); - if(0==rc) rc = fsl__pivot_find(f, true, &nid); - if(rc) goto end; - } - /* ^^^ the above block is a great example of much error checking - intrudes on the library API compared to fossil(1). */ - } - if( FSL_MERGE_TYPE_BACKOUT == opt->mergeType ){ - fsl_id_t const t = pid; - pid = mid; - mid = t; - } - if(0==nid) nid = pid; - if(opt->debug){ - MARKER(("pid=%" FSL_ID_T_PFMT - ", mid=%" FSL_ID_T_PFMT - ", nid=%" FSL_ID_T_PFMT - ", vid=%" FSL_ID_T_PFMT - " integrate=%d\n", - pid, mid, nid, vid, doIntegrate)); - } - if(mid == pid){ - rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Cowardly refusing to perform " - "no-op merge from/to RID #%" FSL_ID_T_PFMT ".", - mid); - goto end; - }else if(mid == vid){ - rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Cowardly refusing to merge " - "version [%S] into itself.", f->ckout.uuid); - goto end; - }else if(!fsl_rid_is_version(f, pid)){ - rc = fsl_cx_err_set(f, FSL_RC_TYPE, - "RID #%" FSL_ID_T_PFMT " does not refer " - "to a checkin version.", pid); - goto end; - }else{ - uint32_t missing = 0; - rc = fsl_vfile_load(f, mid, false, &missing); - if(0==rc && 0==missing){ - rc = fsl_vfile_load(f, pid, false, &missing); - } - if(0==rc && missing){ - rc = fsl_cx_err_set(f, FSL_RC_PHANTOM, - "Cannot merge due to missing content in one " - "or more participating versions."); - } - if(rc) goto end; - } - if( doIntegrate && (fsl_content_is_private(f, mid) - || !fsl_rid_is_leaf(f, mid)) ){ - doIntegrate = false; - } - if(opt->scanForChanges){ - rc = fsl_vfile_changes_scan(f, vid, FSL_VFILE_CKSIG_ENOTFILE); - if(rc) goto end; - } - rc = fsl__renames_tweak(f, mid, pid, vid, nid, opt); - if(rc) goto end; - if(opt->debug){ - MARKER(("pid=%" FSL_ID_T_PFMT - ", mid=%" FSL_ID_T_PFMT - ", nid=%" FSL_ID_T_PFMT - ", vid=%" FSL_ID_T_PFMT - " integrate=%d\n", - pid, mid, nid, vid, doIntegrate)); - MARKER(("Contents of " FSL__TABLE_FVM ":\n")); - if(1==opt->debug){ - fsl_db_each(db, fsl_stmt_each_f_dump, NULL, - "SELECT fn,fnp,fnm,chnged,ridv,ridp,ridm, " - " isexe,islinkv islinkm, fnn " - " FROM " FSL__TABLE_FVM - " WHERE chnged OR (ridv!=ridm AND ridm!=ridp)" - " ORDER BY fn, fnp, fnm "); - }else{ - fsl_db_each(db, fsl_stmt_each_f_dump, NULL, - "SELECT * FROM " FSL__TABLE_FVM - " ORDER BY fn, fnp, fnm"); - } - MARKER(("Contents of " FSL__TABLE_PIVOT ":\n")); - fsl_db_each(db, fsl_stmt_each_f_dump, NULL, - "SELECT * FROM " FSL__TABLE_PIVOT - " ORDER BY src DESC, rid, pending, src"); - MARKER(("Contents of [vmerge]:\n")); - fsl_db_each(db, fsl_stmt_each_f_dump, NULL, - "SELECT * FROM vmerge order by merge"); - } - mState.f = f; - mState.opt = opt; -#define MCB(FCT,RMI,FN) \ - mState.fileChangeType = FCT; \ - mState.fileRmInfo = RMI; \ - mState.filename = FN; \ - rc = opt->callback(&mState); \ - mState.priorName = NULL -#define MCB2(FCT,FN) MCB(FCT,FSL_CKUP_RM_NOT,FN) - /************************************************************************ - ** All of the information needed to do the merge is now contained in the - ** FV table. Starting here, we begin to actually carry out the merge. - ** - ** First, find files in M and V but not in P and report conflicts. - ** The file in M will be ignored. It will be treated as if it - ** does not exist. - */ - rc = fsl_cx_prepare(f, &q, "SELECT idm FROM " FSL__TABLE_FVM - " WHERE idp=0 AND idv>0 AND idm>0"); - if(rc) goto end; - while( 0==rc && FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q)) ){ - fsl_id_t const idm = fsl_stmt_g_id(&q, 0); - rc = fsl_cx_exec(f, "UPDATE " FSL__TABLE_FVM - " SET idm=0 WHERE idm=%" FSL_ID_T_PFMT, idm); - if(0==rc && opt->callback){ - fsl_buffer * const bName = fsl__cx_scratchpad(f); - rc = fsl_db_get_buffer(db, bName, false, - "SELECT pathname FROM vfile WHERE id=%" FSL_ID_T_PFMT, - idm); - if(0==rc){ - MCB2(FSL_MERGE_FCHANGE_CONFLICT_ANCESTOR, - fsl_buffer_cstr(bName)); - } - fsl__cx_scratchpad_yield(f, bName); - } - } - fsl_stmt_finalize(&q); - switch(rc){ - case 0: - case FSL_RC_STEP_DONE: rc = 0; break; - default: goto end; - } - - /* - ** Find files that have changed from P->M but not P->V. - ** Copy the M content over into V. - */ - rc = fsl_cx_prepare(f, &q, - "SELECT idv, ridm, fn, islinkm FROM " FSL__TABLE_FVM - " WHERE idp>0 AND idv>0 AND idm>0" - " AND ridm!=ridp AND ridv=ridp AND NOT chnged" - ); - if(rc) goto end; - while( 0==rc && (FSL_RC_STEP_ROW==fsl_stmt_step(&q)) ){ - fsl_id_t const idv = fsl_stmt_g_id(&q, 0); - fsl_id_t const ridm = fsl_stmt_g_id(&q, 1); - int const islinkm = fsl_stmt_g_int32(&q, 3); - /* Copy content from idm over into idv. Overwrite idv. */ - if(opt->debug){ - const char *zName = fsl_stmt_g_text(&q, 2, NULL); - MARKER(("COPIED (M)=>(V) %s\n", zName)); - } - if( !opt->dryRun ){ - //undo_save(zName); - rc = fsl_cx_exec(f, - "UPDATE vfile SET mtime=0, mrid=%" FSL_ID_T_PFMT - ", chnged=%d, islink=%d," - " mhash=CASE WHEN rid<>%" FSL_ID_T_PFMT - " THEN (SELECT uuid FROM blob WHERE blob.rid=%" FSL_ID_T_PFMT ") END" - " WHERE id=%" FSL_ID_T_PFMT, - ridm, doIntegrate ? 4 : 2, islinkm, ridm, ridm, idv - ); - if(0==rc) rc = fsl__vfile_to_ckout(f, idv, NULL); - } - if(0==rc && opt->callback){ - const char *zName = 0; - rc = fsl_stmt_get_text(&q, 2, &zName, NULL); - if(0==rc){ - MCB2(FSL_MERGE_FCHANGE_COPIED,zName); - } - } - } - fsl_stmt_finalize(&q); - switch(rc){ - case 0: - case FSL_RC_STEP_DONE: rc = 0; break; - default: goto end; - } - - /* - ** Do a three-way merge on files that have changes on both P->M and P->V. - */ - rc = fsl_cx_prepare(f, &q, - "SELECT ridm, idv, ridp, ridv," - " FSL_GLOB('binary-glob'," FSL__TABLE_FVM ".fn)," - " fn, isexe, islinkv, islinkm FROM " FSL__TABLE_FVM - " WHERE idp>0 AND idv>0 AND idm>0" - " AND ridm!=ridp AND (ridv!=ridp OR chnged)" - ); - if(0==rc){ - rc = fsl_buffer_append( absPath, f->ckout.dir, (fsl_int_t)f->ckout.dirLen); - } - while( 0==rc && (FSL_RC_STEP_ROW==fsl_stmt_step(&q)) ){ - fsl_id_t const ridm = fsl_stmt_g_id(&q, 0); - fsl_id_t const idv = fsl_stmt_g_id(&q, 1); - fsl_id_t const ridp = fsl_stmt_g_id(&q, 2); - fsl_id_t const ridv = fsl_stmt_g_id(&q, 3); - int32_t isBinary = fsl_stmt_g_int32(&q, 4); - int32_t const isExe = fsl_stmt_g_int32(&q, 6); - int32_t const islinkv = fsl_stmt_g_int32(&q, 7); - int32_t const islinkm = fsl_stmt_g_int32(&q, 8); - char const *zFullPath; - const char *zName = NULL; - fsl_size_t nName = 0; - rc = fsl_stmt_get_text(&q, 5, &zName, &nName); - if(rc){ - rc = fsl_cx_uplift_db_error2(f, NULL, rc); - break; - } - /* Do a 3-way merge of idp->idm into idp->idv. The results go into idv. */ - if(opt->debug){ - MARKER(("MERGE %s (pivot=%d v1=%d v2=%d)\n", - zName, (int)ridp, (int)ridm, (int)ridv)); - } - if( islinkv || islinkm ){ - //MARKER(("***** Cannot merge symlink %s\n", zName)); - if(opt->callback){ - MCB2(FSL_MERGE_FCHANGE_CONFLICT_SYMLINK,zName); - } - }else if(isBinary){ - if(opt->callback){ - MCB2(FSL_MERGE_FCHANGE_CONFLICT_BINARY,zName); - } - }else{ - fsl_buffer m = fsl_buffer_empty; - fsl_buffer p = fsl_buffer_empty; - fsl_buffer r = fsl_buffer_empty; - //if( !dryRunFlag ) undo_save(zName); - if(opt->debug){ - MARKER(("Merge: %s\n", zName)); - } - absPath->used = f->ckout.dirLen; - rc = fsl_buffer_append(absPath, zName, (fsl_int_t)nName); - if(rc) break; - zFullPath = fsl_buffer_cstr(absPath); - rc = fsl_content_get(f, ridp, &p); - if(0==rc) rc = fsl_content_get(f, ridm, &m); - if(0==rc){ - //unsigned mergeFlags = dryRunFlag ? MERGE_DRYRUN : 0; - //if(keepMergeFlag!=0) mergeFlags |= MERGE_KEEP_FILES; - //rc = merge_3way(&p, zFullPath, &m, &r, mergeFlags); - unsigned int nConflict = 0; - fsl_buffer * const contentLocal = fsl__cx_content_buffer(f); - rc = fsl_buffer_fill_from_filename(contentLocal, zFullPath); - if(0==rc){ - rc = fsl_buffer_merge3( &p, contentLocal, &m, &r, &nConflict ); - switch(rc){ - case 0: - if(opt->debug){ - MARKER(("%swriting merged file w/ %u conflict(s): %s\n", - opt->dryRun ? "Not " : "", nConflict, zName)); - } - if(!opt->dryRun){ - rc = fsl_buffer_to_filename(&r, zFullPath); - if(0==rc) fsl_file_exec_set(zFullPath, !!isExe); - } - break; - case FSL_RC_DIFF_BINARY: - case FSL_RC_TYPE: - /* 2021-12-15: fsl_buffer_merge3() currently returns - FSL_RC_TYPE for binary, but "should" return - FSL_RC_DIFF_BINARY. Changing that is TODO. */ - rc = 0; isBinary = 1; - break; - default: break; - } - } - fsl__cx_content_buffer_yield(f); - if(0==rc && !isBinary){ - rc = fsl_cx_exec(f, "UPDATE vfile " - "SET mtime=0 WHERE id=%" FSL_ID_T_PFMT, idv); - } - if(0==rc && opt->callback){ - fsl_merge_fchange_e const fce = - isBinary - ? FSL_MERGE_FCHANGE_CONFLICT_BINARY - : (nConflict - ? FSL_MERGE_FCHANGE_CONFLICT_MERGED - : FSL_MERGE_FCHANGE_MERGED); - MCB2(fce,zName); - } - } - fsl_buffer_clear(&p); - fsl_buffer_clear(&m); - fsl_buffer_clear(&r); - } - if(0==rc) rc = fsl__vmerge_insert(f, idv, ridm); - } - fsl_stmt_finalize(&q); - switch(rc){ - case 0: - case FSL_RC_STEP_DONE: rc = 0; break; - default: goto end; - } - - /* - ** Drop files that are in P and V but not in M - */ - rc = fsl_cx_prepare(f, &q, - "SELECT idv, fn, chnged FROM " FSL__TABLE_FVM - " WHERE idp>0 AND idv>0 AND idm=0" - ); - while( 0==rc && FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&q)) ){ - fsl_id_t const idv = fsl_stmt_g_id(&q, 0); - int32_t const chnged = fsl_stmt_g_int32(&q, 2); - const char *zName; - fsl_size_t nName = 0; - rc = fsl_stmt_get_text(&q, 1, &zName, &nName); - if(rc) break; - /* Delete the file idv */ - if(opt->debug){ - MARKER(("DELETE %s\n", zName)); - } - if( chnged ){ - if(opt->debug){ - MARKER(("WARNING: local edits lost for %s", zName)); - } - } - //if( !dryRunFlag ) undo_save(zName); - rc = fsl_cx_exec(f, - "UPDATE vfile SET deleted=1 WHERE id=%" FSL_ID_T_PFMT, idv - ); - if(!chnged && !opt->dryRun ){ - /* ^^^ this differs from fossil(1), which always deletes the - local file regardless of whether it has local changes. */ - absPath->used = f->ckout.dirLen; - rc = fsl_buffer_append(absPath, zName, (fsl_int_t)nName); - if(0==rc) fsl_file_unlink(fsl_buffer_cstr(absPath)); - } - if(opt->callback){ - fsl_ckup_rm_state_e const rme = - chnged ? FSL_CKUP_RM_KEPT : FSL_CKUP_RM; - MCB(FSL_MERGE_FCHANGE_RM,rme,zName); - } - } - fsl_stmt_finalize(&q); - switch(rc){ - case 0: - case FSL_RC_STEP_DONE: rc = 0; break; - default: goto end; - } - - /* For certain sets of renames (e.g. A -> B and B -> A), a file that is - ** being renamed must first be moved to a temporary location to avoid - ** being overwritten by another rename operation. A row is added to the - ** TMPRN table for each of these temporary renames. - */ - rc = fsl_cx_exec_multi(f, - "CREATE TEMP TABLE IF NOT EXISTS tmprn(fn UNIQUE, tmpfn);" - "DELETE FROM tmprn;" - ); - - /* - ** Rename files that have taken a rename on P->M but which keep the same - ** name on P->V. If a file is renamed on P->V only or on both P->V and - ** P->M then we retain the V name of the file. - */ - rc = fsl_cx_prepare(f, &q, - "SELECT idv, fnp, fnm, isexe FROM " FSL__TABLE_FVM - " WHERE idv>0 AND idp>0 AND idm>0 AND fnp=fn AND fnm!=fnp" - ); - while( 0==rc && FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&q)) ){ - fsl_id_t const idv = fsl_stmt_g_id(&q, 0); - int32_t const isExe = fsl_stmt_g_int32(&q, 3); - const char *zOldName; - const char *zNewName; - rc = fsl_stmt_get_text(&q, 1, &zOldName, NULL); - if(0==rc) rc = fsl_stmt_get_text(&q, 2, &zNewName, NULL); - if(rc) break; - if(opt->debug){ - MARKER(("RENAME %s -> %s\n", zOldName, zNewName)); - } - //if( !dryRunFlag ) undo_save(zOldName); - //if( !dryRunFlag ) undo_save(zNewName); - rc = fsl_cx_exec_multi(f, - "UPDATE vfile SET pathname=NULL, origname=pathname" - " WHERE vid=%" FSL_ID_T_PFMT " AND pathname=%Q;" - "UPDATE vfile SET pathname=%Q, origname=coalesce(origname,pathname)" - " WHERE id=%" FSL_ID_T_PFMT ";", - vid, zNewName, zNewName, idv - ); - if(rc) break; - if( !opt->dryRun ){ - fsl_buffer * const bFullOld = fsl__cx_scratchpad(f); - fsl_buffer * const bFullNew = fsl__cx_scratchpad(f); - fsl_buffer * const bTmp = fsl__cx_scratchpad(f); - char const *zFullOldPath; - char const *zFullNewPath; - bool const realSymlinks = fsl_cx_allows_symlinks(f, false); - rc = fsl_db_get_buffer(db, bFullOld, false, - "SELECT tmpfn FROM tmprn WHERE fn=%Q", zOldName); - if(!rc && !bFullOld->used){ - rc = fsl_buffer_appendf(bFullOld, "%s%s", f->ckout.dir, zOldName); - } - if(0==rc) rc = fsl_buffer_appendf(bFullNew, "%s%s", f->ckout.dir, zNewName); - if(rc) goto merge_rename_end; - zFullOldPath = fsl_buffer_cstr(bFullOld); - zFullNewPath = fsl_buffer_cstr(bFullNew); - if( fsl_file_size(zFullNewPath)>=0 ){ - rc = fsl_file_tempname(bTmp, "", NULL); - if(rc) goto merge_rename_end; - rc = fsl_cx_exec(f, "INSERT INTO tmprn(fn,tmpfn) VALUES(%Q,%B)", - zNewName, bTmp); - if(rc) goto merge_rename_end; - rc = fsl_is_symlink(zFullNewPath) - ? fsl__symlink_copy(zFullNewPath, fsl_buffer_cstr(bTmp), realSymlinks) - : fsl_file_copy(zFullNewPath, fsl_buffer_cstr(bTmp)); - if(rc){ - rc = fsl_cx_err_set(f, rc, "Error copying file [%s].", - zFullNewPath); - } - if(rc) goto merge_rename_end; - } - rc = fsl_is_symlink(zFullOldPath) - ? fsl__symlink_copy(zFullOldPath, zFullNewPath, realSymlinks) - : fsl_file_copy(zFullOldPath, zFullNewPath); - if(0==rc){ - fsl_file_exec_set(zFullNewPath, !!isExe); - fsl_file_unlink(zFullOldPath); - /* ^^^ Ignore errors: not critical here */ - } - merge_rename_end: - fsl__cx_scratchpad_yield(f, bFullOld); - fsl__cx_scratchpad_yield(f, bFullNew); - fsl__cx_scratchpad_yield(f, bTmp); - } - if(0==rc && opt->callback){ - mState.priorName = zOldName; - MCB2(FSL_MERGE_FCHANGE_RENAMED,zNewName); - } - } - fsl_stmt_finalize(&q); - switch(rc){ - case 0: - case FSL_RC_STEP_DONE: rc = 0; break; - default: goto end; - } - /** - TODO??? The above loop can leave temp files laying around. We - should(?) to (for each tmpfn in tmprn => - unlink(tmpfn)). fossil(1) does not do that, but that seems like a - bug. - */ - /* A file that has been deleted and replaced by a renamed file will have a - ** NULL pathname. Change it to something that makes the output of "status" - ** and similar commands make sense for such files and that will (most likely) - ** not be an actual existing pathname. - */ - rc = fsl_cx_exec(f, - "UPDATE vfile SET pathname=origname || ' (overwritten by rename)'" - " WHERE pathname IS NULL" - ); - if(rc) goto end; - /* - ** Insert into V any files that are not in V or P but are in M. - */ - rc = fsl_cx_prepare(f, &q, - "SELECT idm, fnm FROM " FSL__TABLE_FVM - " WHERE idp=0 AND idv=0 AND idm>0" - ); - while( 0==rc && FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&q)) ){ - fsl_id_t const idm = fsl_stmt_g_id(&q, 0); - const char *zName; - fsl_buffer * const bFullName = fsl__cx_scratchpad(f); - rc = fsl_cx_exec(f, - "REPLACE INTO vfile(vid,chnged,deleted,rid,mrid," - "isexe,islink,pathname,mhash)" - " SELECT %" FSL_ID_T_PFMT ",%d,0,rid,mrid,isexe,islink,pathname," - "CASE WHEN rid<>mrid" - " THEN (SELECT uuid FROM blob WHERE blob.rid=vfile.mrid) END " - "FROM vfile WHERE id=%" FSL_ID_T_PFMT, - vid, doIntegrate - ? FSL_VFILE_CHANGE_INTEGRATE_MOD - : FSL_VFILE_CHANGE_MERGE_ADD, - idm); - if(0==rc) rc = fsl_stmt_get_text(&q, 1, &zName, NULL); - if(0==rc) rc = fsl_buffer_appendf(bFullName, "%s%s", f->ckout.dir, zName); - if(rc) goto merge_add_end; - fsl_merge_fchange_e fchange; - if( fsl_is_file_or_link(fsl_buffer_cstr(bFullName)) - && !fsl_db_exists(db, "SELECT 1 FROM fv WHERE fn=%Q", zName) ){ - if(opt->debug){ - MARKER(("ADDED %s (overwrites an unmanaged file)\n", zName)); - } - fchange = FSL_MERGE_FCHANGE_CONFLICT_ADDED_UNMANAGED; - }else{ - if(opt->debug){ - MARKER(("ADDED %s\n", zName)); - } - fchange = FSL_MERGE_FCHANGE_ADDED; - } - if( !opt->dryRun ){ - //undo_save(zName); - rc = fsl__vfile_to_ckout(f, idm, NULL); - } - merge_add_end: - fsl__cx_scratchpad_yield(f, bFullName); - if(0==rc && opt->callback){ - MCB2(fchange,zName); - } - } - fsl_stmt_finalize(&q); - switch(rc){ - case 0: - case FSL_RC_STEP_DONE: rc = 0; break; - default: goto end; - } - - fsl_id_t vmergeWho = 0; - switch(opt->mergeType){ - case FSL_MERGE_TYPE_CHERRYPICK: - vmergeWho = mid; - /* For a cherry-pick merge, make the default check-in comment the same - ** as the check-in comment on the check-in that is being merged in. */ - if(0==rc){ - rc = fsl_cx_exec(f, - "REPLACE INTO vvar(name,value)" - " SELECT 'ci-comment', coalesce(ecomment,comment) FROM event" - " WHERE type='ci' AND objid=%" FSL_ID_T_PFMT, - mid); - } - break; - case FSL_MERGE_TYPE_BACKOUT: - vmergeWho = pid; - break; - case FSL_MERGE_TYPE_INTEGRATE: - case FSL_MERGE_TYPE_NORMAL: - vmergeWho = mid; - break; - } - if(0==rc){ - rc = fsl__vmerge_insert(f, (int)opt->mergeType, vmergeWho); - } -#undef MCB -#undef MCB2 - end: - if(opt->debug){ - MARKER(("fsl_ckout_merge() made it to the end with rc %s.\n", - fsl_rc_cstr(rc))); - } - fsl__cx_scratchpad_yield(f, absPath); - if(0==rc){ - fsl__renames_finalize(f); - } - fsl_stmt_finalize(&q); - if(inTrans){ - if(0==rc){ - rc = fsl_vfile_unload_except(f, vid); - // ^^^ not strictly needed unless we're NOT rolling back - } - int const rc2 = fsl_cx_transaction_end(f, 0!=rc); - if(rc2 && 0==rc) rc = rc2; - } - return rc; -} - -#undef FSL__TABLE_PIVOT -#undef FSL__TABLE_FVM - -#undef MARKER -/* end of file ./src/merge.c */ -/* start of file ./src/merge3.c */ +/* end of file md5.c */ +/* start of file merge3.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -33052,51 +31271,44 @@ } return true; } /** - pSrc contains an edited file where aC[] describes the edit, - starting at index i. Part of pSrc has already been output. This - routine outputs additional lines of pSrc - lines that correspond to - the next sz lines of the original unedited file. + pSrc contains an edited file where aC[] describes the edit. Part + of pSrc has already been output. This routine outputs additional + lines of pSrc - lines that correspond to the next sz lines of the + original unedited file. Note that sz counts the number of lines of text in the original file, but text is output from the edited file, so the number of lines transfer to pOut might be different from sz. Fewer lines appear in pOut if there are deletes. More lines appear if there are inserts. The aC[] array is updated and the new index into aC[] is returned - via the newIndex. The running line number count is updated via - pLn. + via the final argument. Returns 0 on success, FSL_RC_OOM on allocation error. */ static int output_one_side(fsl_buffer *pOut, fsl_buffer *pSrc, int *aC, int i, int sz, - int *newIndex, - int *pLn){ + int *newIndex){ int rc = 0; while( sz>0 ){ if( aC[i]==0 && aC[i+1]==0 && aC[i+2]==0 ) break; if( aC[i]>=sz ){ rc = fsl_buffer_copy_lines(pOut, pSrc, sz); - *pLn += sz; if(rc) break; aC[i] -= sz; break; } rc = fsl_buffer_copy_lines(pOut, pSrc, aC[i]); - *pLn += aC[i]; - if(!rc){ - rc = fsl_buffer_copy_lines(pOut, pSrc, aC[i+2]); - *pLn += aC[i+2]; - } + if(!rc) rc = fsl_buffer_copy_lines(pOut, pSrc, aC[i+2]); if(rc) break; sz -= aC[i] + aC[i+1]; i += 3; } if(!rc) *newIndex = i; @@ -33128,11 +31340,12 @@ /** Ensure that the text in p, if not empty, ends with a new line. If useCrLf is true adds "\r\n" otherwise "\n". Returns 0 on success or p is empty, and FSL_RC_OOM on OOM. */ -static int ensure_line_end(fsl_buffer *p, bool useCrLf){ +static +int ensure_line_end(fsl_buffer *p, bool useCrLf){ int rc = 0; if( !p->used ) return 0; if( p->mem[p->used-1]!='\n' ){ rc = fsl_buffer_append(p, useCrLf ? "\r\n" : "\n", useCrLf ? 2 : 1); } @@ -33175,50 +31388,28 @@ by fossil. */ static const char *const mergeMarker[] = { /*123456789 123456789 123456789 123456789 123456789 123456789 123456789*/ - "<<<<<<< BEGIN MERGE CONFLICT: local copy shown first <<<<<<<<<<<<", - "||||||| COMMON ANCESTOR content follows |||||||||||||||||||||||||", - "======= MERGED IN content follows ===============================", - ">>>>>>> END MERGE CONFLICT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" -}; -enum { -/* strlen() of each mergeMarker entry. */ -MEMA_LENGTH = 65 -}; -/** - Asserts, the first time it is called, that all mergeMarker entries - are of the same length and returns that length. -*/ -static inline fsl_int_t assert_mema_lengths(){ + "<<<<<<< BEGIN MERGE CONFLICT: local copy shown first <<<<<<<<<<<<<<<", + "||||||| COMMON ANCESTOR content follows ||||||||||||||||||||||||||||", + "======= MERGED IN content follows ==================================", + ">>>>>>> END MERGE CONFLICT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" +}; + +static fsl_int_t assert_mema_lengths(){ + static const fsl_int_t mmLen = 68; static bool once = true; if(once){ once = false; assert(sizeof(mergeMarker)/sizeof(mergeMarker[0]) == 4); - assert((fsl_int_t)fsl_strlen(mergeMarker[0])==MEMA_LENGTH); - assert((fsl_int_t)fsl_strlen(mergeMarker[1])==MEMA_LENGTH); - assert((fsl_int_t)fsl_strlen(mergeMarker[2])==MEMA_LENGTH); - assert((fsl_int_t)fsl_strlen(mergeMarker[3])==MEMA_LENGTH); - } - return MEMA_LENGTH; -} - -/* -** Write out mergeMarker[iMark] to pOut, along with the given line -** number (if>0). Returns 0 on success, FSL_RC_OOM on allocation -** error. -*/ -static int append_merge_mark(fsl_buffer * const pOut, int iMark, - int ln, bool useCrLf){ - int rc = ensure_line_end(pOut, useCrLf); - if(0==rc){ - rc = fsl_buffer_append(pOut, mergeMarker[iMark], MEMA_LENGTH); - if( 0==rc && ln>0 ) rc = fsl_buffer_appendf(pOut, " (line %d)", ln); - if(0==rc) rc = ensure_line_end(pOut, useCrLf); - } - return rc; + assert((fsl_int_t)fsl_strlen(mergeMarker[0])==mmLen); + assert((fsl_int_t)fsl_strlen(mergeMarker[1])==mmLen); + assert((fsl_int_t)fsl_strlen(mergeMarker[2])==mmLen); + assert((fsl_int_t)fsl_strlen(mergeMarker[3])==mmLen); + } + return mmLen; } int fsl_buffer_merge3(fsl_buffer * const pPivot, fsl_buffer * const pV1, fsl_buffer * const pV2, @@ -33230,12 +31421,11 @@ int nCpy, nDel, nIns; /* Number of lines to copy, delete, or insert */ int limit1, limit2; /* Sizes of aC1[] and aC2[] */ int rc = 0; unsigned int nConflict = 0; /* Number of merge conflicts seen so far */ bool useCrLf = false; - int ln1, ln2, lnPivot; /* Line numbers for all files */ - assert_mema_lengths(); + const fsl_int_t mmLen = assert_mema_lengths(); #define RC if(rc) { \ MARKER(("rc=%s\n", fsl_rc_cstr(rc))); goto end; } (void)0 fsl_buffer_reuse(pOut); /* Merge results stored in pOut */ @@ -33263,12 +31453,12 @@ ** is the number of lines of text to copy directly from the pivot, ** the second integer is the number of lines of text to omit from the ** pivot, and the third integer is the number of lines of text that are ** inserted. The edit array ends with a triple of 0,0,0. */ - rc = fsl_diff_v2_raw(pPivot, pV1, NULL, &aC1); - if(!rc) rc = fsl_diff_v2_raw(pPivot, pV2, NULL, &aC2); + rc = fsl__diff_text_raw(pPivot, pV1, 0, &aC1); + if(!rc) rc = fsl__diff_text_raw(pPivot, pV2, 0, &aC2); RC; assert(aC1 && aC2); /* Rewind inputs: Needed to reconstruct output */ fsl_buffer_rewind(pV1); @@ -33294,11 +31484,10 @@ ** which is written into pOut. i1 and i2 are multiples of 3 which are ** indices into aC1[] and aC2[] to the edit triple currently being ** processed */ i1 = i2 = 0; - ln1 = ln2 = lnPivot = 1; while( i10 && aC2[i2]>0 ){ /* Output text that is unchanged in both V1 and V2 */ nCpy = mymin(aC1[i1], aC2[i2]); FDEBUG( printf("COPY %d\n", nCpy); ) rc = fsl_buffer_copy_lines(pOut, pPivot, (fsl_size_t)nCpy); - lnPivot += nCpy; if(!rc) rc = fsl_buffer_copy_lines(0, pV1, (fsl_size_t)nCpy); - ln1 += nCpy; if(!rc) rc = fsl_buffer_copy_lines(0, pV2, (fsl_size_t)nCpy); - ln2 += nCpy; RC; aC1[i1] -= nCpy; aC2[i2] -= nCpy; }else if( aC1[i1] >= aC2[i2+1] && aC1[i1]>0 && aC2[i2+1]+aC2[i2+2]>0 ){ @@ -33320,15 +31506,12 @@ /* Output edits to V2 that occurs within unchanged regions of V1 */ nDel = aC2[i2+1]; nIns = aC2[i2+2]; FDEBUG( printf("EDIT -%d+%d left\n", nDel, nIns); ) rc = fsl_buffer_copy_lines(0, pPivot, (fsl_size_t)nDel); - lnPivot += nDel; if(!rc) rc = fsl_buffer_copy_lines(0, pV1, (fsl_size_t)nDel); - ln1 += nDel; if(!rc) rc = fsl_buffer_copy_lines(pOut, pV2, (fsl_size_t)nIns); - ln2 += nIns; RC; aC1[i1] -= nDel; i2 += 3; }else if( aC2[i2] >= aC1[i1+1] && aC2[i2]>0 && aC1[i1+1]+aC1[i1+2]>0 ){ @@ -33335,15 +31518,12 @@ /* Output edits to V1 that occur within unchanged regions of V2 */ nDel = aC1[i1+1]; nIns = aC1[i1+2]; FDEBUG( printf("EDIT -%d+%d right\n", nDel, nIns); ) rc = fsl_buffer_copy_lines(0, pPivot, (fsl_size_t)nDel); - lnPivot += nDel; if(!rc) fsl_buffer_copy_lines(0, pV2, (fsl_size_t)nDel); - ln2 += nDel; if(!rc) fsl_buffer_copy_lines(pOut, pV1, (fsl_size_t)nIns); - ln1 += nIns; aC2[i2] -= nDel; i1 += 3; }else if( sameEdit(&aC1[i1], &aC2[i2], pV1, pV2) ){ /* Output edits that are identical in both V1 and V2. */ @@ -33350,18 +31530,16 @@ assert( aC1[i1]==0 ); nDel = aC1[i1+1]; nIns = aC1[i1+2]; FDEBUG( printf("EDIT -%d+%d both\n", nDel, nIns); ) rc = fsl_buffer_copy_lines(0, pPivot, (fsl_size_t)nDel); - lnPivot += nDel; if(!rc) fsl_buffer_copy_lines(pOut, pV1, (fsl_size_t)nIns); - ln1 += nIns; if(!rc) fsl_buffer_copy_lines(0, pV2, (fsl_size_t)nIns); - ln2 += nIns; i1 += 3; i2 += 3; - }else{ + }else + { /* We have found a region where different edits to V1 and V2 overlap. ** This is a merge conflict. Find the size of the conflict, then ** output both possible edits separated by distinctive marks. */ int sz = 1; /* Size of the conflict in lines */ @@ -33368,24 +31546,31 @@ ++nConflict; while( !ends_at_CPY(&aC1[i1], sz) || !ends_at_CPY(&aC2[i2], sz) ){ ++sz; } FDEBUG( printf("CONFLICT %d\n", sz); ) - rc = append_merge_mark(pOut, 0, ln1, useCrLf); - if(!rc) rc = output_one_side(pOut, pV1, aC1, i1, sz, &i1, &ln1); + rc = ensure_line_end(pOut, useCrLf); + if(!rc) rc = fsl_buffer_append(pOut, mergeMarker[0], mmLen); + if(!rc) rc = ensure_line_end(pOut, useCrLf); + RC; + rc = output_one_side(pOut, pV1, aC1, i1, sz, &i1); + if(!rc) rc = ensure_line_end(pOut, useCrLf); RC; - - rc = append_merge_mark(pOut, 1, lnPivot, useCrLf); + rc = fsl_buffer_append(pOut, mergeMarker[1], mmLen); + if(!rc) rc = ensure_line_end(pOut, useCrLf); if(!rc) rc = fsl_buffer_copy_lines(pOut, pPivot, sz); - lnPivot += sz; - RC; - - rc = append_merge_mark(pOut, 2, ln2, useCrLf); - if(!rc) rc = output_one_side(pOut, pV2, aC2, i2, sz, &i2, &ln2); - if(!rc) rc = append_merge_mark(pOut, 3, -1, useCrLf); - RC; - } + if(!rc) rc = ensure_line_end(pOut, useCrLf); + RC; + rc = fsl_buffer_append(pOut, mergeMarker[2], mmLen); + if(!rc) rc = ensure_line_end(pOut, useCrLf); + if(!rc) rc = output_one_side(pOut, pV2, aC2, i2, sz, &i2); + if(!rc) rc = ensure_line_end(pOut, useCrLf); + RC; + rc = fsl_buffer_append(pOut, mergeMarker[3], mmLen); + if(!rc) rc = ensure_line_end(pOut, useCrLf); + RC; + } /* If we are finished with an edit triple, advance to the next ** triple. */ if( i1mem; fsl_size_t const n = p->used - len + 1; for(i=0; i -#if FSL_PLATFORM_IS_WINDOWS +#ifdef _WIN32 #include #include +/* + Print a fatal error and quit. +*/ +static void win32_fatal_error(const char *zMsg){ + /*fossil_fatal("%s", zMsg); TODO: what to do here? */ +} #else #include #include #include #endif @@ -33506,11 +31696,11 @@ # define INT_TO_PTR(X) ((void*)(X)) # define PTR_TO_INT(X) ((int)(X)) #endif -#if FSL_PLATFORM_IS_WINDOWS +#ifdef _WIN32 /* On windows, create a child process and specify the stdin, stdout, and stderr channels for that process to use. Return the number of errors. @@ -33550,12 +31740,11 @@ if( rc ){ CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); *pChildPid = pi.dwProcessId; }else{ - //fsl__fatal(FSL_RC_ERROR, "cannot create child process"); - rc = FSL_RC_ERROR; + win32_fatal_error("cannot create child process"); } return rc!=0; } #endif @@ -33572,11 +31761,11 @@ must be passed to fsl_pclose2() to properly clean up. Return 0 on success, non-0 on error. */ int fsl_popen2(const char *zCmd, int *pfdIn, FILE **ppOut, int *pChildPid){ -#if FSL_PLATFORM_IS_WINDOWS +#ifdef _WIN32 /* FIXME: port these win32_fatal_error() bits to error codes. */ HANDLE hStdinRd, hStdinWr, hStdoutRd, hStdoutWr, hStderr; SECURITY_ATTRIBUTES saAttr; DWORD childPid = 0; int fd; @@ -33584,18 +31773,16 @@ saAttr.nLength = sizeof(saAttr); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; hStderr = GetStdHandle(STD_ERROR_HANDLE); if( !CreatePipe(&hStdoutRd, &hStdoutWr, &saAttr, 4096) ){ - //win32_fatal_error("cannot create pipe for stdout"); - return FSL_RC_IO; + win32_fatal_error("cannot create pipe for stdout"); } SetHandleInformation( hStdoutRd, HANDLE_FLAG_INHERIT, FALSE); if( !CreatePipe(&hStdinRd, &hStdinWr, &saAttr, 4096) ){ - //win32_fatal_error("cannot create pipe for stdin"); - return FSL_RC_IO; + win32_fatal_error("cannot create pipe for stdin"); } SetHandleInformation( hStdinWr, HANDLE_FLAG_INHERIT, FALSE); win32_create_child_process(fsl_utf8_to_unicode(zCmd), hStdinRd, hStdoutWr, hStderr,&childPid); @@ -33645,12 +31832,11 @@ close(1); fd = dup(pin[1]); if( fd!=1 ) nErr++; close(pin[0]); close(pin[1]); - execl("/bin/sh", "/bin/sh", "-c", zCmd, (char*)0) - /* doesn't return on success */; + execl("/bin/sh", "/bin/sh", "-c", zCmd, (char*)0); return fsl_errno_to_rc(errno, FSL_RC_ERROR); }else{ /* This is the parent process */ close(pin[1]); *pfdIn = pin[0]; @@ -33661,38 +31847,29 @@ #endif } /** Close the connection to a child process previously created using - fsl_popen2(). All 3 arguments are assumed to values returned via - fsl_popen2()'s output parameters: the input file descriptor, - output FILE handle, and child process PID. - - If childPid is not zero, that process is killed with SIGINT before - the I/O channels are closed. - - On Windows platforms, killing of the child process is not - implemented. (Patches are welcomed.) + fsl_popen2(). Kill off the child process, then close the pipes. */ void fsl_pclose2(int fdIn, FILE *pOut, int childPid){ -#if FSL_PLATFORM_IS_WINDOWS +#ifdef _WIN32 /* Not implemented, yet */ close(fdIn); fclose(pOut); #else - if(childPid>0) kill(childPid, SIGINT); close(fdIn); fclose(pOut); - while( waitpid(childPid>0 ? (pid_t)childPid : (pid_t)0, - NULL, WNOHANG)>0 ) {} + kill(childPid, SIGINT); + while( waitpid(0, 0, WNOHANG)>0 ) {} #endif } #undef PTR_TO_INT #undef INT_TO_PTR -/* end of file ./src/popen.c */ -/* start of file ./src/pq.c */ +/* end of file popen.c */ +/* start of file pq.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -33764,12 +31941,12 @@ p->list[i] = p->list[i+1]; } --p->used; return e; } -/* end of file ./src/pq.c */ -/* start of file ./src/repo.c */ +/* end of file pq.c */ +/* start of file repo.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -33827,40 +32004,43 @@ " LIMIT 1", rid, rid, FSL_TAGID_BRANCH, zBranch ); } -int fsl_branch_of_rid(fsl_cx * const f, fsl_int_t rid, - bool doFallback, char ** zOut ){ - char *zBr = 0; - fsl_db * const db = fsl_cx_db_repo(f); - fsl_stmt st = fsl_stmt_empty; - int rc; - if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO; - assert(db); - rc = fsl_cx_prepare(f, &st, - "SELECT value FROM tagxref " - "WHERE rid=%" FSL_ID_T_PFMT " AND tagid=%d " - "AND tagtype>0 " - "/*%s()*/", rid, FSL_TAGID_BRANCH,__func__); - if(rc) return rc; - if( fsl_stmt_step(&st)==FSL_RC_STEP_ROW ){ - zBr = fsl_strdup(fsl_stmt_g_text(&st,0,0)); - if(!zBr) rc = FSL_RC_OOM; - } - fsl_stmt_finalize(&st); - if( !rc ){ - if( zBr==0 && doFallback ){ - zBr = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", 0); - if(!zBr){ - zBr = fsl_strdup("trunk"); - if(!zBr) rc = FSL_RC_OOM; - } - } - if(0==rc) *zOut = zBr; - } - return rc; +/** + TODO: figure out if this needs to be in the public API and, if it does, + change its signature to: + + int fsl_branch_of_rid(fsl_cx *f, fsl_int_t rid, char **zOut ) + + So that we can distinguish "not found" from OOM errors. +*/ +static char * fsl_branch_of_rid(fsl_cx * const f, fsl_int_t rid){ + char *zBr = 0; + fsl_db * const db = fsl_cx_db_repo(f); + fsl_stmt * st = 0; + int rc; + assert(db); + rc = fsl_db_prepare_cached(db, &st, + "SELECT value FROM tagxref " + "WHERE rid=? AND tagid=%d " + "AND tagtype>0 " + "/*%s()*/", FSL_TAGID_BRANCH,__func__); + if(rc) return 0; + rc = fsl_stmt_bind_id(st, 1, rid); + if(rc) goto end; + if( fsl_stmt_step(st)==FSL_RC_STEP_ROW ){ + zBr = fsl_strdup(fsl_stmt_g_text(st,0,0)); + if(!zBr) rc = FSL_RC_OOM; + } + end: + fsl_stmt_cached_yield(st); + if( !rc && zBr==0 ){ + zBr = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", 0); + if(!zBr) zBr = fsl_strdup("trunk"); + } + return zBr; } /** morewt ==> most recent event with tag @@ -33937,13 +32117,14 @@ enum fsl_stobr_type eType){ fsl_db * db; fsl_stmt q = fsl_stmt_empty; int rc; fsl_id_t ans = rid; - char * zBr = 0; - rc = fsl_branch_of_rid(f, rid, true, &zBr); - if(rc) return rc; + char *zBr = fsl_branch_of_rid(f, rid); + if(!zBr){ + goto oom; + } db = fsl_cx_db_repo(f); assert(db); rc = fsl_db_prepare(db, &q, "SELECT pid, EXISTS(SELECT 1 FROM tagxref" " WHERE tagid=%d AND tagtype>0" @@ -33971,15 +32152,16 @@ ans = fsl_stmt_g_id(&q, 0); }while( fsl_stmt_g_int32(&q, 1)==1 && ans>0 ); fsl_stmt_finalize(&q); end: if( ans>0 && eType==FSL_STOBR_YOAN ){ - rc = fsl_branch_of_rid(f, ans, true, &zBr); - if(rc) goto oom; - else{ + zBr = fsl_branch_of_rid(f, ans); + if(zBr){ ans = fsl_youngest_ancestor_in_branch(f, rid, zBr); fsl_free(zBr); + }else{ + goto oom; } } return ans; oom: if(!f->error.code){ @@ -34277,72 +32459,81 @@ fsl_cx_err_set(f, FSL_RC_RANGE, "UUID is too long: %s", uuid); return -4; } else { fsl_id_t rid = -5; - fsl_stmt * q = NULL; - int rc = 0; - bool const isGlob = !fsl_is_uuid_len((int)uuidLen); - if(isGlob){ - q = &f->cache.stmt.uuidToRidGlob; - if(!q->stmt){ - rc = fsl_cx_prepare(f, q, - "SELECT rid FROM blob WHERE " - "uuid GLOB ?1 || '*' /*%s()*/",__func__); - } - }else{ - /* Optimization for the common internally-used case.*/ - q = &f->cache.stmt.uuidToRid; - if(!q->stmt){ - rc = fsl_cx_prepare(f, q, - "SELECT rid FROM blob WHERE " - "uuid=?1 /*%s()*/",__func__); - } - } - if(rc) return -10; - rc = fsl_stmt_bind_step(q, "s", uuid); - switch(rc){ - case FSL_RC_STEP_ROW: - rc = 0; - rid = fsl_stmt_g_id(q, 0); - if(isGlob){ - /* Check for an ambiguous result. We don't need this for - the !isGlob case because that one does an exact match - on a unique key. */ - rc = fsl_stmt_step(q); - switch(rc){ - case FSL_RC_STEP_ROW: - rc = 0; - fsl_cx_err_set(f, FSL_RC_AMBIGUOUS, - "UUID prefix is ambiguous: %s", - uuid); - rid = -6; - break; - case FSL_RC_STEP_DONE: - /* Unambiguous UUID */ - rc = 0; - break; - default: - assert(db->error.code); - break; - /* fall through and uplift the db error below... */ - } - } - break; - case 0: /* No entry found */ - rid = 0; - rc = 0; - break; - default: - assert(db->error.code); - rid = -7; - break; - } - if(rc && db->error.code && !f->error.code){ - fsl_cx_uplift_db_error(f, db); - } - fsl_stmt_reset(q); + fsl_stmt q = fsl_stmt_empty; + fsl_stmt * qS = NULL; + int rc; + rc = fsl_is_uuid_len((int)uuidLen) + /* Optimization for the common internally-used case. + + FIXME: there is an *astronomically small* chance of a prefix + collision on a v1-length uuidLen against a v2-length + blob.uuid value, leading to no match found for an existing v2 + uuid here. Like... a *REALLY* small chance. + */ + ? fsl_db_prepare_cached(db, &qS, + "SELECT rid FROM blob WHERE " + "uuid=? /*%s()*/",__func__) + : fsl_db_prepare(db, &q, + "SELECT rid FROM blob WHERE " + "uuid GLOB '%s*'", + uuid); + if(!rc){ + fsl_stmt * st = qS ? qS : &q; + if(qS){ + rc = fsl_stmt_bind_text(qS, 1, uuid, (fsl_int_t)uuidLen, 0); + } + if(!rc){ + rc = fsl_stmt_step(st); + switch(rc){ + case FSL_RC_STEP_ROW: + rc = 0; + rid = fsl_stmt_g_id(st, 0); + if(!qS){ + /* + Check for an ambiguous result. We don't need this for + the (qS==st) case because that one does an exact match + on a unique key. + */ + rc = fsl_stmt_step(st); + switch(rc){ + case FSL_RC_STEP_ROW: + rc = 0; + fsl_cx_err_set(f, FSL_RC_AMBIGUOUS, + "UUID prefix is ambiguous: %s", + uuid); + rid = -6; + break; + case FSL_RC_STEP_DONE: + /* Unambiguous UUID */ + rc = 0; + break; + default: + assert(st->db->error.code); + /* fall through and uplift the db error below... */ + } + } + break; + case FSL_RC_STEP_DONE: + /* No entry found */ + rid = 0; + rc = 0; + break; + default: + assert(st->db->error.code); + rid = -7; + break; + } + } + if(rc && db->error.code && !f->error.code){ + fsl_cx_uplift_db_error(f, db); + } + if(qS) fsl_stmt_cached_yield(qS); + else fsl_stmt_finalize(&q); + } return rid; } } fsl_id_t fsl_repo_filename_fnid( fsl_cx * f, char const * fn ){ @@ -34412,36 +32603,36 @@ } return rc; } int fsl_delta_src_id( fsl_cx * const f, fsl_id_t deltaRid, - fsl_id_t * const rv ){ - if(deltaRid<=0) return FSL_RC_RANGE; - if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO; - int rc = 0; - fsl_stmt * const q = &f->cache.stmt.deltaSrcId; - if(!q->stmt){ - rc = fsl_cx_prepare(f, q, - "SELECT srcid FROM delta " - "WHERE rid=? /*%s()*/",__func__); - if(rc) return rc; - } - rc = fsl_stmt_bind_step(q, "R", deltaRid); - switch(rc){ - case FSL_RC_STEP_ROW: - rc = 0; - *rv = fsl_stmt_g_id(q, 0); - break; - case 0: - rc = 0; - *rv = 0; - default: - fsl_cx_uplift_db_error(f, q->db); - break; - } - fsl_stmt_reset(q); - return rc; + fsl_id_t * rv ){ + fsl_db * const dbR = fsl_cx_db_repo(f); + if(!rv) return FSL_RC_MISUSE; + else if(deltaRid<=0) return FSL_RC_RANGE; + else if(!dbR) return FSL_RC_NOT_A_REPO; + else { + int rc; + fsl_stmt * q = NULL; + rc = fsl_db_prepare_cached(dbR, &q, + "SELECT srcid FROM delta " + "WHERE rid=? /*%s()*/",__func__); + if(!rc){ + rc = fsl_stmt_bind_id(q, 1, deltaRid); + if(!rc){ + if(FSL_RC_STEP_ROW==(rc=fsl_stmt_step(q))){ + rc = 0; + *rv = fsl_stmt_g_id(q, 0); + }else if(FSL_RC_STEP_DONE==rc){ + rc = 0; + *rv = 0; + } + } + fsl_stmt_cached_yield(q); + } + return rc; + } } int fsl__repo_verify_before_commit( fsl_cx * const f, fsl_id_t rid ){ @@ -34679,12 +32870,14 @@ fsl_db * db = 0; fsl_cx F = fsl_cx_empty /* used if !f */; int rc = 0; char const * userName = 0; fsl_time_t const unixNow = (fsl_time_t)time(0); - bool fileExists; - bool inTrans = 0; + char fileExists; + char inTrans = 0; + extern int fsl_cx_attach_role(fsl_cx * f, const char *zDbName, fsl_dbrole_e r) + /* Internal routine from fsl_cx.c */; if(!opt || !opt->filename) return FSL_RC_MISUSE; fileExists = 0 == fsl_file_access(opt->filename,0); if(fileExists && !opt->allowOverwrite){ return f ? fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS, @@ -34696,10 +32889,12 @@ if(f){ rc = fsl_ckout_close(f) /* Will fail if a transaction is active! */; switch(rc){ case 0: + case FSL_RC_NOT_FOUND: + rc = 0; break; default: return rc; } }else{ @@ -34712,19 +32907,30 @@ } /* We probably should truncate/unlink the file here before continuing, to ensure a clean slate. */ if(fileExists){ +#if 0 + FILE * file = fsl_fopen(opt->filename, "w"/*truncates it*/); + if(!file){ + rc = fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_IO), + "Cannot open '%s' for writing.", + opt->filename); + goto end2; + }else{ + fsl_fclose(file); + } +#else rc = fsl_file_unlink(opt->filename); if(rc){ rc = fsl_cx_err_set(f, rc, "Cannot unlink existing repo file: %s", opt->filename); goto end2; } +#endif } - rc = fsl__cx_attach_role(f, opt->filename, FSL_DBROLE_REPO, true); - MARKER(("attach role rc=%s\n", fsl_rc_cstr(rc))); + rc = fsl_cx_attach_role(f, opt->filename, FSL_DBROLE_REPO); if(rc){ goto end2; } db = fsl_cx_db(f); if(!f->repo.user){ @@ -34755,30 +32961,32 @@ have to make it so here as well. Not yet sure where this routine is used in fossil (i.e. whether the option is actually exercised). */ rc = fsl_db_exec_multi(db, - "INSERT OR IGNORE INTO %q.config (name,value,mtime) " + "INSERT INTO repo.config (name,value,mtime) " "VALUES ('server-code'," "lower(hex(randomblob(20)))," "%"PRIi64");" - "INSERT OR IGNORE INTO %q.config (name,value,mtime) " + "INSERT INTO repo.config (name,value,mtime) " "VALUES ('project-code'," "lower(hex(randomblob(20)))," "%"PRIi64");", - db->name, (int64_t)unixNow, - db->name, (int64_t)unixNow); + (int64_t)unixNow, + (int64_t)unixNow + ); if(rc) goto end1; } + /* Set some config vars ... */ { fsl_stmt st = fsl_stmt_empty; rc = fsl_db_prepare(db, &st, - "INSERT INTO %q.config (name,value,mtime) " + "INSERT INTO repo.config (name,value,mtime) " "VALUES (?,?,%"PRIi64")", - db->name, (int64_t)unixNow); + (int64_t)unixNow); if(!rc){ fsl_stmt_bind_int64(&st, 3, unixNow); #define DBSET_STR(KEY,VAL) \ fsl_stmt_bind_text(&st, 1, KEY, -1, 0); \ fsl_stmt_bind_text(&st, 2, VAL, -1, 0); \ @@ -34813,11 +33021,11 @@ if(inTrans){ if(!rc) rc = fsl_db_transaction_end(db, 0); else fsl_db_transaction_end(db, 1); inTrans = 0; } - fsl_close_scm_dbs(f); + fsl_cx_close_dbs(f); db = 0; if(rc) goto end2; /** In order for injection of the first commit to go through @@ -34870,20 +33078,19 @@ inTrans2 = 1; /* Copy all settings from the supplied template repository. */ rc = fsl_db_exec(db, - "INSERT OR REPLACE INTO %q.config" + "INSERT OR REPLACE INTO repo.config" " SELECT name,value,mtime FROM settingSrc.config" " WHERE (name IN %s OR name IN %s)" " AND name NOT GLOB 'project-*';", - db->name, inopConfig, inopDb); + inopConfig, inopDb); if(rc) goto detach; rc = fsl_db_exec(db, - "REPLACE INTO %q.reportfmt " - "SELECT * FROM settingSrc.reportfmt;", - db->name); + "REPLACE INTO repo.reportfmt " + "SELECT * FROM settingSrc.reportfmt;"); if(rc) goto detach; /* Copy the user permissions, contact information, last modified time, and photo for all the "system" users from the supplied @@ -34891,21 +33098,21 @@ columns are not copied because they contain security information or other data specific to the other repository. The list of columns copied by this SQL statement may need to be revised in the future. */ - rc = fsl_db_exec(db, "UPDATE %q.user SET" + rc = fsl_db_exec(db, "UPDATE repo.user SET" " cap = (SELECT u2.cap FROM settingSrc.user u2" " WHERE u2.login = user.login)," " info = (SELECT u2.info FROM settingSrc.user u2" " WHERE u2.login = user.login)," " mtime = (SELECT u2.mtime FROM settingSrc.user u2" " WHERE u2.login = user.login)," " photo = (SELECT u2.photo FROM settingSrc.user u2" " WHERE u2.login = user.login)" - " WHERE user.login IN ('anonymous','nobody','developer','reader');", - db->name); + " WHERE user.login IN ('anonymous','nobody','developer','reader');" + ); detach: fsl_free(inopConfig); fsl_free(inopDb); if(inTrans2){ @@ -34915,11 +33122,21 @@ fsl_db_detach(db, "settingSrc"); if(rc) goto end2; } if(opt->commitMessage && *opt->commitMessage){ - /* Set up initial commit. */ + /* + Set up initial commit. Because of the historically empty P-card + on the first commit, we can't create that one using the fsl_deck + API unless we elide the P-card (not as fossil does) and insert + an empty R-card (as fossil does). We need one of P- or R-card to + unambiguously distinguish this MANIFEST from a CONTROL artifact. + + Reminder to self: fsl_deck has been adjusted to deal with the + initial-checkin(-like) case in the mean time. But this code + works, so no need to go changing it... + */ fsl_deck d = fsl_deck_empty; fsl_cx_err_reset(f); fsl_deck_init(f, &d, FSL_SATYPE_CHECKIN); rc = fsl_deck_C_set(&d, opt->commitMessage, -1); if(!rc) rc = fsl_deck_D_set(&d, fsl_db_julian_now(db)); @@ -34946,12 +33163,11 @@ if(rc) fsl_file_unlink(opt->filename); } return rc; } -static int fsl_repo_dir_names_rid( fsl_cx * const f, fsl_id_t rid, - fsl_list * const tgt, +static int fsl_repo_dir_names_rid( fsl_cx * f, fsl_id_t rid, fsl_list * tgt, bool addSlash){ fsl_db * dbR = fsl_needs_repo(f); fsl_deck D = fsl_deck_empty; fsl_deck * d = &D; int rc = 0; @@ -34974,18 +33190,19 @@ "tmp_filelist_for_rid_%d", (int)rid); if(rc) goto end; rc = fsl_deck_F_rewind(d); while( !rc && !(rc=fsl_deck_F_next(d, &fc)) && fc ){ + //if(!fc->name) continue; assert(fc->name && *fc->name); if(!st.stmt){ rc = fsl_db_exec(dbR, "CREATE TEMP TABLE IF NOT EXISTS " - "\"%b\"(n TEXT UNIQUE ON CONFLICT IGNORE)", + "%b(n TEXT UNIQUE ON CONFLICT IGNORE)", &tname); if(!rc){ rc = fsl_db_prepare(dbR, &st, - "INSERT INTO \"%b\"(n) " + "INSERT INTO %b(n) " "VALUES(fsl_dirpart(?,%d))", &tname, addSlash ? 1 : 0); } if(rc) goto end; assert(st.stmt); @@ -35003,11 +33220,11 @@ } if(!rc && (count>0)){ fsl_stmt_finalize(&st); rc = fsl_db_prepare(dbR, &st, - "SELECT n FROM \"%b\" WHERE n " + "SELECT n FROM %b WHERE n " "IS NOT NULL ORDER BY n %s", &tname, fsl_cx_filename_collation(f)); while( !rc && (FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&st))) ){ fsl_size_t nLen = 0; @@ -35036,21 +33253,21 @@ fsl_cx_uplift_db_error(f, dbR); } fsl_stmt_finalize(&st); fsl_deck_clean(d); if(tname.used){ - fsl_db_exec(dbR, "DROP TABLE IF EXISTS \"%b\"", &tname); + fsl_db_exec(dbR, "DROP TABLE IF EXISTS %b", &tname); } fsl_buffer_clear(&tname); return rc; } -int fsl_repo_dir_names( fsl_cx * const f, fsl_id_t rid, fsl_list * const tgt, +int fsl_repo_dir_names( fsl_cx * f, fsl_id_t rid, fsl_list * tgt, bool addSlash ){ - fsl_db * const db = fsl_needs_repo(f); - if(!db) return FSL_RC_NOT_A_REPO; - else if(!tgt) return FSL_RC_MISUSE; + fsl_db * db = (f && tgt) ? fsl_needs_repo(f) : NULL; + if(!f || !tgt) return FSL_RC_MISUSE; + else if(!db) return FSL_RC_NOT_A_REPO; else { int rc; if(rid>=0){ if(!rid){ /* Dir list for current checkout version */ @@ -35100,11 +33317,11 @@ if(!f || !f->dbMain) return 0; else{ int const roleId = f->ckout.db.dbh ? FSL_DBROLE_MAIN : FSL_DBROLE_REPO /* If CKOUT is attached, it is the main DB and REPO is ATTACHed. */ ; - char const * zRole = fsl_db_role_name(roleId); + char const * zRole = fsl_db_role_label(roleId); assert(f->dbMain); return sqlite3_db_readonly(f->dbMain->dbh, zRole) ? 1 : 0; } } @@ -35133,16 +33350,13 @@ int const dbRole = (f->dbMain==&f->config.db) ? FSL_DBROLE_MAIN : FSL_DBROLE_CONFIG; rc = fsl_db_exec(dbConf, "INSERT OR IGNORE INTO %s.global_config(name,value) " "VALUES('repo:%q',1)", - fsl_db_role_name(dbRole), + fsl_db_role_label(dbRole), fsl_buffer_cstr(full)); - if(rc){ - fsl_cx_uplift_db_error(f, dbConf); - goto end; - } + if(rc) goto end; } dbC = fsl_cx_db_ckout(f); if(dbC && (zCDir=f->ckout.dir)){ /* If we have a checkout, update its repo's list of checkouts... */ @@ -35149,11 +33363,11 @@ /* Assumption: if we have an opened checkout, dbR is ATTACHed with the role REPO. */ int ro; assert(dbR); ro = sqlite3_db_readonly(dbR->dbh, - fsl_db_role_name(FSL_DBROLE_REPO)); + fsl_db_role_label(FSL_DBROLE_REPO)); assert(ro>=0); if(!ro){ fsl_buffer localRoot = fsl_buffer_empty; rc = fsl_file_canonical_name(zCDir, &localRoot, 1); if(0==rc){ @@ -35164,20 +33378,20 @@ int const dbRole = (f->dbMain==&f->config.db) ? FSL_DBROLE_MAIN : FSL_DBROLE_CONFIG; rc = fsl_db_exec(dbConf, "REPLACE INTO INTO %s.global_config(name,value) " "VALUES('ckout:%q',1)", - fsl_db_role_name(dbRole), + fsl_db_role_label(dbRole), fsl_buffer_cstr(&localRoot)); } if(0==rc){ /* We know that repo is ATTACHed to ckout here. */ assert(dbR == dbC); rc = fsl_db_exec(dbR, "REPLACE INTO %s.config(name, value, mtime) " "VALUES('ckout:%q', 1, now())", - fsl_db_role_name(FSL_DBROLE_REPO), + fsl_db_role_label(FSL_DBROLE_REPO), fsl_buffer_cstr(&localRoot)); } } fsl_buffer_clear(&localRoot); } @@ -35221,20 +33435,20 @@ } return rv; } } -int fsl_repo_extract( fsl_cx * const f, fsl_repo_extract_opt const * const opt_ ){ +int fsl_repo_extract( fsl_cx * f, fsl_repo_extract_opt const * opt_ ){ if(!f || !opt_->callback) return FSL_RC_MISUSE; else if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO; else if(opt_->checkinRid<=0){ return fsl_cx_err_set(f, FSL_RC_RANGE, "RID must be positive."); }else{ int rc; fsl_deck mf = fsl_deck_empty; - fsl_buffer * const content = opt_->extractContent - ? &f->cache.fileContent + fsl_buffer * content = opt_->extractContent + ? &f->fileContent : NULL; fsl_id_t fid; fsl_repo_extract_state xst = fsl_repo_extract_state_empty; fsl_card_F const * fc = NULL; fsl_repo_extract_opt const opt = *opt_ @@ -35277,11 +33491,10 @@ "Could not resolve RID for UUID: %s", fc->uuid); }else if(opt.extractContent){ fsl_buffer_reuse(content); rc = fsl_content_get(f, fid, content); - //assert(FSL_RC_RANGE!=rc); } if(!rc){ /** Call the callback. */ xst.fCard = fc; assert(fid>0); @@ -35345,12 +33558,12 @@ return rc; } } -int fsl_repo_blob_lookup( fsl_cx * const f, fsl_buffer const * const src, - fsl_id_t * const ridOut, fsl_uuid_str * hashOut ){ +int fsl_repo_blob_lookup( fsl_cx * f, fsl_buffer const * src, fsl_id_t * ridOut, + fsl_uuid_str * hashOut ){ int rc; fsl_buffer hash_ = fsl_buffer_empty; fsl_buffer * hash; fsl_id_t rid = 0; if(!fsl_cx_db_repo(f)) return FSL_RC_NOT_A_REPO; @@ -35469,11 +33682,11 @@ fsl__cx_scratchpad_yield(f, sql); fsl_stmt_finalize(&q); return rc; } -int fsl_repo_manifest_write(fsl_cx * const f, +int fsl_repo_manifest_write(fsl_cx *f, fsl_id_t manifestRid, fsl_buffer * const pManifest, fsl_buffer * const pHash, fsl_buffer * const pTags) { fsl_db * const db = fsl_needs_repo(f); @@ -35609,11 +33822,11 @@ (1) Change the CHECK constraint on BLOB.UUID so that the length is greater than or equal to 40, not exactly equal to 40. */ zBlobSchema = fsl_db_g_text(frs->db, NULL, "SELECT sql FROM %!Q.sqlite_schema" - " WHERE name='blob'", fsl_db_role_name(FSL_DBROLE_REPO)); + " WHERE name='blob'", fsl_db_role_label(FSL_DBROLE_REPO)); if(!zBlobSchema){ /* ^^^^ reminder: fossil(1) simply ignores this case, silently doing nothing instead. */ rc = fsl_cx_uplift_db_error(frs->f, frs->db); if(!rc){ @@ -35632,11 +33845,11 @@ sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE, 0, &rc2); rc = fsl_cx_exec_multi(frs->f, "PRAGMA writable_schema=ON;" "UPDATE %!Q.sqlite_schema SET sql=%Q WHERE name LIKE 'blob';" "PRAGMA writable_schema=OFF;", - fsl_db_role_name(FSL_DBROLE_REPO), zBlobSchema + fsl_db_role_label(FSL_DBROLE_REPO), zBlobSchema ); sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE, 1, &rc2); break; } } @@ -35644,11 +33857,11 @@ rc = fsl_cx_exec(frs->f, "CREATE VIEW IF NOT EXISTS " " %!Q.artifact(rid,rcvid,size,atype,srcid,hash,content) AS " " SELECT blob.rid,rcvid,size,1,srcid,uuid,content" " FROM blob LEFT JOIN delta ON (blob.rid=delta.rid);", - fsl_db_role_name(FSL_DBROLE_REPO) + fsl_db_role_label(FSL_DBROLE_REPO) ); end: fsl_free(zBlobSchema); return rc; @@ -35813,17 +34026,24 @@ (sz = fsl_stmt_g_int64(&frs->qChild, 1))>=0 ){ fsl_buffer next = fsl_buffer_empty; fsl_buffer delta = fsl_buffer_empty; void const * blob = 0; fsl_size_t deltaBlobSize = 0; - rc = INTCHECK fsl_stmt_get_blob(&frs->qChild, 0, &blob, &deltaBlobSize); + rc = INTCHECK fsl_stmt_get_blob(&frs->qChild, 0, &blob, &deltaBlobSize) + /* Library-level TODO: a heuristic/convention in fsl_buffer + APIs which says that if buf.mem is not NULL and buf.capacity + is 0 then the memory is owned elsewhere and must be copied + if/when it would be modified by the buffer API. That would allow + us to emulate some of the buffer-copy optimization which fossil does, + e.g. in this very spot. + */; if(rc) goto outro; - fsl_buffer_external(&delta, blob, (fsl_int_t)deltaBlobSize); + rc = fsl_buffer_append(&delta, blob, (fsl_int_t)deltaBlobSize); + fsl_stmt_reset(&frs->qChild); rc = INTCHECK fsl_buffer_uncompress(&delta, &delta); if(rc) goto outro; rc = INTCHECK fsl_buffer_delta_apply(content, &delta, &next); - fsl_stmt_reset(&frs->qChild); fsl_buffer_clear(&delta); if(rc){ if(FSL_RC_OOM!=rc){ rc = fsl_cx_err_set(frs->f, rc, "Error applying delta #%" FSL_ID_T_PFMT @@ -35914,55 +34134,60 @@ fsl__cx_scratchpad_yield(frs->f, b); return rc; } + +#define FSL__REBUILD_SKIP_TICKETS 1 /* remove this once crosslinking does + something useful with tickets. */ static int fsl__rebuild(fsl_cx * const f, fsl_rebuild_opt const * const opt){ fsl_stmt s = fsl_stmt_empty; fsl_stmt q = fsl_stmt_empty; fsl_db * const db = fsl_cx_db_repo(f); int rc; FslRebuildState frs = FslRebuildState_empty; - fsl_buffer * const sql = fsl__cx_scratchpad(f); + fsl_buffer sql = fsl_buffer_empty; assert(db); frs.f = frs.step.f = f; frs.db = db; frs.opt = frs.step.opt = opt; rc = fsl__rebuild_update_schema(&frs); - if(!rc) rc = fsl_buffer_reserve(sql, 1024 * 4); + if(!rc) rc = fsl_buffer_reserve(&sql, 1024 * 4); if(rc) goto end; fsl__cx_clear_mf_seen(f, false); - /* DROP all tables which are not part of our One True Vision of the - repo db... */ rc = fsl_cx_prepare(f, &q, "SELECT name FROM %!Q.sqlite_schema /*scan*/" " WHERE type='table'" " AND name NOT IN ('admin_log', 'blob','delta','rcvfrom','user','alias'," "'config','shun','private','reportfmt'," "'concealed','accesslog','modreq'," "'purgeevent','purgeitem','unversioned'," +#if FSL__REBUILD_SKIP_TICKETS "'ticket','ticketchng'," +#endif "'subscriber','pending_alert','chat'" ")" " AND name NOT GLOB 'sqlite_*'" " AND name NOT GLOB 'fx_*'", - fsl_db_role_name(FSL_DBROLE_REPO) + fsl_db_role_label(FSL_DBROLE_REPO) ); while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){ - rc = fsl_buffer_appendf(sql, "DROP TABLE IF EXISTS %!Q;\n", + rc = fsl_buffer_appendf(&sql, "DROP TABLE IF EXISTS %!Q;\n", fsl_stmt_g_text(&q, 0, NULL)); } fsl_stmt_finalize(&q); - if(0==rc && fsl_buffer_size(sql)){ - rc = fsl_cx_exec_multi(f, "%b", sql); + if(0==rc && fsl_buffer_size(&sql)){ + rc = fsl_cx_exec_multi(f, "%b", &sql); } if(rc) goto end; rc = fsl_cx_exec_multi(f, "%s", fsl_schema_repo2()); +#if !FSL__REBUILD_SKIP_TICKETS if(0==rc) rc = fsl__cx_ticket_create_table(f); +#endif if(0==rc) rc = fsl__shunned_remove(f); if(0==rc){ rc = fsl_cx_exec_multi(f, "INSERT INTO unclustered" " SELECT rid FROM blob EXCEPT SELECT rid FROM private;" @@ -35988,11 +34213,10 @@ //totalSize += incrSize*2; rc = fsl_cx_prepare(f, &s, "SELECT rid, size FROM blob /*scan*/" " WHERE NOT EXISTS(SELECT 1 FROM shun WHERE uuid=blob.uuid)" " AND NOT EXISTS(SELECT 1 FROM delta WHERE rid=blob.rid)" - "%s", opt->randomize ? " ORDER BY RANDOM()" : "" ); if(rc) goto end; rc = fsl__crosslink_begin(f) /* Maintenace reminder: if this call succeeds, BE SURE that we do not skip past the fsl__crosslink_end() call via @@ -36015,11 +34239,10 @@ fsl_stmt_finalize(&s); if(rc) goto crosslink_end; rc = fsl_cx_prepare(f, &s, "SELECT rid, size FROM blob" " WHERE NOT EXISTS(SELECT 1 FROM shun WHERE uuid=blob.uuid)" - "%s", opt->randomize ? " ORDER BY RANDOM()" : "" ); while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&s) ){ fsl_id_t const rid = fsl_stmt_g_id(&s, 0); int64_t const size = fsl_stmt_g_int64(&s, 1); if( size>=0 ){ @@ -36028,33 +34251,10 @@ rc = fsl_content_get(f, rid, &content); if(0==rc){ rc = fsl__rebuild_step(&frs, rid, size, &content); assert(!content.mem); } - /* - 2021-12-17: hmmm... while debugging the problem reported here: - - https://fossil-scm.org/forum/forumpost/f4cc31863179f843 - - It was discovered that fossil will simply skip any content - it cannot read in this step, even if it's skipped over - because of a broken blob-to-delta mapping (whereas fossil's - test-integrity command will catch that case). If such a case - happens to us, fsl_content_get() fails with FSL_RC_PHANTOM. - That seems to me to be the right thing to do, as such a case - is indicative of db corruption. However, if we skip over - these then we cannot rebuild a repo which has such (invalid) - state. - - Feature or bug? - - For now let's keep it strict and fail if we can't fetch the - content. We can reevaluate that decision later if needed. We - can add a fsl_rebuild_opt::ignorePhantomFailure (better name - pending!) flag which tells us how the user would prefer to - deal with this. - */ fsl_buffer_clear(&content); } }else{ rc = fsl_cx_exec_multi(f, "INSERT OR IGNORE INTO phantom " "VALUES(%" FSL_ID_T_PFMT ")", rid); @@ -36069,26 +34269,26 @@ crosslink_end: rc = fsl__crosslink_end(f, rc); if(rc) goto end; rc = fsl__rebuild_tag_trunk(&frs); if(rc) goto end; - //if( opt->createClusters ) rc = fsl__create_cluster(f); + //if( opt->clustering ) rc = fsl__create_cluster(f); rc = fsl_cx_exec_multi(f, "REPLACE INTO config(name,value,mtime) VALUES('content-schema',%Q,now());" "REPLACE INTO config(name,value,mtime) VALUES('aux-schema',%Q,now());" "REPLACE INTO config(name,value,mtime) VALUES('rebuilt',%Q,now());", FSL_CONTENT_SCHEMA, FSL_AUX_SCHEMA, "libfossil " FSL_LIB_VERSION_HASH " " FSL_LIB_VERSION_TIMESTAMP ); end: - fsl__cx_scratchpad_yield(f, sql); if(0==rc && frs.opt->callback){ frs.step.stepNumber = 0; frs.step.rid = 0; frs.step.blobSize = 0; rc = frs.opt->callback(&frs.step); } + fsl_buffer_clear(&sql); fsl_stmt_finalize(&s); fsl_stmt_finalize(&frs.qDeltas); fsl_stmt_finalize(&frs.qSize); fsl_stmt_finalize(&frs.qChild); fsl_id_bag_clear(&frs.idsDone); @@ -36107,114 +34307,14 @@ } fsl_cx_interrupt(f, 0, NULL); return rc; } - -int fsl_cidiff(fsl_cx * const f, fsl_cidiff_opt const * const opt){ - fsl_deck d1 = fsl_deck_empty; - fsl_deck d2 = fsl_deck_empty; - fsl_card_F const * fc1; - fsl_card_F const * fc2; - int rc; - fsl_cidiff_state cst = fsl_cidiff_state_empty; - if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO; - rc = fsl_deck_load_rid(f, &d1, opt->v1, FSL_SATYPE_CHECKIN); - if(rc) goto end; - rc = fsl_deck_load_rid(f, &d2, opt->v2, FSL_SATYPE_CHECKIN); - if(rc) goto end; - rc = fsl_deck_F_rewind(&d1); - if(0==rc) rc = fsl_deck_F_rewind(&d2); - if(rc) goto end; - fsl_deck_F_next(&d1, &fc1); - fsl_deck_F_next(&d2, &fc2); - cst.f = f; - cst.opt = opt; - cst.d1 = &d1; - cst.d2 = &d2; - rc = opt->callback(&cst); - cst.stepType = FSL_RC_STEP_ROW; - while(0==rc && (fc1 || fc2)){ - int nameCmp; - cst.changes = FSL_CIDIFF_NONE; - if(!fc1) nameCmp = 1; - else if(!fc2) nameCmp = -1; - else{ - nameCmp = fsl_strcmp(fc1->name, fc2->name); - if(fc2->priorName){ - if(0==nameCmp){ - cst.changes |= FSL_CIDIFF_FILE_RENAMED; - }else if(0==fsl_strcmp(fc1->name, fc2->priorName)){ - /** - Treat these as being the same file for this purpose. - - We ostensibly know that fc1 was renamed to fc2->name here - BUT there's a corner case we can't sensibly determine - here: file A renamed to B and file C renamed to A. If - both of those F-cards just happen to align at this point - in this loop, we're mis-informing the user. Reliably - catching that type of complex situation requires - significant hoop-jumping, as can be witness in - fsl_ckout_merge() (which still misses some convoluted - cases). - */ - nameCmp = 0; - cst.changes |= FSL_CIDIFF_FILE_RENAMED; - } - } - if(fc1->perm!=fc2->perm){ - cst.changes |= FSL_CIDIFF_FILE_PERMS; - } - } - if(nameCmp<0){ - nameCmp = -1/*see below*/; - assert(fc1); - cst.changes |= FSL_CIDIFF_FILE_REMOVED; - cst.fc1 = fc1; cst.fc2 = NULL; - }else if(nameCmp>0){ - nameCmp = 1/*see below*/; - cst.changes |= FSL_CIDIFF_FILE_ADDED; - cst.fc1 = NULL; cst.fc2 = fc2; - }else{ - cst.fc1 = fc1; cst.fc2 = fc2; - } - if(fc1 && fc2 && 0!=fsl_strcmp(fc1->uuid, fc2->uuid)){ - cst.changes |= FSL_CIDIFF_FILE_MODIFIED; - } - rc = opt->callback(&cst); - switch(rc ? 2 : nameCmp){ - case 2: break; - case -1: rc = fsl_deck_F_next(&d1, &fc1); break; - case 1: rc = fsl_deck_F_next(&d2, &fc2); break; - case 0: - rc = fsl_deck_F_next(&d1, &fc1); - if(0==rc) rc = fsl_deck_F_next(&d2, &fc2); - break; - default: - fsl__fatal(FSL_RC_MISUSE,"Internal API misuse."); - } - }/*while(f-cards)*/ - if(0==rc){ - cst.fc1 = cst.fc2 = NULL; - cst.stepType = FSL_RC_STEP_DONE; - rc = opt->callback(&cst); - } - end: - fsl_deck_finalize(&d1); - fsl_deck_finalize(&d2); - return rc; -} - - -bool fsl_repo_forbids_delta_manifests(fsl_cx * const f){ - return fsl_config_get_bool(f, FSL_CONFDB_REPO, false, - "forbid-delta-manifests"); -} - +#undef FSL__REBUILD_SKIP_TICKETS #undef MARKER -/* end of file ./src/repo.c */ -/* start of file ./src/schema.c */ +/* end of file repo.c */ +/* start of file schema.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 Stephan Beal (https://wanderinghorse.net). @@ -36266,12 +34366,12 @@ char const * fsl_schema_forum(){ extern char const * fsl_schema_forum_cstr; return fsl_schema_forum_cstr; } -/* end of file ./src/schema.c */ -/* start of file ./src/search.c */ +/* end of file schema.c */ +/* start of file search.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -36367,12 +34467,12 @@ return rc; #endif } #undef MARKER -/* end of file ./src/search.c */ -/* start of file ./src/sha1.c */ +/* end of file search.c */ +/* start of file sha1.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ #include #include /* strlen() */ #include /* NULL on linux */ @@ -38271,12 +36371,12 @@ (len<0) ? fsl_strlen(zIn) : (fsl_size_t)len); fsl_sha1_final_hex(&ctx, zHex); return zHex; } } -/* end of file ./src/sha1.c */ -/* start of file ./src/sha3.c */ +/* end of file sha1.c */ +/* start of file sha3.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* ** Copyright (c) 2017 D. Richard Hipp ** @@ -38906,41 +37006,15 @@ return rc; #endif } } -#undef A00 -#undef A01 -#undef A02 -#undef A03 -#undef A04 -#undef A10 -#undef A11 -#undef A12 -#undef A13 -#undef A14 -#undef A20 -#undef A21 -#undef A22 -#undef A23 -#undef A24 -#undef A30 -#undef A31 -#undef A32 -#undef A33 -#undef A34 -#undef A40 -#undef A41 -#undef A42 -#undef A43 -#undef A44 -#undef ROL64 #undef SHA3_BYTEORDER #undef MARKER -/* end of file ./src/sha3.c */ -/* start of file ./src/strftime.c */ +/* end of file sha3.c */ +/* start of file strftime.c */ /******************************************************************************* * The Elm Mail System - $Revision: 1.3 $ $State: Exp $ * * Public-domain relatively quick-and-dirty implemenation of * ANSI library routine for System V Unix systems. @@ -39547,12 +37621,12 @@ fsl_time_t epochTime, bool convertToLocal){ time_t orig = (time_t)epochTime; struct tm * tim = convertToLocal ? localtime(&orig) : gmtime(&orig); return fsl_strftime( dest, destLen, format, tim ); } -/* end of file ./src/strftime.c */ -/* start of file ./src/tag.c */ +/* end of file strftime.c */ +/* start of file tag.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -40186,12 +38260,12 @@ return rc; } #undef MARKER -/* end of file ./src/tag.c */ -/* start of file ./src/ticket.c */ +/* end of file tag.c */ +/* start of file ticket.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -40215,19 +38289,19 @@ rc = fsl_cx_exec_multi(f, "DROP TABLE IF EXISTS ticket;" "DROP TABLE IF EXISTS ticketchng;" ); if(!rc){ - fsl_buffer * const buf = &f->cache.fileContent; + fsl_buffer * const buf = &f->fileContent; fsl_buffer_reuse(buf); rc = fsl_cx_schema_ticket(f, buf); if(!rc) rc = fsl_cx_exec_multi(f, "%b", buf); } return rc; } -static int fsl__tkt_field_id(fsl_list const * jli, const char *zFieldName){ +static int fsl_tkt_field_id(fsl_list const * jli, const char *zFieldName){ int i; fsl_card_J const * jc; for(i=0; i<(int)jli->used; ++i){ jc = (fsl_card_J const *)jli->list[i]; if( !fsl_strcmp(zFieldName, jc->field) ) return i; @@ -40234,33 +38308,29 @@ } return -1; } int fsl__cx_ticket_load_fields(fsl_cx * const f, bool forceReload){ - fsl_list * const li = &f->ticket.customFields; + fsl_stmt q = fsl_stmt_empty; + int i, rc = 0; + fsl_list * li = &f->ticket.customFields; + fsl_card_J * jc; + fsl_db * db; if(li->used){ if(!forceReload) return 0; - fsl__card_J_list_free(li, false); + fsl__card_J_list_free(li, 0); /* Fall through and reload ... */ - }else if( !fsl_needs_repo(f) ){ + } + if( !(db = fsl_needs_repo(f)) ){ return FSL_RC_NOT_A_REPO; } - fsl_card_J * jc; - fsl_stmt q = fsl_stmt_empty; - int i; - int rc = fsl_cx_prepare(f, &q, "PRAGMA table_info(ticket)"); + rc = fsl_db_prepare(db, &q, "PRAGMA table_info(ticket)"); if(!rc) while( FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){ char const * zFieldName = fsl_stmt_g_text(&q, 1, NULL); - if(!zFieldName){ - rc = FSL_RC_OOM; - break; - } f->ticket.hasTicket = 1; if( 0==memcmp(zFieldName,"tkt_", 4)){ if( 0==fsl_strcmp(zFieldName,"tkt_ctime")) f->ticket.hasCTime = 1; - /* These are core field names, part of every fossil ticket - table. */ continue; } jc = fsl_card_J_malloc(0, zFieldName, NULL); if(!jc){ rc = FSL_RC_OOM; @@ -40274,25 +38344,19 @@ } } fsl_stmt_finalize(&q); if(rc) goto end; - rc = fsl_cx_prepare(f, &q, "PRAGMA table_info(ticketchng)"); + rc = fsl_db_prepare(db, &q, "PRAGMA table_info(ticketchng)"); if(!rc) while( FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){ char const * zFieldName = fsl_stmt_g_text(&q, 1, NULL); - if(!zFieldName){ - rc = FSL_RC_OOM; - break; - } f->ticket.hasChng = 1; if( 0==memcmp(zFieldName,"tkt_", 4)){ if( 0==fsl_strcmp(zFieldName,"tkt_rid")) f->ticket.hasChngRid = 1; - /* These are core field names, part of every fossil ticketchng - table. */ continue; } - if( (i=fsl__tkt_field_id(li, zFieldName)) >= 0){ + if( (i=fsl_tkt_field_id(li, zFieldName)) >= 0){ jc = (fsl_card_J*)li->list[i]; jc->flags |= FSL_CARD_J_CHNG; continue; } jc = fsl_card_J_malloc(0, zFieldName, NULL); @@ -40312,830 +38376,12 @@ if(!rc){ fsl_list_sort(li, fsl__qsort_cmp_J_cards); } return rc; } - -static int fsl__ticket_insert(fsl_deck * const d, fsl_id_t tktId, - fsl_id_t * const tgtId){ - /* Derived from fossil(1) tkt.c:ticket_insert() */; - fsl_cx * const f = d->f; - fsl_id_t const rid = d->rid; - int rc = 0; - fsl_buffer * const sql1 = fsl__cx_scratchpad(f); - fsl_buffer * const sql2 = fsl__cx_scratchpad(f); - fsl_buffer * const sql3 = fsl__cx_scratchpad(f); - fsl_db * const db = fsl_cx_db_repo(f); - fsl_list const * const cf = &f->ticket.customFields; - fsl_size_t i; - //char const * zMimetype = NULL; - fsl_stmt q = fsl_stmt_empty; - char aUsed[cf->used]; - assert(rid>0 && f!=NULL && db); - if(0==tktId){ - rc = fsl_cx_exec_multi(f, "INSERT INTO ticket(tkt_uuid, tkt_mtime) " - "VALUES(%Q, 0)", d->K); - if(rc) goto end; - tktId = fsl_db_last_insert_id(db); - } - rc = fsl_buffer_append(sql1, "UPDATE OR REPLACE ticket SET tkt_mtime=?1", -1); - if(0==rc && f->ticket.hasCTime){ - rc = fsl_buffer_append(sql1, ", tkt_ctime=coalesce(tkt_ctime,?1)", -1); - } - if(rc) goto end; - memset(aUsed, 0, cf->used); - for(i = 0; 0==rc && i < d->J.used; ++i){ - fsl_card_J const * const dJC = (fsl_card_J*)d->J.list[i]; - int const j = fsl__tkt_field_id(cf, dJC->field); - if(j<0){ - /* Ticket has a field which this repo does not have. Skip it. */ - continue; - } - aUsed[j] = FSL_CARD_J_TICKET; - fsl_card_J const * const rJC = (fsl_card_J*)cf->list[j]; - if(rJC->flags & FSL_CARD_J_TICKET){ - if(dJC->append){ - rc = fsl_buffer_appendf(sql1, ", %!Q=coalesce(%!Q,'') || %Q", - dJC->field, dJC->field, dJC->value); - }else{ - rc = fsl_buffer_appendf(sql1, ", %!Q=%Q", - dJC->field, dJC->value); - } - if(rc) break; - } - if(rJC->flags & FSL_CARD_J_CHNG){ - rc = fsl_buffer_appendf(sql2, ",%!Q", dJC->field); - if(0==rc) rc = fsl_buffer_appendf(sql3, ",%Q", dJC->value); - if(rc) break; - } -#if 0 - if(0==fsl_strcmp(dJC->field, "mimetype")){ - zMimetype = dJC->value; - } -#endif - } - if(rc) goto end; - /* MISSING: a block from fossil(1) tkt.c which extracts backlinks: - - if( rid>0 ){ - for(i=0; inField; i++){ - const char *zName = p->aField[i].zName; - const char *zBaseName = zName[0]=='+' ? zName+1 : zName; - j = fieldId(zBaseName); - if( j<0 ) continue; - backlink_extract(p->aField[i].zValue, zMimetype, rid, BKLNK_TICKET, - p->rDate, i==0); - } - } - - That's not critical for core ticket functionality. - */ - rc = fsl_buffer_appendf(sql1, " WHERE tkt_id=%" FSL_ID_T_PFMT, tktId); - if(rc) goto end; - rc = fsl_cx_prepare(f, &q, "%b", sql1); - if(rc) goto end; - rc = fsl_stmt_bind_step(&q, "f", d->D); - fsl_stmt_finalize(&q); - if(rc) goto end; - fsl_buffer_reuse(sql1); - if(f->ticket.hasChngRid || sql2->used){ - bool fromTkt = false; - if(f->ticket.hasChngRid){ - rc = fsl_buffer_append(sql2, ",tkt_rid", -1); - if(0==rc) rc = fsl_buffer_appendf(sql3, ",%" FSL_ID_T_PFMT, d->rid); - if(rc) goto end; - } - for(i = 0; 0==rc && i < cf->used; ++i){ - fsl_card_J const * const rJC = (fsl_card_J*)cf->list[i]; - if(0==aUsed[i] && (rJC->flags & FSL_CARD_J_BOTH)==FSL_CARD_J_BOTH){ - fromTkt = true; - rc = fsl_buffer_appendf(sql2, ",%!Q", rJC->field); - if(0==rc) rc = fsl_buffer_appendf(sql3, ",%!Q", rJC->field); - } - } - if(rc) goto end; - if(fromTkt){ - rc = fsl_cx_prepare(f, &q, "INSERT INTO ticketchng(tkt_id,tkt_mtime%b)" - "SELECT %"FSL_ID_T_PFMT",?1%b " - "FROM ticket WHERE tkt_id=%"FSL_ID_T_PFMT, - sql2, tktId, sql3, tktId); - }else{ - rc = fsl_cx_prepare(f, &q, "INSERT INTO ticketchng(tkt_id,tkt_mtime%b)" - "VALUES(%"FSL_ID_T_PFMT",?1%b)", - sql2, tktId, sql3); - } - if(0==rc) rc = fsl_stmt_bind_step(&q, "f", d->D); - } - end: - fsl_stmt_finalize(&q); - fsl__cx_scratchpad_yield(f, sql1); - fsl__cx_scratchpad_yield(f, sql2); - fsl__cx_scratchpad_yield(f, sql3); - *tgtId = tktId; - return rc; -} - -static int fsl__ticket_timeline_entry(fsl_deck * const d, bool isNew, fsl_id_t tagId){ - /* Derived from fossil(1) manifest.c:mainfest_ticket_event() */; - int rc; - fsl_buffer * const comment = fsl__cx_scratchpad(d->f); - fsl_buffer * const brief = fsl__cx_scratchpad(d->f); - char * zTitle = 0; - char * zNewStatus = 0; - fsl_db * const db = fsl_cx_db_repo(d->f); - fsl_cx * const f = d->f; - if(!f->ticket.titleColumn){ - assert(!f->ticket.statusColumn); - rc = fsl_db_get_text(db, &f->ticket.titleColumn, NULL, - "SELECT coalesce(" - "(SELECT value FROM config WHERE name='ticket-title-expr')," - "'title')"); - if(0==rc){ - rc = fsl_db_get_text(db, &f->ticket.statusColumn, NULL, - "SELECT coalesce(" - "(SELECT value FROM config WHERE name='ticket-status-column')," - "'status')"); - } - if(rc) return fsl_cx_uplift_db_error( f, db ); - } - rc = fsl_db_get_text(db, &zTitle, NULL, - "SELECT coalesce(%!Q,'unknown') " - "FROM ticket WHERE tkt_uuid=%Q", - f->ticket.titleColumn, d->K); - if(rc){ - fsl_cx_uplift_db_error(d->f, db); - goto end; - } - if(isNew){ - rc = fsl_buffer_appendf(comment, "New ticket [%!S|%S] %h.", - d->K, d->K, zTitle); - if(0==rc){ - rc = fsl_buffer_appendf(brief, "New ticket [%!S|%S].", - d->K, d->K); - } - if(rc) goto end; - }else{ - // Update an existing ticket... - char * zNewStatus = 0; - for(fsl_size_t i = 0; i < d->J.used; ++i){ - fsl_card_J const * const jc = (fsl_card_J*)d->J.list[i]; - if(0==fsl_strcmp(jc->field, f->ticket.statusColumn)){ - zNewStatus = jc->value; - break; - } - } - if(zNewStatus){ - rc = fsl_buffer_appendf(comment, "%h ticket [%!S|%S]: %h", - zNewStatus, d->K, d->K, zTitle); - if(!rc && d->J.used>1){ - rc = fsl_buffer_appendf(comment, " plus %d other change%s", - (int)d->J.used-1, d->J.used==2 ? "" : "s"); - } - if(0==rc) rc = fsl_buffer_appendf(brief, "%h ticket [%!S|%S].", - zNewStatus, d->K, d->K); - if(rc) goto end; - }else{ - rc = fsl_db_get_text(db, &zNewStatus, NULL, - "SELECT coalesce(%!Q,'unknown') " - "FROM ticket WHERE tkt_uuid=%Q", - f->ticket.statusColumn, d->K); - if(rc){ - rc = fsl_cx_uplift_db_error2(f, db, rc); - goto end; - } - rc = fsl_buffer_appendf(comment, "Ticket [%!S|%S] %h " - "status still %h with %d other change%s", - d->K, d->K, zTitle, zNewStatus, (int)d->J.used, - 1==d->J.used ? "" : "s"); - fsl_free(zNewStatus); - if(rc) goto end; - rc = fsl_buffer_appendf(brief, "Ticket [%!S|%S]: %d change%s", - d->K, d->K, (int)d->J.used, - 1==d->J.used ? "" : "s"); - if(rc) goto end; - } - } - assert(0==rc); - // MISSING: manifest_create_event_triggers() - rc = fsl_cx_exec(d->f, - "REPLACE INTO event" - "(type, tagid, mtime, objid, user, comment, brief) " - "VALUES('t', %"FSL_ID_T_PFMT", %"FSL_JULIAN_T_PFMT", " - "%"FSL_ID_T_PFMT",%Q,%B,%B)", - tagId, d->D, d->rid, d->U, comment, brief); - end: - fsl_free(zTitle); - fsl_free(zNewStatus); - fsl__cx_scratchpad_yield(d->f, comment); - fsl__cx_scratchpad_yield(d->f, brief); - return rc; -} - -int fsl__ticket_rebuild(fsl_cx * const f, char const * zTktKCard){ - int rc; - fsl_id_t tktId; - fsl_id_t tagId; - fsl_db * const db = fsl_needs_repo(f); - fsl_stmt q = fsl_stmt_empty; - if(!db) return FSL_RC_NOT_A_REPO; - assert(!f->cache.isCrosslinking); - rc = fsl__cx_ticket_load_fields(f, false); - if(rc) goto end; - else if(!f->ticket.hasTicket) return 0; - char * const zTag = fsl_mprintf("tkt-%s", zTktKCard); - if(!zTag){ - rc = FSL_RC_OOM; - goto end; - } - tagId = fsl_tag_id(f, zTag, true); - fsl_free(zTag); - if(tagId<0){ - rc = f->error.code; - assert(0!=rc); - goto end; - } - tktId = fsl_db_g_id(db, 0, "SELECT tkt_id FROM ticket " - "WHERE tkt_uuid=%Q", zTktKCard); - if(tktId>0){ - if(f->ticket.hasChng){ - rc = fsl_cx_exec(f, "DELETE FROM ticketchng " - "WHERE tkt_id=%" FSL_ID_T_PFMT, - tktId); - } - if(!rc) rc = fsl_cx_exec(f, "DELETE FROM ticket " - "WHERE tkt_id=%" FSL_ID_T_PFMT, - tktId); - if(rc) goto end; - } - tktId = 0; - rc = fsl_cx_prepare(f, &q, "SELECT rid FROM tagxref " - "WHERE tagid=%" FSL_ID_T_PFMT - " ORDER BY mtime", tagId); - int counter = 0; - /* Potential TODO (fossil does not do this): - DELETE FROM EVENT WHERE tagid=${tagId} */ - while(0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q)){ - fsl_deck deck = fsl_deck_empty; - fsl_id_t const rid = fsl_stmt_g_id(&q, 0); - rc = fsl_deck_load_rid(f, &deck, rid, FSL_SATYPE_TICKET); - if(rc) goto outro; - assert(deck.rid==rid); - rc = fsl__ticket_insert(&deck, tktId, &tktId); - if(0==rc){ - rc = fsl__ticket_timeline_entry(&deck, 0==counter++, tagId); - if(0==rc) rc = fsl__call_xlink_listeners(&deck); - } - outro: - fsl_deck_finalize(&deck); - } - end: - fsl_stmt_finalize(&q); - return rc; -} -/* end of file ./src/ticket.c */ -/* start of file ./src/udf.c */ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -/* - Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt - - SPDX-License-Identifier: BSD-2-Clause-FreeBSD - SPDX-FileCopyrightText: 2021 The Libfossil Authors - SPDX-ArtifactOfProjectName: Libfossil - SPDX-FileType: Code - - Heavily indebted to the Fossil SCM project (https://fossil-scm.org). -*/ -/************************************************************************* - This file houses fsl_cx-related sqlite3 User Defined Functions (UDFs). -*/ -#if !defined(FSL_ENABLE_SQLITE_REGEXP) -# define FSL_ENABLE_SQLITE_REGEXP 0 -#endif -#if FSL_ENABLE_SQLITE_REGEXP -#endif -#include - -/* Only for debugging */ -#include -#define MARKER(pfexp) \ - do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ - printf pfexp; \ - } while(0) - - -/** - SQL function for debugging. - - The print() function writes its arguments to fsl_output() - if the bound fsl_cx->cxConfig.sqlPrint flag is true. -*/ -static void fsl_db_sql_print( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); - assert(f); - if( f->cxConfig.sqlPrint ){ - int i; - for(i=0; ickout.dir && f->ckout.dirLen){ - sqlite3_result_text(context, f->ckout.dir, - (int)f->ckout.dirLen - - (includeSlash ? 0 : 1), - SQLITE_TRANSIENT); - }else{ - sqlite3_result_null(context); - } -} - - -/** - SQL Function to return the check-in time for a file. - Requires (vid,fid) RID arguments, as described for - fsl_mtime_of_manifest_file(). - */ -static void fsl_db_checkin_mtime_udf( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); - fsl_time_t mtime = 0; - int rc; - fsl_id_t vid, fid; - assert(f); - vid = (fsl_id_t)sqlite3_value_int(argv[0]); - fid = (fsl_id_t)sqlite3_value_int(argv[1]); - rc = fsl_mtime_of_manifest_file(f, vid, fid, &mtime); - if( rc==0 ){ - sqlite3_result_int64(context, mtime); - }else{ - sqlite3_result_error(context, "fsl_mtime_of_manifest_file() failed", -1); - } -} - - -/** - SQL UDF binding for fsl_content_get(). - - FSL_CONTENT(RID INTEGER | SYMBOLIC_NAME) returns the - undeltified/uncompressed content of the [blob] record identified by - the given RID or symbolic name. -*/ -static void fsl_db_content_udf( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - fsl_cx * const f = (fsl_cx*)sqlite3_user_data(context); - fsl_id_t rid = 0; - char const * arg; - int rc; - fsl_buffer b = fsl_buffer_empty; - assert(f); - if(1 != argc){ - sqlite3_result_error(context, "Expecting one argument", -1); - return; - } - if(SQLITE_INTEGER==sqlite3_value_type(argv[0])){ - rid = (fsl_id_t)sqlite3_value_int64(argv[0]); - arg = NULL; - }else{ - arg = (const char*)sqlite3_value_text(argv[0]); - if(!arg){ - sqlite3_result_error(context, "Invalid argument", -1); - return; - } - rc = fsl_sym_to_rid(f, arg, FSL_SATYPE_ANY, &rid); - if(rc) goto cx_err; - else if(!rid){ - sqlite3_result_error(context, "No blob found", -1); - return; - } - } - rc = fsl_content_get(f, rid, &b); - if(rc) goto cx_err; - /* Curiously, i'm seeing no difference in allocation counts here whether - we copy the blob here or pass off ownership... */ - sqlite3_result_blob(context, b.mem, (int)b.used, fsl_free); - b = fsl_buffer_empty; - return; - cx_err: - fsl_buffer_clear(&b); - assert(f->error.msg.used); - if(FSL_RC_OOM==rc){ - sqlite3_result_error_nomem(context); - }else{ - assert(f->error.msg.used); - sqlite3_result_error(context, (char const *)f->error.msg.mem, - (int)f->error.msg.used); - } -} - -/** - SQL UDF FSL_SYM2RID(SYMBOLIC_NAME) resolves the name to a [blob].[rid] - value or triggers an error if it cannot be resolved. - */ -static void fsl_db_sym2rid_udf( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - fsl_cx * const f = (fsl_cx*)sqlite3_user_data(context); - char const * arg; - assert(f); - if(1 != argc){ - sqlite3_result_error(context, "Expecting one argument", -1); - return; - } - arg = (const char*)sqlite3_value_text(argv[0]); - if(!arg){ - sqlite3_result_error(context, "Expecting a STRING argument", -1); - }else{ - fsl_id_t rid = 0; - int const rc = fsl_sym_to_rid(f, arg, FSL_SATYPE_ANY, &rid); - if(rc){ - if(FSL_RC_OOM==rc){ - sqlite3_result_error_nomem(context); - }else{ - assert(f->error.msg.used); - sqlite3_result_error(context, (char const *)f->error.msg.mem, - (int)f->error.msg.used); - } - fsl_cx_err_reset(f) - /* This is arguable but keeps this error from poluting - down-stream code (seen it happen in unit tests). The irony - is, it's very possible/likely that the error will propagate - back up into f->error at some point. - */; - }else{ - assert(rid>0); - sqlite3_result_int64(context, rid); - } - } -} - -static void fsl_db_dirpart_udf( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - char const * arg; - int rc; - fsl_buffer b = fsl_buffer_empty; - int fSlash = 0; - if(argc<1 || argc>2){ - sqlite3_result_error(context, - "Expecting (string) or (string,bool) arguments", - -1); - return; - } - arg = (const char*)sqlite3_value_text(argv[0]); - if(!arg){ - sqlite3_result_error(context, "Invalid argument", -1); - return; - } - if(argc>1){ - fSlash = sqlite3_value_int(argv[1]); - } - rc = fsl_file_dirpart(arg, -1, &b, fSlash ? 1 : 0); - if(!rc){ - if(b.used && *b.mem){ -#if 0 - sqlite3_result_text(context, (char const *)b.mem, - (int)b.used, SQLITE_TRANSIENT); -#else - sqlite3_result_text(context, (char const *)b.mem, - (int)b.used, fsl_free); - b = fsl_buffer_empty /* we passed ^^^^^ on ownership of b.mem */; -#endif - }else{ - sqlite3_result_null(context); - } - }else{ - if(FSL_RC_OOM==rc){ - sqlite3_result_error_nomem(context); - }else{ - sqlite3_result_error(context, "fsl_dirpart() failed!", -1); - } - } - fsl_buffer_clear(&b); -} - - -/* - Implement the user() SQL function. user() takes no arguments and - returns the user ID of the current user. -*/ -static void fsl_db_user_udf( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); - assert(f); - if(f->repo.user){ - sqlite3_result_text(context, f->repo.user, -1, SQLITE_STATIC); - }else{ - sqlite3_result_null(context); - } -} - -/** - SQL function: - - fsl_is_enqueued(vfile.id) - fsl_if_enqueued(vfile.id, X, Y) - - On the commit command, when filenames are specified (in order to do - a partial commit) the vfile.id values for the named files are - loaded into the fsl_cx state. This function looks at that state to - see if a file is named in that list. - - In the first form (1 argument) return TRUE if either no files are - named (meaning that all changes are to be committed) or if id is - found in the list. - - In the second form (3 arguments) return argument X if true and Y if - false unless Y is NULL, in which case always return X. -*/ -static void fsl_db_selected_for_checkin_udf( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - int rc = 0; - fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); - fsl_id_bag * bag = &f->ckin.selectedIds; - assert(argc==1 || argc==3); - if( bag->entryCount ){ - fsl_id_t const iId = (fsl_id_t)sqlite3_value_int64(argv[0]); - rc = iId ? (fsl_id_bag_contains(bag, iId) ? 1 : 0) : 0; - }else{ - rc = 1; - } - if(1==argc){ - sqlite3_result_int(context, rc); - }else{ - assert(3 == argc); - assert( rc==0 || rc==1 ); - if( sqlite3_value_type(argv[2-rc])==SQLITE_NULL ) rc = 1-rc; - sqlite3_result_value(context, argv[2-rc]); - } -} - -/** - fsl_match_vfile_or_dir(p1,p2) - - A helper for resolving expressions like: - - WHERE pathname='X' C OR - (pathname>'X/' C AND pathname<'X0' C) - - i.e. is 'X' a match for the LHS or is it a directory prefix of - LHS? - - C = empty or COLLATE NOCASE, depending on the case-sensitivity - setting of the fsl_cx instance associated with - sqlite3_user_data(context). p1 is typically vfile.pathname or - vfile.origname, and p2 is the string being compared against that. - - Resolves to NULL if either argument is NULL, 0 if the comparison - shown above is false, 1 if the comparison is an exact match, or 2 - if p2 is a directory prefix part of p1. -*/ -static void fsl_db_match_vfile_or_dir( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - fsl_cx * f = (fsl_cx*)sqlite3_user_data(context); - char const * p1; - char const * p2; - fsl_buffer * b = 0; - int rc = 0; - assert(f); - if(2 != argc){ - sqlite3_result_error(context, "Expecting two arguments", -1); - return; - } - p1 = (const char*)sqlite3_value_text(argv[0]); - p2 = (const char*)sqlite3_value_text(argv[1]); - if(!p1 || !p2){ - sqlite3_result_null(context); - return; - } - int (*cmp)(char const *, char const *) = - f->cache.caseInsensitive ? fsl_stricmp : fsl_strcmp; - if(0==cmp(p1, p2)){ - sqlite3_result_int(context, 1); - return; - } - b = fsl__cx_scratchpad(f); - rc = fsl_buffer_appendf(b, "%s/", p2); - if(rc) goto oom; - else if(cmp(p1, fsl_buffer_cstr(b))>0){ - b->mem[b->used-1] = '0'; - if(cmp(p1, fsl_buffer_cstr(b))<0) - rc = 2; - } - assert(0==rc || 2==rc); - sqlite3_result_int(context, rc); - end: - fsl__cx_scratchpad_yield(f, b); - return; - oom: - sqlite3_result_error_nomem(context); - goto end; -} - -/** - F(glob-list-name, filename) - - Returns 1 if the 2nd argument matches any glob in the fossil glob - list named by the first argument. The first argument must be a name - resolvable via fsl_glob_name_to_category() or an error is - triggered. The second value is intended to be a string, but NULL is - accepted (but never matches anything). - - If no match is found, 0 is returned. An empty glob list never matches - anything. -*/ -static void fsl_db_cx_glob_udf( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - fsl_cx * const f = (fsl_cx*)sqlite3_user_data(context); - fsl_list * li = NULL; - fsl_glob_category_e globType; - char const * p1; - char const * p2; - p2 = (const char*)sqlite3_value_text(argv[1])/*value to check*/; - if(NULL==p2 || 0==p2[0]){ - sqlite3_result_int(context, 0); - return; - } - p1 = (const char*)sqlite3_value_text(argv[0])/*glob set name*/; - globType = fsl_glob_name_to_category(p1); - if(FSL_GLOBS_INVALID==globType){ - char buf[100] = {0}; - buf[sizeof(buf)-1] = 0; - fsl_snprintf(buf, (fsl_size_t)sizeof(buf)-1, - "Unknown glob pattern name: %#.*s", - 50, p1 ? p1 : "NULL"); - sqlite3_result_error(context, buf, -1); - return; - } - fsl_cx_glob_list(f, globType, &li, false); - assert(li); - sqlite3_result_int(context, fsl_glob_list_matches(li, p2) ? 1 : 0); -} - - -/** - Plug in fsl_cx-specific db functionality into the given db handle. - This must only be passed the MAIN db handle for the context. -*/ -int fsl__cx_init_db(fsl_cx * const f, fsl_db * const db){ - int rc; - assert(!f->dbMain); - if(f->cxConfig.traceSql){ - fsl_db_sqltrace_enable(db, stdout); - } - f->dbMain = db; - db->role = FSL_DBROLE_MAIN; - /* This all comes from db.c:db_open()... */ - /* FIXME: check result codes here. */ - sqlite3 * const dbh = db->dbh; - sqlite3_busy_timeout(dbh, 5000 /* historical value */); - sqlite3_wal_autocheckpoint(dbh, 1); /* Set to checkpoint frequently */ - rc = fsl_cx_exec_multi(f, - "PRAGMA foreign_keys=OFF;" - // ^^^ vmerge table relies on this for its magical - // vmerge.id values. - //"PRAGMA main.temp_store=FILE;" - //"PRAGMA main.journal_mode=TRUNCATE;" - // ^^^ note that WAL is not possible on a TEMP db - // and OFF leads to undefined behaviour if - // ROLLBACK is used! - ); - if(rc) goto end; - sqlite3_create_function(dbh, "now", 0, SQLITE_ANY, 0, - fsl_db_now_udf, 0, 0); - sqlite3_create_function(dbh, "fsl_ci_mtime", 2, - SQLITE_ANY | SQLITE_DETERMINISTIC, f, - fsl_db_checkin_mtime_udf, 0, 0); - sqlite3_create_function(dbh, "fsl_user", 0, - SQLITE_ANY | SQLITE_DETERMINISTIC, f, - fsl_db_user_udf, 0, 0); - sqlite3_create_function(dbh, "fsl_print", -1, - SQLITE_UTF8 - /* not strictly SQLITE_DETERMINISTIC - because it produces output */, - f, fsl_db_sql_print,0,0); - sqlite3_create_function(dbh, "fsl_content", 1, - SQLITE_ANY | SQLITE_DETERMINISTIC, f, - fsl_db_content_udf, 0, 0); - sqlite3_create_function(dbh, "fsl_sym2rid", 1, - SQLITE_ANY | SQLITE_DETERMINISTIC, f, - fsl_db_sym2rid_udf, 0, 0); - sqlite3_create_function(dbh, "fsl_dirpart", 1, - SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, - fsl_db_dirpart_udf, 0, 0); - sqlite3_create_function(dbh, "fsl_dirpart", 2, - SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, - fsl_db_dirpart_udf, 0, 0); - sqlite3_create_function(dbh, "fsl_j2u", 1, - SQLITE_ANY | SQLITE_DETERMINISTIC, NULL, - fsl_db_j2u_udf, 0, 0); - /* - fsl_i[sf]_selected() both require access to the f's list of - files being considered for commit. - */ - sqlite3_create_function(dbh, "fsl_is_enqueued", 1, SQLITE_UTF8, f, - fsl_db_selected_for_checkin_udf,0,0 ); - sqlite3_create_function(dbh, "fsl_if_enqueued", 3, SQLITE_UTF8, f, - fsl_db_selected_for_checkin_udf,0,0 ); - - sqlite3_create_function(dbh, "fsl_ckout_dir", -1, - SQLITE_UTF8 | SQLITE_DETERMINISTIC, - f, fsl_db_cx_chkout_dir_udf,0,0 ); - sqlite3_create_function(dbh, "fsl_match_vfile_or_dir", 2, - SQLITE_UTF8 | SQLITE_DETERMINISTIC, - f, fsl_db_match_vfile_or_dir,0,0 ); - sqlite3_create_function(dbh, "fsl_glob", 2, - SQLITE_UTF8 | SQLITE_DETERMINISTIC, - /* noting that ^^^^^ it's only deterministic - for a given statement execution IF no SQL - triggers an effect which forces the globs to - reload. That "shouldn't ever happen." */ - f, fsl_db_cx_glob_udf, 0, 0 ); - -#if 0 - /* functions registered in v1 by db.c:db_open(). */ - /* porting cgi() requires access to the HTTP/CGI - layer. i.e. this belongs downstream. */ - sqlite3_create_function(dbh, "cgi", 1, SQLITE_ANY, 0, db_sql_cgi, 0, 0); - sqlite3_create_function(dbh, "cgi", 2, SQLITE_ANY, 0, db_sql_cgi, 0, 0); - re_add_sql_func(db) /* Requires the regex bits. */; -#endif - end: - return rc; -} - - -#undef MARKER -/* end of file ./src/udf.c */ -/* start of file ./src/utf8.c */ +/* end of file ticket.c */ +/* start of file utf8.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* ** Copyright (c) 2017 D. Richard Hipp ** @@ -41398,12 +38644,12 @@ } } return zPath; #elif defined(__APPLE__) && !defined(WITHOUT_ICONV) return fsl_strdup(zUtf8) - /* Why? Why not just act like Unix? - Much later: so that fsl_filename_free() can DTRT. */; + /* Why? Why not just act like Unix? */ + ; #else return (void *)zUtf8; /* No-op on unix */ #endif } @@ -41448,12 +38694,12 @@ } } return rc; } } -/* end of file ./src/utf8.c */ -/* start of file ./src/vfile.c */ +/* end of file utf8.c */ +/* start of file vfile.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -41646,23 +38892,24 @@ int fsl_vfile_changes_scan(fsl_cx * const f, fsl_id_t vid, unsigned cksigFlags){ fsl_stmt * stUpdate = NULL; fsl_stmt q = fsl_stmt_empty; int rc = 0; + fsl_db * const db = fsl_needs_ckout(f); fsl_fstat fst = fsl_fstat_empty; fsl_size_t rootLen; fsl_buffer * fileCksum = fsl__cx_scratchpad(f); bool const useMtime = (cksigFlags & FSL_VFILE_CKSIG_HASH)==0 && fsl_config_get_bool(f, FSL_CONFDB_REPO, true, "mtime-changes"); - if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT; + if(!db) return FSL_RC_NOT_A_CKOUT; assert(f->ckout.dir); if(vid<=0) vid = f->ckout.rid; assert(vid>=0); rootLen = fsl_strlen(f->ckout.dir); assert(rootLen); - rc = fsl_cx_transaction_begin(f); + rc = fsl_db_transaction_begin(db); if(rc) return rc; if(f->ckout.rid != vid){ rc = fsl_vfile_load(f, vid, (FSL_VFILE_CKSIG_KEEP_OTHERS & cksigFlags) ? false : true, NULL); @@ -41679,11 +38926,11 @@ "WHERE vf.vid=%"FSL_ID_T_PFMT" " "AND (chnged<>0 OR pathname<>origname OR deleted<>0)" "ORDER BY vf.id", vid); #endif - rc = fsl_cx_prepare(f, &q, "SELECT " + rc = fsl_db_prepare(db, &q, "SELECT " /*0*/"id," /*1*/"%Q || pathname," /*2*/"vfile.mrid," /*3*/"deleted," /*4*/"chnged," @@ -41840,19 +39087,25 @@ } } #endif if( currentMtime!=oldMtime || changed!=oldChanged ){ if(!stUpdate){ - rc = fsl_cx_prepare_cached(f, &stUpdate, + rc = fsl_db_prepare_cached(db, &stUpdate, "UPDATE vfile SET " "mtime=?1, chnged=?2 " "WHERE id=?3 " "/*%s()*/",__func__); if(rc) goto end; + }else{ + fsl_stmt_reset(stUpdate); } - rc = fsl_stmt_bind_step(stUpdate, "IiR", currentMtime, changed, id); - if(rc) goto end; + fsl_stmt_bind_int64(stUpdate, 1, currentMtime); + fsl_stmt_bind_int32(stUpdate, 2, changed); + fsl_stmt_bind_id(stUpdate, 3, id); + rc = fsl_stmt_step(stUpdate); + if(FSL_RC_STEP_DONE!=rc) goto end; + rc = 0; /* MARKER(("UPDATED vfile.(mtime,chnged) for: %s\n", zName)); */ } }/*while(step)*/ #if 0 @@ -41866,21 +39119,23 @@ "AND (chnged<>0 OR pathname<>origname OR deleted<>0)" "ORDER BY vf.id", vid); #endif end: fsl__cx_scratchpad_yield(f, fileCksum); - if(!rc){ - rc = fsl__ckout_clear_merge_state(f, false); - } if(!rc && (cksigFlags & FSL_VFILE_CKSIG_WRITE_CKOUT_VERSION) && (f->ckout.rid != vid)){ rc = fsl__ckout_version_write(f, vid, 0); + }else if(rc){ + rc = fsl_cx_uplift_db_error2(f, db, rc); } if(rc) { - fsl_cx_transaction_end(f, true); + fsl_db_transaction_rollback(db); }else{ - rc = fsl_cx_transaction_end(f, false); + rc = fsl_db_transaction_commit(db); + if(rc){ + rc = fsl_cx_uplift_db_error2(f, db, rc); + } } fsl_stmt_cached_yield(stUpdate); fsl_stmt_finalize(&q); return rc; } @@ -42024,12 +39279,12 @@ fsl_stmt_finalize(&q); return rc; } #undef MARKER -/* end of file ./src/vfile.c */ -/* start of file ./src/vpath.c */ +/* end of file vfile.c */ +/* start of file vpath.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -42230,13 +39485,12 @@ return rc; } /** Creates, if needed, the [ancestor] table, else clears its - contents. Returns 0 on success, non-0 on db error (in which case - f's error state is updated). -*/ + contents. Returns + */ static int fsl__init_ancestor(fsl_cx * const f){ fsl_db * const db = fsl_cx_db_repo(f); int rc; if(db){ rc = fsl_db_exec_multi(db, @@ -42469,12 +39723,12 @@ rc = fsl_cx_uplift_db_error2(f, db, rc); goto end; } #undef MARKER -/* end of file ./src/vpath.c */ -/* start of file ./src/wiki.c */ +/* end of file vpath.c */ +/* start of file wiki.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt @@ -42496,11 +39750,11 @@ do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ printf pfexp; \ } while(0) -int fsl_wiki_names_get( fsl_cx * const f, fsl_list * const tgt ){ +int fsl_wiki_names_get( fsl_cx * f, fsl_list * tgt ){ fsl_db * db = fsl_needs_repo(f); if(!f || !tgt) return FSL_RC_MISUSE; else if(!db) return FSL_RC_NOT_A_REPO; else { int rc = fsl_db_select_slist( db, tgt, @@ -42513,32 +39767,30 @@ } return rc; } } -int fsl_wiki_latest_rid( fsl_cx * const f, char const * pageName, fsl_id_t * const rid ){ +int fsl_wiki_latest_rid( fsl_cx * f, char const * pageName, fsl_id_t * rid ){ fsl_db * db = f ? fsl_needs_repo(f) : NULL; if(!f || !pageName) return FSL_RC_MISUSE; else if(!*pageName) return FSL_RC_RANGE; else if(!db) return FSL_RC_NOT_A_REPO; else return fsl_db_get_id(db, rid, "SELECT x.rid FROM tag t, tagxref x " "WHERE x.tagid=t.tagid " "AND t.tagname='wiki-%q' " - "AND TYPEOF(x.value+0)='integer' " - // ^^^^ only 'wiki-%' tags which are wiki pages "ORDER BY mtime DESC LIMIT 1", pageName); } -bool fsl_wiki_page_exists(fsl_cx * const f, char const * pageName){ +bool fsl_wiki_page_exists(fsl_cx * f, char const * pageName){ fsl_id_t rid = 0; return (0==fsl_wiki_latest_rid(f, pageName, &rid)) && (rid>0); } -int fsl_wiki_load_latest( fsl_cx * const f, char const * pageName, fsl_deck * d ){ +int fsl_wiki_load_latest( fsl_cx * f, char const * pageName, fsl_deck * d ){ fsl_db * db = f ? fsl_needs_repo(f) : NULL; if(!f || !pageName || !d) return FSL_RC_MISUSE; else if(!*pageName) return FSL_RC_RANGE; else if(!db) return FSL_RC_NOT_A_REPO; else{ @@ -42548,19 +39800,20 @@ else if(0==rid) return FSL_RC_NOT_FOUND; return fsl_deck_load_rid( f, d, rid, FSL_SATYPE_WIKI); } } -int fsl_wiki_foreach_page( fsl_cx * const f, fsl_deck_visitor_f cb, void * state ){ - if(!cb) return FSL_RC_MISUSE; - else if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO; +int fsl_wiki_foreach_page( fsl_cx * f, fsl_deck_visitor_f cb, void * state ){ + fsl_db * db = f ? fsl_needs_repo(f) : NULL; + if(!f || !cb) return FSL_RC_MISUSE; + else if(!db) return FSL_RC_NOT_A_REPO; else{ fsl_stmt st = fsl_stmt_empty; fsl_stmt names = fsl_stmt_empty; int rc; - bool doBreak = false; - rc = fsl_cx_prepare(f, &names, + char doBreak = 0; + rc = fsl_db_prepare(db, &names, "SELECT substr(tagname,6) AS name " "FROM tag " "WHERE tagname GLOB 'wiki-*' " "ORDER BY lower(name)"); if(rc) return rc; @@ -42567,36 +39820,36 @@ while( !doBreak && !rc && (FSL_RC_STEP_ROW==fsl_stmt_step(&names))){ fsl_size_t nameLen = 0; char const * pageName = fsl_stmt_g_text(&names, 0, &nameLen); if(!st.stmt){ - rc = fsl_cx_prepare(f, &st, + rc = fsl_db_prepare(db, &st, "SELECT x.rid AS mrid FROM tag t, tagxref x " "WHERE x.tagid=t.tagid " - "AND t.tagname='wiki-'||?1 " - "AND TYPEOF(x.value+0)='integer' " - // ^^^^ only 'wiki-%' tags which are wiki pages - "ORDER BY x.mtime DESC LIMIT 1"); + "AND t.tagname='wiki-'||? " + "ORDER BY mtime DESC LIMIT 1"); if(rc) goto end; } - rc = fsl_stmt_bind_step(&st, "s", pageName); - if(rc!=FSL_RC_STEP_ROW) continue; - fsl_deck d = fsl_deck_empty; - fsl_id_t const rid = fsl_stmt_g_id(&st, 0); - rc = fsl_deck_load_rid( f, &d, rid, FSL_SATYPE_WIKI); - if(!rc){ - assert(d.rid==rid); - rc = cb(f, &d, state); - if(FSL_RC_BREAK==rc){ - rc = 0; - doBreak = true; - } - } - fsl_deck_finalize(&d); + rc = fsl_stmt_bind_text(&st, 1, pageName, (fsl_int_t)nameLen, 0); + if(rc) break; + rc = fsl_stmt_step(&st); + assert(FSL_RC_STEP_ROW==rc); + if(FSL_RC_STEP_ROW==rc){ + fsl_deck d = fsl_deck_empty; + fsl_id_t rid = fsl_stmt_g_id(&st, 0); + rc = fsl_deck_load_rid( f, &d, rid, FSL_SATYPE_WIKI); + if(!rc){ + rc = cb(f, &d, state); + if(FSL_RC_BREAK==rc){ + rc = 0; + doBreak = 1; + } + } + fsl_deck_finalize(&d); + } fsl_stmt_reset(&st); } - end: fsl_stmt_finalize(&st); fsl_stmt_finalize(&names); return rc; } @@ -42668,12 +39921,12 @@ return rc; } } #undef MARKER -/* end of file ./src/wiki.c */ -/* start of file ./src/zip.c */ +/* end of file wiki.c */ +/* start of file zip.c */ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* ** Copyright (c) 2017 D. Richard Hipp ** @@ -43141,11 +40394,11 @@ } return rc; } -int fsl_repo_zip_sym_to_filename( fsl_cx * const f, char const * sym, +int fsl_repo_zip_sym_to_filename( fsl_cx * f, char const * sym, char const * rootDir, char const * fileName, fsl_card_F_visitor_f progress, void * progressState ){ int rc; @@ -43190,11 +40443,11 @@ /** Always write the manifest files to the zip, regardless of the repo-level settings. This decision is up for debate. */ if(rc) goto end; else { - fsl_buffer * const bManifest = &f->cache.fileContent; + fsl_buffer * const bManifest = &f->fileContent; fsl_buffer * const bHash = fsl__cx_scratchpad(f); fsl_buffer * const bTags = fsl__cx_scratchpad(f); fsl_buffer_reuse(bManifest); rc = fsl_repo_manifest_write(f, mf.rid, bManifest, bHash, bTags); if(rc) goto mf_end; @@ -43227,727 +40480,28 @@ } #undef MARKER -/* end of file ./src/zip.c */ -/* start of file ./src/difftk_cstr.c */ -/** @page page_difftk_cstr difftk.tcl - -Binary form of file ./src/difftk.tcl. - -*/ -/* auto-generated code - edit at your own risk! (Good luck with that!) */ -static char const fsl_difftk_cstr_a[] = { -35, 32, 84, 104, 105, 115, 32, 115, 99, 114, 105, 112, 116, 32, 119, 97, 115, 32, 116, 97, -107, 101, 110, 32, 118, 101, 114, 98, 97, 116, 105, 109, 32, 102, 114, 111, 109, 32, 116, 104, -101, 32, 70, 111, 115, 115, 105, 108, 32, 83, 67, 77, 32, 112, 114, 111, 106, 101, 99, 116, -46, 32, 32, 73, 116, 32, 105, 115, 10, 35, 32, 110, 111, 116, 32, 115, 116, 97, 110, 100, -97, 108, 111, 110, 101, 58, 32, 105, 116, 32, 105, 115, 32, 105, 110, 116, 101, 110, 100, 101, -100, 32, 116, 111, 32, 98, 101, 32, 101, 109, 98, 101, 100, 100, 101, 100, 32, 105, 110, 32, -111, 117, 116, 112, 117, 116, 32, 103, 101, 110, 101, 114, 97, 116, 101, 100, 32, 98, 121, 10, -35, 32, 102, 45, 118, 100, 105, 102, 102, 32, 40, 111, 114, 32, 115, 105, 109, 105, 108, 97, -114, 41, 46, 10, 115, 101, 116, 32, 112, 114, 111, 103, 32, 123, 10, 112, 97, 99, 107, 97, -103, 101, 32, 114, 101, 113, 117, 105, 114, 101, 32, 84, 107, 10, 10, 97, 114, 114, 97, 121, -32, 115, 101, 116, 32, 67, 70, 71, 32, 123, 10, 32, 32, 84, 73, 84, 76, 69, 32, 32, -32, 32, 32, 32, 123, 70, 111, 115, 115, 105, 108, 32, 68, 105, 102, 102, 125, 10, 32, 32, -76, 78, 95, 67, 79, 76, 95, 66, 71, 32, 32, 35, 100, 100, 100, 100, 100, 100, 10, 32, -32, 76, 78, 95, 67, 79, 76, 95, 70, 71, 32, 32, 35, 52, 52, 52, 52, 52, 52, 10, -32, 32, 84, 88, 84, 95, 67, 79, 76, 95, 66, 71, 32, 35, 102, 102, 102, 102, 102, 102, -10, 32, 32, 84, 88, 84, 95, 67, 79, 76, 95, 70, 71, 32, 35, 48, 48, 48, 48, 48, -48, 10, 32, 32, 77, 75, 82, 95, 67, 79, 76, 95, 66, 71, 32, 35, 52, 52, 52, 52, -52, 52, 10, 32, 32, 77, 75, 82, 95, 67, 79, 76, 95, 70, 71, 32, 35, 100, 100, 100, -100, 100, 100, 10, 32, 32, 67, 72, 78, 71, 95, 66, 71, 32, 32, 32, 32, 35, 100, 48, -100, 48, 102, 102, 10, 32, 32, 65, 68, 68, 95, 66, 71, 32, 32, 32, 32, 32, 35, 99, -48, 102, 102, 99, 48, 10, 32, 32, 82, 77, 95, 66, 71, 32, 32, 32, 32, 32, 32, 35, -102, 102, 99, 48, 99, 48, 10, 32, 32, 72, 82, 95, 70, 71, 32, 32, 32, 32, 32, 32, -35, 52, 52, 52, 52, 52, 52, 10, 32, 32, 72, 82, 95, 80, 65, 68, 95, 84, 79, 80, -32, 52, 10, 32, 32, 72, 82, 95, 80, 65, 68, 95, 66, 84, 77, 32, 56, 10, 32, 32, -70, 78, 95, 66, 71, 32, 32, 32, 32, 32, 32, 35, 52, 52, 52, 52, 52, 52, 10, 32, -32, 70, 78, 95, 70, 71, 32, 32, 32, 32, 32, 32, 35, 102, 102, 102, 102, 102, 102, 10, -32, 32, 70, 78, 95, 80, 65, 68, 32, 32, 32, 32, 32, 53, 10, 32, 32, 69, 82, 82, -95, 70, 71, 32, 32, 32, 32, 32, 35, 101, 101, 48, 48, 48, 48, 10, 32, 32, 80, 65, -68, 88, 32, 32, 32, 32, 32, 32, 32, 53, 10, 32, 32, 87, 73, 68, 84, 72, 32, 32, -32, 32, 32, 32, 56, 48, 10, 32, 32, 72, 69, 73, 71, 72, 84, 32, 32, 32, 32, 32, -52, 53, 10, 32, 32, 76, 66, 95, 72, 69, 73, 71, 72, 84, 32, 32, 50, 53, 10, 125, -10, 10, 105, 102, 32, 123, 33, 91, 110, 97, 109, 101, 115, 112, 97, 99, 101, 32, 101, 120, -105, 115, 116, 115, 32, 116, 116, 107, 93, 125, 32, 123, 10, 32, 32, 105, 110, 116, 101, 114, -112, 32, 97, 108, 105, 97, 115, 32, 123, 125, 32, 58, 58, 116, 116, 107, 58, 58, 115, 99, -114, 111, 108, 108, 98, 97, 114, 32, 123, 125, 32, 58, 58, 115, 99, 114, 111, 108, 108, 98, -97, 114, 10, 32, 32, 105, 110, 116, 101, 114, 112, 32, 97, 108, 105, 97, 115, 32, 123, 125, -32, 58, 58, 116, 116, 107, 58, 58, 109, 101, 110, 117, 98, 117, 116, 116, 111, 110, 32, 123, -125, 32, 58, 58, 109, 101, 110, 117, 98, 117, 116, 116, 111, 110, 10, 125, 10, 10, 112, 114, -111, 99, 32, 100, 101, 104, 116, 109, 108, 32, 123, 120, 125, 32, 123, 10, 32, 32, 115, 101, -116, 32, 120, 32, 91, 114, 101, 103, 115, 117, 98, 32, 45, 97, 108, 108, 32, 123, 60, 91, -94, 62, 93, 42, 62, 125, 32, 36, 120, 32, 123, 125, 93, 10, 32, 32, 114, 101, 116, 117, -114, 110, 32, 91, 115, 116, 114, 105, 110, 103, 32, 109, 97, 112, 32, 123, 38, 97, 109, 112, -59, 32, 38, 32, 38, 108, 116, 59, 32, 60, 32, 38, 103, 116, 59, 32, 62, 32, 38, 35, -51, 57, 59, 32, 39, 32, 38, 113, 117, 111, 116, 59, 32, 92, 34, 125, 32, 36, 120, 93, -10, 125, 10, 10, 112, 114, 111, 99, 32, 99, 111, 108, 115, 32, 123, 125, 32, 123, 10, 32, -32, 114, 101, 116, 117, 114, 110, 32, 91, 108, 105, 115, 116, 32, 46, 108, 110, 65, 32, 46, -116, 120, 116, 65, 32, 46, 109, 107, 114, 32, 46, 108, 110, 66, 32, 46, 116, 120, 116, 66, -93, 10, 125, 10, 10, 112, 114, 111, 99, 32, 99, 111, 108, 84, 121, 112, 101, 32, 123, 99, -125, 32, 123, 10, 32, 32, 114, 101, 103, 101, 120, 112, 32, 123, 91, 97, 45, 122, 93, 43, -125, 32, 36, 99, 32, 116, 121, 112, 101, 10, 32, 32, 114, 101, 116, 117, 114, 110, 32, 36, -116, 121, 112, 101, 10, 125, 10, 10, 112, 114, 111, 99, 32, 103, 101, 116, 76, 105, 110, 101, -32, 123, 100, 105, 102, 102, 116, 120, 116, 32, 78, 32, 105, 105, 118, 97, 114, 125, 32, 123, -10, 32, 32, 117, 112, 118, 97, 114, 32, 36, 105, 105, 118, 97, 114, 32, 105, 105, 10, 32, -32, 105, 102, 32, 123, 36, 105, 105, 62, 61, 36, 78, 125, 32, 123, 114, 101, 116, 117, 114, -110, 32, 45, 49, 125, 10, 32, 32, 115, 101, 116, 32, 120, 32, 91, 108, 105, 110, 100, 101, -120, 32, 36, 100, 105, 102, 102, 116, 120, 116, 32, 36, 105, 105, 93, 10, 32, 32, 105, 110, -99, 114, 32, 105, 105, 10, 32, 32, 114, 101, 116, 117, 114, 110, 32, 36, 120, 10, 125, 10, -10, 112, 114, 111, 99, 32, 114, 101, 97, 100, 68, 105, 102, 102, 115, 32, 123, 102, 111, 115, -115, 105, 108, 99, 109, 100, 125, 32, 123, 10, 32, 32, 103, 108, 111, 98, 97, 108, 32, 100, -105, 102, 102, 116, 120, 116, 10, 32, 32, 105, 102, 32, 123, 33, 91, 105, 110, 102, 111, 32, -101, 120, 105, 115, 116, 115, 32, 100, 105, 102, 102, 116, 120, 116, 93, 125, 32, 123, 10, 32, -32, 32, 32, 115, 101, 116, 32, 105, 110, 32, 91, 111, 112, 101, 110, 32, 36, 102, 111, 115, -115, 105, 108, 99, 109, 100, 32, 114, 93, 10, 32, 32, 32, 32, 102, 99, 111, 110, 102, 105, -103, 117, 114, 101, 32, 36, 105, 110, 32, 45, 101, 110, 99, 111, 100, 105, 110, 103, 32, 117, -116, 102, 45, 56, 10, 32, 32, 32, 32, 115, 101, 116, 32, 100, 105, 102, 102, 116, 120, 116, -32, 91, 115, 112, 108, 105, 116, 32, 91, 114, 101, 97, 100, 32, 36, 105, 110, 93, 32, 92, -110, 93, 10, 32, 32, 32, 32, 99, 108, 111, 115, 101, 32, 36, 105, 110, 10, 32, 32, 125, -10, 32, 32, 115, 101, 116, 32, 78, 32, 91, 108, 108, 101, 110, 103, 116, 104, 32, 36, 100, -105, 102, 102, 116, 120, 116, 93, 10, 32, 32, 115, 101, 116, 32, 105, 105, 32, 48, 10, 32, -32, 115, 101, 116, 32, 110, 68, 105, 102, 102, 115, 32, 48, 10, 32, 32, 115, 101, 116, 32, -110, 49, 32, 48, 10, 32, 32, 115, 101, 116, 32, 110, 50, 32, 48, 32, 32, 10, 32, 32, -97, 114, 114, 97, 121, 32, 115, 101, 116, 32, 119, 105, 100, 116, 104, 115, 32, 123, 116, 120, -116, 32, 51, 32, 108, 110, 32, 51, 32, 109, 107, 114, 32, 49, 125, 10, 32, 32, 119, 104, -105, 108, 101, 32, 123, 91, 115, 101, 116, 32, 108, 105, 110, 101, 32, 91, 103, 101, 116, 76, -105, 110, 101, 32, 36, 100, 105, 102, 102, 116, 120, 116, 32, 36, 78, 32, 105, 105, 93, 93, -32, 33, 61, 32, 45, 49, 125, 32, 123, 10, 32, 32, 32, 32, 115, 119, 105, 116, 99, 104, -32, 45, 45, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 48, 93, -32, 123, 10, 32, 32, 32, 32, 32, 32, 70, 73, 76, 69, 32, 123, 10, 32, 32, 32, 32, -32, 32, 32, 32, 105, 110, 99, 114, 32, 110, 68, 105, 102, 102, 115, 10, 32, 32, 32, 32, -32, 32, 32, 32, 102, 111, 114, 101, 97, 99, 104, 32, 119, 120, 32, 91, 108, 105, 115, 116, -32, 91, 115, 116, 114, 105, 110, 103, 32, 108, 101, 110, 103, 116, 104, 32, 36, 110, 49, 93, -32, 91, 115, 116, 114, 105, 110, 103, 32, 108, 101, 110, 103, 116, 104, 32, 36, 110, 50, 93, -93, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 105, 102, 32, 123, 36, 119, -120, 62, 36, 119, 105, 100, 116, 104, 115, 40, 108, 110, 41, 125, 32, 123, 115, 101, 116, 32, -119, 105, 100, 116, 104, 115, 40, 108, 110, 41, 32, 36, 119, 120, 125, 10, 32, 32, 32, 32, -32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, -110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 102, 110, 32, 92, 110, 32, 45, -10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, -116, 32, 101, 110, 100, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, -49, 93, 92, 110, 32, 102, 110, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, -32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, -102, 110, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 66, -32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 102, 110, 32, 92, 110, -32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, -101, 114, 116, 32, 101, 110, 100, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, -101, 32, 50, 93, 92, 110, 32, 102, 110, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, -32, 32, 32, 46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 105, 110, 115, 101, 114, 116, -32, 101, 110, 100, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 50, -93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 110, 49, 32, 48, 10, 32, -32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 110, 50, 32, 48, 10, 32, 32, 32, 32, -32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 83, 75, 73, 80, 32, 123, 10, 32, 32, 32, -32, 32, 32, 32, 32, 115, 101, 116, 32, 110, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, -108, 105, 110, 101, 32, 49, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, -32, 110, 49, 32, 36, 110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, -110, 50, 32, 36, 110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, -110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 46, 46, 46, 92, 110, 32, 104, 114, 108, 110, -10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, -116, 32, 101, 110, 100, 32, 91, 115, 116, 114, 105, 110, 103, 32, 114, 101, 112, 101, 97, 116, -32, 46, 32, 51, 48, 93, 92, 110, 32, 104, 114, 116, 120, 116, 10, 32, 32, 32, 32, 32, -32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, -110, 32, 104, 114, 108, 110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 66, 32, -105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 46, 46, 46, 92, 110, 32, 104, 114, 108, -110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 101, -114, 116, 32, 101, 110, 100, 32, 91, 115, 116, 114, 105, 110, 103, 32, 114, 101, 112, 101, 97, -116, 32, 46, 32, 51, 48, 93, 92, 110, 32, 104, 114, 116, 120, 116, 10, 32, 32, 32, 32, -32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 67, 79, 77, 32, 123, 10, 32, 32, 32, 32, -32, 32, 32, 32, 115, 101, 116, 32, 120, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, -105, 110, 101, 32, 49, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, -110, 49, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 110, 50, 10, 32, -32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, -110, 100, 32, 36, 110, 49, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, -116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 92, 110, -32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, -114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, -46, 108, 110, 66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 110, 50, 92, -110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, -115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 92, 110, 32, 45, 10, 32, 32, 32, 32, -32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 73, 78, 83, 32, 123, 10, 32, 32, 32, 32, -32, 32, 32, 32, 115, 101, 116, 32, 120, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, -105, 110, 101, 32, 49, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, -110, 50, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 110, 115, 101, -114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, -46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, -45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, -116, 32, 101, 110, 100, 32, 62, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, -46, 108, 110, 66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 110, 50, 92, -110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, -115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 32, 97, 100, 100, 32, 92, 110, 32, 45, -10, 32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 68, 69, 76, 32, 123, -10, 32, 32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 120, 32, 91, 108, 105, 110, 100, -101, 120, 32, 36, 108, 105, 110, 101, 32, 49, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, -105, 110, 99, 114, 32, 110, 49, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, -32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 110, 49, 92, 110, 32, 45, 10, -32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, -32, 101, 110, 100, 32, 36, 120, 32, 114, 109, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, -32, 32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, -60, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 66, 32, 105, -110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, -32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, -92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 69, -68, 73, 84, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 110, -49, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 110, 50, 10, 32, 32, -32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, -100, 32, 36, 110, 49, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, -110, 66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 110, 50, 92, 110, 32, -45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, -116, 32, 101, 110, 100, 32, 124, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, -115, 101, 116, 32, 110, 110, 32, 91, 108, 108, 101, 110, 103, 116, 104, 32, 36, 108, 105, 110, -101, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 102, 111, 114, 32, 123, 115, 101, 116, 32, -105, 32, 49, 125, 32, 123, 36, 105, 60, 36, 110, 110, 125, 32, 123, 105, 110, 99, 114, 32, -105, 32, 51, 125, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 115, 101, 116, -32, 120, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 36, 105, 93, -10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 105, 102, 32, 123, 36, 120, 32, 110, 101, -32, 34, 34, 125, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, -116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 32, 45, -10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, -110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 32, 45, 10, 32, 32, 32, 32, 32, -32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 105, 102, 32, -123, 36, 105, 43, 50, 60, 36, 110, 110, 125, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, -32, 32, 32, 32, 32, 115, 101, 116, 32, 120, 49, 32, 91, 108, 105, 110, 100, 101, 120, 32, -36, 108, 105, 110, 101, 32, 91, 101, 120, 112, 114, 32, 123, 36, 105, 43, 49, 125, 93, 93, -10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 120, 50, 32, -91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 91, 101, 120, 112, 114, 32, -123, 36, 105, 43, 50, 125, 93, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, -32, 105, 102, 32, 123, 34, 36, 120, 49, 34, 32, 101, 113, 32, 34, 34, 125, 32, 123, 10, -32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, -105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 50, 32, 97, 100, 100, 10, 32, -32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 105, 102, 32, -123, 34, 36, 120, 50, 34, 32, 101, 113, 32, 34, 34, 125, 32, 123, 10, 32, 32, 32, 32, -32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, -114, 116, 32, 101, 110, 100, 32, 36, 120, 49, 32, 114, 109, 10, 32, 32, 32, 32, 32, 32, -32, 32, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 32, -32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, -116, 32, 101, 110, 100, 32, 36, 120, 49, 32, 99, 104, 110, 103, 10, 32, 32, 32, 32, 32, -32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 101, 114, -116, 32, 101, 110, 100, 32, 36, 120, 50, 32, 99, 104, 110, 103, 10, 32, 32, 32, 32, 32, -32, 32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 125, -10, 32, 32, 32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, -116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, -10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 101, 114, -116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 125, 10, 32, -32, 32, 32, 32, 32, 34, 34, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 102, 111, -114, 101, 97, 99, 104, 32, 119, 120, 32, 91, 108, 105, 115, 116, 32, 91, 115, 116, 114, 105, -110, 103, 32, 108, 101, 110, 103, 116, 104, 32, 36, 110, 49, 93, 32, 91, 115, 116, 114, 105, -110, 103, 32, 108, 101, 110, 103, 116, 104, 32, 36, 110, 50, 93, 93, 32, 123, 10, 32, 32, -32, 32, 32, 32, 32, 32, 32, 32, 105, 102, 32, 123, 36, 119, 120, 62, 36, 119, 105, 100, -116, 104, 115, 40, 108, 110, 41, 125, 32, 123, 115, 101, 116, 32, 119, 105, 100, 116, 104, 115, -40, 108, 110, 41, 32, 36, 119, 120, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 125, 10, -32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 100, 101, 102, 97, 117, 108, -116, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 110, 115, -101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, -32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 108, -105, 110, 101, 92, 110, 32, 101, 114, 114, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 109, -107, 114, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, -32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 66, 32, 105, 110, 115, 101, 114, 116, 32, 101, -110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, -66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 108, 105, 110, 101, 92, 110, -32, 101, 114, 114, 10, 32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 125, 10, 32, -32, 125, 10, 10, 32, 32, 102, 111, 114, 101, 97, 99, 104, 32, 99, 32, 91, 99, 111, 108, -115, 93, 32, 123, 10, 32, 32, 32, 32, 115, 101, 116, 32, 116, 121, 112, 101, 32, 91, 99, -111, 108, 84, 121, 112, 101, 32, 36, 99, 93, 10, 32, 32, 32, 32, 105, 102, 32, 123, 36, -116, 121, 112, 101, 32, 110, 101, 32, 34, 116, 120, 116, 34, 125, 32, 123, 10, 32, 32, 32, -32, 32, 32, 36, 99, 32, 99, 111, 110, 102, 105, 103, 32, 45, 119, 105, 100, 116, 104, 32, -36, 119, 105, 100, 116, 104, 115, 40, 36, 116, 121, 112, 101, 41, 10, 32, 32, 32, 32, 125, -10, 32, 32, 32, 32, 36, 99, 32, 99, 111, 110, 102, 105, 103, 32, 45, 115, 116, 97, 116, -101, 32, 100, 105, 115, 97, 98, 108, 101, 100, 10, 32, 32, 125, 10, 32, 32, 105, 102, 32, -123, 36, 110, 68, 105, 102, 102, 115, 32, 60, 61, 32, 91, 46, 119, 102, 105, 108, 101, 115, -46, 108, 98, 32, 99, 103, 101, 116, 32, 45, 104, 101, 105, 103, 104, 116, 93, 125, 32, 123, -10, 32, 32, 32, 32, 46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 99, 111, 110, 102, -105, 103, 32, 45, 104, 101, 105, 103, 104, 116, 32, 36, 110, 68, 105, 102, 102, 115, 10, 32, -32, 32, 32, 103, 114, 105, 100, 32, 114, 101, 109, 111, 118, 101, 32, 46, 119, 102, 105, 108, -101, 115, 46, 115, 98, 10, 32, 32, 125, 10, 10, 32, 32, 114, 101, 116, 117, 114, 110, 32, -36, 110, 68, 105, 102, 102, 115, 10, 125, 10, 10, 112, 114, 111, 99, 32, 118, 105, 101, 119, -68, 105, 102, 102, 32, 123, 105, 100, 120, 125, 32, 123, 10, 32, 32, 46, 116, 120, 116, 65, -32, 121, 118, 105, 101, 119, 32, 36, 105, 100, 120, 10, 32, 32, 46, 116, 120, 116, 65, 32, -120, 118, 105, 101, 119, 32, 109, 111, 118, 101, 116, 111, 32, 48, 10, 125, 10, 10, 112, 114, -111, 99, 32, 99, 121, 99, 108, 101, 68, 105, 102, 102, 115, 32, 123, 123, 114, 101, 118, 101, -114, 115, 101, 32, 48, 125, 125, 32, 123, 10, 32, 32, 105, 102, 32, 123, 36, 114, 101, 118, -101, 114, 115, 101, 125, 32, 123, 10, 32, 32, 32, 32, 115, 101, 116, 32, 114, 97, 110, 103, -101, 32, 91, 46, 116, 120, 116, 65, 32, 116, 97, 103, 32, 112, 114, 101, 118, 114, 97, 110, -103, 101, 32, 102, 110, 32, 64, 48, 44, 48, 32, 49, 46, 48, 93, 10, 32, 32, 32, 32, -105, 102, 32, 123, 36, 114, 97, 110, 103, 101, 32, 101, 113, 32, 34, 34, 125, 32, 123, 10, -32, 32, 32, 32, 32, 32, 118, 105, 101, 119, 68, 105, 102, 102, 32, 123, 102, 110, 46, 108, -97, 115, 116, 32, 45, 49, 99, 125, 10, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 32, -123, 10, 32, 32, 32, 32, 32, 32, 118, 105, 101, 119, 68, 105, 102, 102, 32, 91, 108, 105, -110, 100, 101, 120, 32, 36, 114, 97, 110, 103, 101, 32, 48, 93, 10, 32, 32, 32, 32, 125, -10, 32, 32, 125, 32, 101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 115, 101, 116, 32, -114, 97, 110, 103, 101, 32, 91, 46, 116, 120, 116, 65, 32, 116, 97, 103, 32, 110, 101, 120, -116, 114, 97, 110, 103, 101, 32, 102, 110, 32, 123, 64, 48, 44, 48, 32, 43, 49, 99, 125, -32, 101, 110, 100, 93, 10, 32, 32, 32, 32, 105, 102, 32, 123, 36, 114, 97, 110, 103, 101, -32, 101, 113, 32, 34, 34, 32, 124, 124, 32, 91, 108, 105, 110, 100, 101, 120, 32, 91, 46, -116, 120, 116, 65, 32, 121, 118, 105, 101, 119, 93, 32, 49, 93, 32, 61, 61, 32, 49, 125, -32, 123, 10, 32, 32, 32, 32, 32, 32, 118, 105, 101, 119, 68, 105, 102, 102, 32, 102, 110, -46, 102, 105, 114, 115, 116, 10, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 32, 123, 10, -32, 32, 32, 32, 32, 32, 118, 105, 101, 119, 68, 105, 102, 102, 32, 91, 108, 105, 110, 100, -101, 120, 32, 36, 114, 97, 110, 103, 101, 32, 48, 93, 10, 32, 32, 32, 32, 125, 10, 32, -32, 125, 10, 125, 10, 10, 112, 114, 111, 99, 32, 120, 118, 105, 115, 32, 123, 99, 111, 108, -125, 32, 123, 10, 32, 32, 115, 101, 116, 32, 118, 105, 101, 119, 32, 91, 36, 99, 111, 108, -32, 120, 118, 105, 101, 119, 93, 10, 32, 32, 114, 101, 116, 117, 114, 110, 32, 91, 101, 120, -112, 114, 32, 123, 91, 108, 105, 110, 100, 101, 120, 32, 36, 118, 105, 101, 119, 32, 49, 93, -45, 91, 108, 105, 110, 100, 101, 120, 32, 36, 118, 105, 101, 119, 32, 48, 93, 125, 93, 10, -125, 10, 10, 112, 114, 111, 99, 32, 115, 99, 114, 111, 108, 108, 45, 120, 32, 123, 97, 114, -103, 115, 125, 32, 123, 10, 32, 32, 115, 101, 116, 32, 99, 32, 46, 116, 120, 116, 91, 101, -120, 112, 114, 32, 123, 91, 120, 118, 105, 115, 32, 46, 116, 120, 116, 65, 93, 32, 60, 32, -91, 120, 118, 105, 115, 32, 46, 116, 120, 116, 66, 93, 32, 63, 32, 34, 65, 34, 32, 58, -32, 34, 66, 34, 125, 93, 10, 32, 32, 101, 118, 97, 108, 32, 36, 99, 32, 120, 118, 105, -101, 119, 32, 36, 97, 114, 103, 115, 10, 125, 10, 10, 105, 110, 116, 101, 114, 112, 32, 97, -108, 105, 97, 115, 32, 123, 125, 32, 115, 99, 114, 111, 108, 108, 45, 121, 32, 123, 125, 32, -46, 116, 120, 116, 65, 32, 121, 118, 105, 101, 119, 10, 10, 112, 114, 111, 99, 32, 110, 111, -111, 112, 32, 123, 97, 114, 103, 115, 125, 32, 123, 125, 10, 10, 112, 114, 111, 99, 32, 101, -110, 97, 98, 108, 101, 83, 121, 110, 99, 32, 123, 97, 120, 105, 115, 125, 32, 123, 10, 32, -32, 117, 112, 100, 97, 116, 101, 32, 105, 100, 108, 101, 116, 97, 115, 107, 115, 10, 32, 32, -105, 110, 116, 101, 114, 112, 32, 97, 108, 105, 97, 115, 32, 123, 125, 32, 115, 121, 110, 99, -45, 36, 97, 120, 105, 115, 32, 123, 125, 10, 32, 32, 114, 101, 110, 97, 109, 101, 32, 95, -115, 121, 110, 99, 45, 36, 97, 120, 105, 115, 32, 115, 121, 110, 99, 45, 36, 97, 120, 105, -115, 10, 125, 10, 10, 112, 114, 111, 99, 32, 100, 105, 115, 97, 98, 108, 101, 83, 121, 110, -99, 32, 123, 97, 120, 105, 115, 125, 32, 123, 10, 32, 32, 114, 101, 110, 97, 109, 101, 32, -115, 121, 110, 99, 45, 36, 97, 120, 105, 115, 32, 95, 115, 121, 110, 99, 45, 36, 97, 120, -105, 115, 10, 32, 32, 105, 110, 116, 101, 114, 112, 32, 97, 108, 105, 97, 115, 32, 123, 125, -32, 115, 121, 110, 99, 45, 36, 97, 120, 105, 115, 32, 123, 125, 32, 110, 111, 111, 112, 10, -125, 10, 10, 112, 114, 111, 99, 32, 115, 121, 110, 99, 45, 120, 32, 123, 99, 111, 108, 32, -102, 105, 114, 115, 116, 32, 108, 97, 115, 116, 125, 32, 123, 10, 32, 32, 100, 105, 115, 97, -98, 108, 101, 83, 121, 110, 99, 32, 120, 10, 32, 32, 36, 99, 111, 108, 32, 120, 118, 105, -101, 119, 32, 109, 111, 118, 101, 116, 111, 32, 91, 101, 120, 112, 114, 32, 123, 36, 102, 105, -114, 115, 116, 42, 91, 120, 118, 105, 115, 32, 36, 99, 111, 108, 93, 47, 40, 36, 108, 97, -115, 116, 45, 36, 102, 105, 114, 115, 116, 41, 125, 93, 10, 32, 32, 102, 111, 114, 101, 97, -99, 104, 32, 115, 105, 100, 101, 32, 123, 65, 32, 66, 125, 32, 123, 10, 32, 32, 32, 32, -115, 101, 116, 32, 115, 98, 32, 46, 115, 98, 120, 36, 115, 105, 100, 101, 10, 32, 32, 32, -32, 115, 101, 116, 32, 120, 118, 105, 101, 119, 32, 91, 46, 116, 120, 116, 36, 115, 105, 100, -101, 32, 120, 118, 105, 101, 119, 93, 10, 32, 32, 32, 32, 105, 102, 32, 123, 91, 108, 105, -110, 100, 101, 120, 32, 36, 120, 118, 105, 101, 119, 32, 48, 93, 32, 62, 32, 48, 32, 124, -124, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 120, 118, 105, 101, 119, 32, 49, 93, 32, -60, 32, 49, 125, 32, 123, 10, 32, 32, 32, 32, 32, 32, 103, 114, 105, 100, 32, 36, 115, -98, 10, 32, 32, 32, 32, 32, 32, 101, 118, 97, 108, 32, 36, 115, 98, 32, 115, 101, 116, -32, 36, 120, 118, 105, 101, 119, 10, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 32, 123, -10, 32, 32, 32, 32, 32, 32, 103, 114, 105, 100, 32, 114, 101, 109, 111, 118, 101, 32, 36, -115, 98, 10, 32, 32, 32, 32, 125, 10, 32, 32, 125, 10, 32, 32, 101, 110, 97, 98, 108, -101, 83, 121, 110, 99, 32, 120, 10, 125, 10, 10, 112, 114, 111, 99, 32, 115, 121, 110, 99, -45, 121, 32, 123, 102, 105, 114, 115, 116, 32, 108, 97, 115, 116, 125, 32, 123, 10, 32, 32, -100, 105, 115, 97, 98, 108, 101, 83, 121, 110, 99, 32, 121, 10, 32, 32, 102, 111, 114, 101, -97, 99, 104, 32, 99, 32, 91, 99, 111, 108, 115, 93, 32, 123, 10, 32, 32, 32, 32, 36, -99, 32, 121, 118, 105, 101, 119, 32, 109, 111, 118, 101, 116, 111, 32, 36, 102, 105, 114, 115, -116, 10, 32, 32, 125, 10, 32, 32, 105, 102, 32, 123, 36, 102, 105, 114, 115, 116, 32, 62, -32, 48, 32, 124, 124, 32, 36, 108, 97, 115, 116, 32, 60, 32, 49, 125, 32, 123, 10, 32, -32, 32, 32, 103, 114, 105, 100, 32, 46, 115, 98, 121, 10, 32, 32, 32, 32, 46, 115, 98, -121, 32, 115, 101, 116, 32, 36, 102, 105, 114, 115, 116, 32, 36, 108, 97, 115, 116, 10, 32, -32, 125, 32, 101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 103, 114, 105, 100, 32, 114, -101, 109, 111, 118, 101, 32, 46, 115, 98, 121, 10, 32, 32, 125, 10, 32, 32, 101, 110, 97, -98, 108, 101, 83, 121, 110, 99, 32, 121, 10, 125, 10, 10, 119, 109, 32, 119, 105, 116, 104, -100, 114, 97, 119, 32, 46, 10, 119, 109, 32, 116, 105, 116, 108, 101, 32, 46, 32, 36, 67, -70, 71, 40, 84, 73, 84, 76, 69, 41, 10, 119, 109, 32, 105, 99, 111, 110, 110, 97, 109, -101, 32, 46, 32, 36, 67, 70, 71, 40, 84, 73, 84, 76, 69, 41, 10, 35, 32, 75, 101, -121, 115, 116, 114, 111, 107, 101, 32, 98, 105, 110, 100, 105, 110, 103, 115, 32, 102, 111, 114, -32, 111, 110, 32, 116, 104, 101, 32, 116, 111, 112, 45, 108, 101, 118, 101, 108, 32, 119, 105, -110, 100, 111, 119, 32, 102, 111, 114, 32, 110, 97, 118, 105, 103, 97, 116, 105, 111, 110, 32, -97, 110, 100, 10, 35, 32, 99, 111, 110, 116, 114, 111, 108, 32, 97, 108, 115, 111, 32, 102, -105, 114, 101, 32, 119, 104, 101, 110, 32, 116, 104, 111, 115, 101, 32, 115, 97, 109, 101, 32, -107, 101, 121, 115, 116, 114, 111, 107, 101, 115, 32, 97, 114, 101, 32, 112, 114, 101, 115, 115, -101, 100, 32, 105, 110, 32, 116, 104, 101, 10, 35, 32, 83, 101, 97, 114, 99, 104, 32, 101, -110, 116, 114, 121, 32, 98, 111, 120, 46, 32, 32, 68, 105, 115, 97, 98, 108, 101, 32, 116, -104, 101, 109, 44, 32, 116, 111, 32, 112, 114, 101, 118, 101, 110, 116, 32, 116, 104, 101, 32, -100, 105, 102, 102, 32, 115, 99, 114, 101, 101, 110, 32, 102, 114, 111, 109, 10, 35, 32, 100, -105, 115, 97, 112, 112, 101, 97, 114, 105, 110, 103, 32, 97, 98, 114, 117, 112, 116, 108, 121, -32, 97, 110, 100, 32, 117, 110, 101, 120, 112, 101, 99, 116, 101, 100, 108, 121, 32, 119, 104, -101, 110, 32, 115, 101, 97, 114, 99, 104, 105, 110, 103, 32, 102, 111, 114, 32, 34, 113, 34, -46, 10, 35, 10, 98, 105, 110, 100, 32, 46, 32, 60, 67, 111, 110, 116, 114, 111, 108, 45, -113, 62, 32, 101, 120, 105, 116, 10, 98, 105, 110, 100, 32, 46, 32, 60, 67, 111, 110, 116, -114, 111, 108, 45, 112, 62, 32, 123, 99, 97, 116, 99, 104, 32, 115, 101, 97, 114, 99, 104, -80, 114, 101, 118, 59, 32, 98, 114, 101, 97, 107, 125, 10, 98, 105, 110, 100, 32, 46, 32, -60, 67, 111, 110, 116, 114, 111, 108, 45, 110, 62, 32, 123, 99, 97, 116, 99, 104, 32, 115, -101, 97, 114, 99, 104, 78, 101, 120, 116, 59, 32, 98, 114, 101, 97, 107, 125, 10, 98, 105, -110, 100, 32, 46, 32, 60, 69, 115, 99, 97, 112, 101, 62, 60, 69, 115, 99, 97, 112, 101, -62, 32, 101, 120, 105, 116, 10, 98, 105, 110, 100, 32, 46, 32, 60, 68, 101, 115, 116, 114, -111, 121, 62, 32, 123, 97, 102, 116, 101, 114, 32, 48, 32, 101, 120, 105, 116, 125, 10, 98, -105, 110, 100, 32, 46, 32, 60, 84, 97, 98, 62, 32, 123, 99, 121, 99, 108, 101, 68, 105, -102, 102, 115, 59, 32, 98, 114, 101, 97, 107, 125, 10, 98, 105, 110, 100, 32, 46, 32, 60, -60, 80, 114, 101, 118, 87, 105, 110, 100, 111, 119, 62, 62, 32, 123, 99, 121, 99, 108, 101, -68, 105, 102, 102, 115, 32, 49, 59, 32, 98, 114, 101, 97, 107, 125, 10, 98, 105, 110, 100, -32, 46, 32, 60, 67, 111, 110, 116, 114, 111, 108, 45, 102, 62, 32, 123, 115, 101, 97, 114, -99, 104, 79, 110, 79, 102, 102, 59, 32, 98, 114, 101, 97, 107, 125, 10, 98, 105, 110, 100, -32, 46, 32, 60, 67, 111, 110, 116, 114, 111, 108, 45, 103, 62, 32, 123, 99, 97, 116, 99, -104, 32, 115, 101, 97, 114, 99, 104, 78, 101, 120, 116, 59, 32, 98, 114, 101, 97, 107, 125, -10, 98, 105, 110, 100, 32, 46, 32, 60, 82, 101, 116, 117, 114, 110, 62, 32, 123, 10, 32, -32, 101, 118, 101, 110, 116, 32, 103, 101, 110, 101, 114, 97, 116, 101, 32, 46, 98, 98, 46, -102, 105, 108, 101, 115, 32, 60, 49, 62, 10, 32, 32, 101, 118, 101, 110, 116, 32, 103, 101, -110, 101, 114, 97, 116, 101, 32, 46, 98, 98, 46, 102, 105, 108, 101, 115, 32, 60, 66, 117, -116, 116, 111, 110, 82, 101, 108, 101, 97, 115, 101, 45, 49, 62, 10, 32, 32, 98, 114, 101, -97, 107, 10, 125, 10, 102, 111, 114, 101, 97, 99, 104, 32, 123, 107, 101, 121, 32, 97, 120, -105, 115, 32, 97, 114, 103, 115, 125, 32, 123, 10, 32, 32, 85, 112, 32, 32, 32, 32, 121, -32, 123, 115, 99, 114, 111, 108, 108, 32, 45, 53, 32, 117, 110, 105, 116, 115, 125, 10, 32, -32, 107, 32, 32, 32, 32, 32, 121, 32, 123, 115, 99, 114, 111, 108, 108, 32, 45, 53, 32, -117, 110, 105, 116, 115, 125, 10, 32, 32, 68, 111, 119, 110, 32, 32, 121, 32, 123, 115, 99, -114, 111, 108, 108, 32, 53, 32, 117, 110, 105, 116, 115, 125, 10, 32, 32, 106, 32, 32, 32, -32, 32, 121, 32, 123, 115, 99, 114, 111, 108, 108, 32, 53, 32, 117, 110, 105, 116, 115, 125, -10, 32, 32, 76, 101, 102, 116, 32, 32, 120, 32, 123, 115, 99, 114, 111, 108, 108, 32, 45, -53, 32, 117, 110, 105, 116, 115, 125, 10, 32, 32, 104, 32, 32, 32, 32, 32, 120, 32, 123, -115, 99, 114, 111, 108, 108, 32, 45, 53, 32, 117, 110, 105, 116, 115, 125, 10, 32, 32, 82, -105, 103, 104, 116, 32, 120, 32, 123, 115, 99, 114, 111, 108, 108, 32, 53, 32, 117, 110, 105, -116, 115, 125, 10, 32, 32, 108, 32, 32, 32, 32, 32, 120, 32, 123, 115, 99, 114, 111, 108, -108, 32, 53, 32, 117, 110, 105, 116, 115, 125, 10, 32, 32, 80, 114, 105, 111, 114, 32, 121, -32, 123, 115, 99, 114, 111, 108, 108, 32, 45, 49, 32, 112, 97, 103, 101, 125, 10, 32, 32, -98, 32, 32, 32, 32, 32, 121, 32, 123, 115, 99, 114, 111, 108, 108, 32, 45, 49, 32, 112, -97, 103, 101, 125, 10, 32, 32, 78, 101, 120, 116, 32, 32, 121, 32, 123, 115, 99, 114, 111, -108, 108, 32, 49, 32, 112, 97, 103, 101, 125, 10, 32, 32, 115, 112, 97, 99, 101, 32, 121, -32, 123, 115, 99, 114, 111, 108, 108, 32, 49, 32, 112, 97, 103, 101, 125, 10, 32, 32, 72, -111, 109, 101, 32, 32, 121, 32, 123, 109, 111, 118, 101, 116, 111, 32, 48, 125, 10, 32, 32, -103, 32, 32, 32, 32, 32, 121, 32, 123, 109, 111, 118, 101, 116, 111, 32, 48, 125, 10, 32, -32, 69, 110, 100, 32, 32, 32, 121, 32, 123, 109, 111, 118, 101, 116, 111, 32, 49, 125, 10, -125, 32, 123, 10, 32, 32, 98, 105, 110, 100, 32, 46, 32, 60, 36, 107, 101, 121, 62, 32, -34, 115, 99, 114, 111, 108, 108, 45, 36, 97, 120, 105, 115, 32, 36, 97, 114, 103, 115, 59, -32, 98, 114, 101, 97, 107, 34, 10, 32, 32, 98, 105, 110, 100, 32, 46, 32, 60, 83, 104, -105, 102, 116, 45, 36, 107, 101, 121, 62, 32, 99, 111, 110, 116, 105, 110, 117, 101, 10, 125, -10, 10, 102, 114, 97, 109, 101, 32, 46, 98, 98, 10, 58, 58, 116, 116, 107, 58, 58, 109, -101, 110, 117, 98, 117, 116, 116, 111, 110, 32, 46, 98, 98, 46, 102, 105, 108, 101, 115, 32, -45, 116, 101, 120, 116, 32, 34, 70, 105, 108, 101, 115, 34, 10, 105, 102, 32, 123, 91, 116, -107, 32, 119, 105, 110, 100, 111, 119, 105, 110, 103, 115, 121, 115, 116, 101, 109, 93, 32, 101, -113, 32, 34, 119, 105, 110, 51, 50, 34, 125, 32, 123, 10, 32, 32, 58, 58, 116, 116, 107, -58, 58, 115, 116, 121, 108, 101, 32, 116, 104, 101, 109, 101, 32, 117, 115, 101, 32, 119, 105, -110, 110, 97, 116, 105, 118, 101, 10, 32, 32, 46, 98, 98, 46, 102, 105, 108, 101, 115, 32, -99, 111, 110, 102, 105, 103, 117, 114, 101, 32, 45, 112, 97, 100, 100, 105, 110, 103, 32, 123, -50, 48, 32, 49, 32, 49, 48, 32, 50, 125, 10, 125, 10, 116, 111, 112, 108, 101, 118, 101, -108, 32, 46, 119, 102, 105, 108, 101, 115, 10, 119, 109, 32, 119, 105, 116, 104, 100, 114, 97, -119, 32, 46, 119, 102, 105, 108, 101, 115, 10, 117, 112, 100, 97, 116, 101, 32, 105, 100, 108, -101, 116, 97, 115, 107, 115, 10, 119, 109, 32, 116, 114, 97, 110, 115, 105, 101, 110, 116, 32, -46, 119, 102, 105, 108, 101, 115, 32, 46, 10, 119, 109, 32, 111, 118, 101, 114, 114, 105, 100, -101, 114, 101, 100, 105, 114, 101, 99, 116, 32, 46, 119, 102, 105, 108, 101, 115, 32, 49, 10, -108, 105, 115, 116, 98, 111, 120, 32, 46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 45, -119, 105, 100, 116, 104, 32, 48, 32, 45, 104, 101, 105, 103, 104, 116, 32, 36, 67, 70, 71, -40, 76, 66, 95, 72, 69, 73, 71, 72, 84, 41, 32, 45, 97, 99, 116, 105, 118, 101, 115, -116, 121, 108, 101, 32, 110, 111, 110, 101, 32, 92, 10, 32, 32, 45, 121, 115, 99, 114, 111, -108, 108, 32, 123, 46, 119, 102, 105, 108, 101, 115, 46, 115, 98, 32, 115, 101, 116, 125, 10, -58, 58, 116, 116, 107, 58, 58, 115, 99, 114, 111, 108, 108, 98, 97, 114, 32, 46, 119, 102, -105, 108, 101, 115, 46, 115, 98, 32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 123, 46, 119, -102, 105, 108, 101, 115, 46, 108, 98, 32, 121, 118, 105, 101, 119, 125, 10, 103, 114, 105, 100, -32, 46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 46, 119, 102, 105, 108, 101, 115, 46, -115, 98, 32, 45, 115, 116, 105, 99, 107, 121, 32, 110, 115, 10, 98, 105, 110, 100, 32, 46, -98, 98, 46, 102, 105, 108, 101, 115, 32, 60, 49, 62, 32, 123, 10, 32, 32, 115, 101, 116, -32, 120, 32, 91, 119, 105, 110, 102, 111, 32, 114, 111, 111, 116, 120, 32, 37, 87, 93, 10, -32, 32, 115, 101, 116, 32, 121, 32, 91, 101, 120, 112, 114, 32, 123, 91, 119, 105, 110, 102, -111, 32, 114, 111, 111, 116, 121, 32, 37, 87, 93, 43, 91, 119, 105, 110, 102, 111, 32, 104, -101, 105, 103, 104, 116, 32, 37, 87, 93, 125, 93, 10, 32, 32, 119, 109, 32, 103, 101, 111, -109, 101, 116, 114, 121, 32, 46, 119, 102, 105, 108, 101, 115, 32, 43, 36, 120, 43, 36, 121, -10, 32, 32, 119, 109, 32, 100, 101, 105, 99, 111, 110, 105, 102, 121, 32, 46, 119, 102, 105, -108, 101, 115, 10, 32, 32, 102, 111, 99, 117, 115, 32, 46, 119, 102, 105, 108, 101, 115, 46, -108, 98, 10, 125, 10, 98, 105, 110, 100, 32, 46, 119, 102, 105, 108, 101, 115, 32, 60, 70, -111, 99, 117, 115, 79, 117, 116, 62, 32, 123, 119, 109, 32, 119, 105, 116, 104, 100, 114, 97, -119, 32, 46, 119, 102, 105, 108, 101, 115, 125, 10, 98, 105, 110, 100, 32, 46, 119, 102, 105, -108, 101, 115, 32, 60, 69, 115, 99, 97, 112, 101, 62, 32, 123, 102, 111, 99, 117, 115, 32, -46, 125, 10, 102, 111, 114, 101, 97, 99, 104, 32, 101, 118, 116, 32, 123, 49, 32, 82, 101, -116, 117, 114, 110, 125, 32, 123, 10, 32, 32, 98, 105, 110, 100, 32, 46, 119, 102, 105, 108, -101, 115, 46, 108, 98, 32, 60, 36, 101, 118, 116, 62, 32, 123, 10, 32, 32, 32, 32, 99, -97, 116, 99, 104, 32, 123, 10, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 105, 100, 120, -32, 91, 108, 105, 110, 100, 101, 120, 32, 91, 46, 116, 120, 116, 65, 32, 116, 97, 103, 32, -114, 97, 110, 103, 101, 115, 32, 102, 110, 93, 32, 91, 101, 120, 112, 114, 32, 123, 91, 37, -87, 32, 99, 117, 114, 115, 101, 108, 101, 99, 116, 105, 111, 110, 93, 42, 50, 125, 93, 93, -10, 32, 32, 32, 32, 32, 32, 118, 105, 101, 119, 68, 105, 102, 102, 32, 36, 105, 100, 120, -10, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 102, 111, 99, 117, 115, 32, 46, 10, 32, -32, 32, 32, 98, 114, 101, 97, 107, 10, 32, 32, 125, 10, 125, 10, 98, 105, 110, 100, 32, -46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 60, 77, 111, 116, 105, 111, 110, 62, 32, -123, 10, 32, 32, 37, 87, 32, 115, 101, 108, 101, 99, 116, 105, 111, 110, 32, 99, 108, 101, -97, 114, 32, 48, 32, 101, 110, 100, 10, 32, 32, 37, 87, 32, 115, 101, 108, 101, 99, 116, -105, 111, 110, 32, 115, 101, 116, 32, 64, 37, 120, 44, 37, 121, 10, 125, 10, 10, 102, 111, -114, 101, 97, 99, 104, 32, 123, 115, 105, 100, 101, 32, 115, 121, 110, 99, 67, 111, 108, 125, -32, 123, 65, 32, 46, 116, 120, 116, 66, 32, 66, 32, 46, 116, 120, 116, 65, 125, 32, 123, -10, 32, 32, 115, 101, 116, 32, 108, 110, 32, 46, 108, 110, 36, 115, 105, 100, 101, 10, 32, -32, 116, 101, 120, 116, 32, 36, 108, 110, 10, 32, 32, 36, 108, 110, 32, 116, 97, 103, 32, -99, 111, 110, 102, 105, 103, 32, 45, 32, 45, 106, 117, 115, 116, 105, 102, 121, 32, 114, 105, -103, 104, 116, 10, 10, 32, 32, 115, 101, 116, 32, 116, 120, 116, 32, 46, 116, 120, 116, 36, -115, 105, 100, 101, 10, 32, 32, 116, 101, 120, 116, 32, 36, 116, 120, 116, 32, 45, 119, 105, -100, 116, 104, 32, 36, 67, 70, 71, 40, 87, 73, 68, 84, 72, 41, 32, 45, 104, 101, 105, -103, 104, 116, 32, 36, 67, 70, 71, 40, 72, 69, 73, 71, 72, 84, 41, 32, 45, 119, 114, -97, 112, 32, 110, 111, 110, 101, 32, 92, 10, 32, 32, 32, 32, 45, 120, 115, 99, 114, 111, -108, 108, 32, 34, 115, 121, 110, 99, 45, 120, 32, 36, 115, 121, 110, 99, 67, 111, 108, 34, -10, 32, 32, 99, 97, 116, 99, 104, 32, 123, 36, 116, 120, 116, 32, 99, 111, 110, 102, 105, -103, 32, 45, 116, 97, 98, 115, 116, 121, 108, 101, 32, 119, 111, 114, 100, 112, 114, 111, 99, -101, 115, 115, 111, 114, 125, 32, 59, 35, 32, 82, 101, 113, 117, 105, 114, 101, 100, 32, 102, -111, 114, 32, 84, 107, 62, 61, 56, 46, 53, 10, 32, 32, 102, 111, 114, 101, 97, 99, 104, -32, 116, 97, 103, 32, 123, 97, 100, 100, 32, 114, 109, 32, 99, 104, 110, 103, 125, 32, 123, -10, 32, 32, 32, 32, 36, 116, 120, 116, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 103, -32, 36, 116, 97, 103, 32, 45, 98, 97, 99, 107, 103, 114, 111, 117, 110, 100, 32, 36, 67, -70, 71, 40, 91, 115, 116, 114, 105, 110, 103, 32, 116, 111, 117, 112, 112, 101, 114, 32, 36, -116, 97, 103, 93, 95, 66, 71, 41, 10, 32, 32, 32, 32, 36, 116, 120, 116, 32, 116, 97, -103, 32, 108, 111, 119, 101, 114, 32, 36, 116, 97, 103, 10, 32, 32, 125, 10, 32, 32, 36, -116, 120, 116, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 102, 110, 32, 45, 98, -97, 99, 107, 103, 114, 111, 117, 110, 100, 32, 36, 67, 70, 71, 40, 70, 78, 95, 66, 71, -41, 32, 45, 102, 111, 114, 101, 103, 114, 111, 117, 110, 100, 32, 36, 67, 70, 71, 40, 70, -78, 95, 70, 71, 41, 32, 92, 10, 32, 32, 32, 32, 45, 106, 117, 115, 116, 105, 102, 121, -32, 99, 101, 110, 116, 101, 114, 10, 32, 32, 36, 116, 120, 116, 32, 116, 97, 103, 32, 99, -111, 110, 102, 105, 103, 32, 101, 114, 114, 32, 45, 102, 111, 114, 101, 103, 114, 111, 117, 110, -100, 32, 36, 67, 70, 71, 40, 69, 82, 82, 95, 70, 71, 41, 10, 125, 10, 116, 101, 120, -116, 32, 46, 109, 107, 114, 10, 10, 102, 111, 114, 101, 97, 99, 104, 32, 99, 32, 91, 99, -111, 108, 115, 93, 32, 123, 10, 32, 32, 115, 101, 116, 32, 107, 101, 121, 80, 114, 101, 102, -105, 120, 32, 91, 115, 116, 114, 105, 110, 103, 32, 116, 111, 117, 112, 112, 101, 114, 32, 91, -99, 111, 108, 84, 121, 112, 101, 32, 36, 99, 93, 93, 95, 67, 79, 76, 95, 10, 32, 32, -105, 102, 32, 123, 91, 116, 107, 32, 119, 105, 110, 100, 111, 119, 105, 110, 103, 115, 121, 115, -116, 101, 109, 93, 32, 101, 113, 32, 34, 119, 105, 110, 51, 50, 34, 125, 32, 123, 36, 99, -32, 99, 111, 110, 102, 105, 103, 32, 45, 102, 111, 110, 116, 32, 123, 99, 111, 117, 114, 105, -101, 114, 32, 57, 125, 125, 10, 32, 32, 36, 99, 32, 99, 111, 110, 102, 105, 103, 32, 45, -98, 103, 32, 36, 67, 70, 71, 40, 36, 123, 107, 101, 121, 80, 114, 101, 102, 105, 120, 125, -66, 71, 41, 32, 45, 102, 103, 32, 36, 67, 70, 71, 40, 36, 123, 107, 101, 121, 80, 114, -101, 102, 105, 120, 125, 70, 71, 41, 32, 45, 98, 111, 114, 100, 101, 114, 119, 105, 100, 116, -104, 32, 48, 32, 92, 10, 32, 32, 32, 32, 45, 112, 97, 100, 120, 32, 36, 67, 70, 71, -40, 80, 65, 68, 88, 41, 32, 45, 121, 115, 99, 114, 111, 108, 108, 32, 115, 121, 110, 99, -45, 121, 10, 32, 32, 36, 99, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 104, -114, 108, 110, 32, 45, 115, 112, 97, 99, 105, 110, 103, 49, 32, 36, 67, 70, 71, 40, 72, -82, 95, 80, 65, 68, 95, 84, 79, 80, 41, 32, 45, 115, 112, 97, 99, 105, 110, 103, 51, -32, 36, 67, 70, 71, 40, 72, 82, 95, 80, 65, 68, 95, 66, 84, 77, 41, 32, 92, 10, -32, 32, 32, 32, 32, 45, 102, 111, 114, 101, 103, 114, 111, 117, 110, 100, 32, 36, 67, 70, -71, 40, 72, 82, 95, 70, 71, 41, 32, 45, 106, 117, 115, 116, 105, 102, 121, 32, 114, 105, -103, 104, 116, 10, 32, 32, 36, 99, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, -104, 114, 116, 120, 116, 32, 32, 45, 115, 112, 97, 99, 105, 110, 103, 49, 32, 36, 67, 70, -71, 40, 72, 82, 95, 80, 65, 68, 95, 84, 79, 80, 41, 32, 45, 115, 112, 97, 99, 105, -110, 103, 51, 32, 36, 67, 70, 71, 40, 72, 82, 95, 80, 65, 68, 95, 66, 84, 77, 41, -32, 92, 10, 32, 32, 32, 32, 32, 45, 102, 111, 114, 101, 103, 114, 111, 117, 110, 100, 32, -36, 67, 70, 71, 40, 72, 82, 95, 70, 71, 41, 32, 45, 106, 117, 115, 116, 105, 102, 121, -32, 99, 101, 110, 116, 101, 114, 10, 32, 32, 36, 99, 32, 116, 97, 103, 32, 99, 111, 110, -102, 105, 103, 32, 102, 110, 32, 45, 115, 112, 97, 99, 105, 110, 103, 49, 32, 36, 67, 70, -71, 40, 70, 78, 95, 80, 65, 68, 41, 32, 45, 115, 112, 97, 99, 105, 110, 103, 51, 32, -36, 67, 70, 71, 40, 70, 78, 95, 80, 65, 68, 41, 10, 32, 32, 98, 105, 110, 100, 116, -97, 103, 115, 32, 36, 99, 32, 34, 46, 32, 36, 99, 32, 84, 101, 120, 116, 32, 97, 108, -108, 34, 10, 32, 32, 98, 105, 110, 100, 32, 36, 99, 32, 60, 49, 62, 32, 123, 102, 111, -99, 117, 115, 32, 37, 87, 125, 10, 125, 10, 10, 58, 58, 116, 116, 107, 58, 58, 115, 99, -114, 111, 108, 108, 98, 97, 114, 32, 46, 115, 98, 121, 32, 45, 99, 111, 109, 109, 97, 110, -100, 32, 123, 46, 116, 120, 116, 65, 32, 121, 118, 105, 101, 119, 125, 32, 45, 111, 114, 105, -101, 110, 116, 32, 118, 101, 114, 116, 105, 99, 97, 108, 10, 58, 58, 116, 116, 107, 58, 58, -115, 99, 114, 111, 108, 108, 98, 97, 114, 32, 46, 115, 98, 120, 65, 32, 45, 99, 111, 109, -109, 97, 110, 100, 32, 123, 46, 116, 120, 116, 65, 32, 120, 118, 105, 101, 119, 125, 32, 45, -111, 114, 105, 101, 110, 116, 32, 104, 111, 114, 105, 122, 111, 110, 116, 97, 108, 10, 58, 58, -116, 116, 107, 58, 58, 115, 99, 114, 111, 108, 108, 98, 97, 114, 32, 46, 115, 98, 120, 66, -32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 123, 46, 116, 120, 116, 66, 32, 120, 118, 105, -101, 119, 125, 32, 45, 111, 114, 105, 101, 110, 116, 32, 104, 111, 114, 105, 122, 111, 110, 116, -97, 108, 10, 102, 114, 97, 109, 101, 32, 46, 115, 112, 97, 99, 101, 114, 10, 10, 105, 102, -32, 123, 91, 114, 101, 97, 100, 68, 105, 102, 102, 115, 32, 36, 102, 111, 115, 115, 105, 108, -99, 109, 100, 93, 32, 61, 61, 32, 48, 125, 32, 123, 10, 32, 32, 116, 107, 95, 109, 101, -115, 115, 97, 103, 101, 66, 111, 120, 32, 45, 116, 121, 112, 101, 32, 111, 107, 32, 45, 116, -105, 116, 108, 101, 32, 36, 67, 70, 71, 40, 84, 73, 84, 76, 69, 41, 32, 45, 109, 101, -115, 115, 97, 103, 101, 32, 34, 78, 111, 32, 99, 104, 97, 110, 103, 101, 115, 34, 10, 32, -32, 101, 120, 105, 116, 10, 125, 10, 117, 112, 100, 97, 116, 101, 32, 105, 100, 108, 101, 116, -97, 115, 107, 115, 10, 10, 112, 114, 111, 99, 32, 115, 97, 118, 101, 68, 105, 102, 102, 32, -123, 125, 32, 123, 10, 32, 32, 115, 101, 116, 32, 102, 110, 32, 91, 116, 107, 95, 103, 101, -116, 83, 97, 118, 101, 70, 105, 108, 101, 93, 10, 32, 32, 105, 102, 32, 123, 36, 102, 110, -61, 61, 34, 34, 125, 32, 114, 101, 116, 117, 114, 110, 10, 32, 32, 115, 101, 116, 32, 111, -117, 116, 32, 91, 111, 112, 101, 110, 32, 36, 102, 110, 32, 119, 98, 93, 10, 32, 32, 112, -117, 116, 115, 32, 36, 111, 117, 116, 32, 34, 35, 33, 47, 117, 115, 114, 47, 98, 105, 110, -47, 116, 99, 108, 115, 104, 92, 110, 35, 92, 110, 35, 32, 82, 117, 110, 32, 116, 104, 105, -115, 32, 115, 99, 114, 105, 112, 116, 32, 117, 115, 105, 110, 103, 32, 39, 116, 99, 108, 115, -104, 39, 32, 111, 114, 32, 39, 119, 105, 115, 104, 39, 34, 10, 32, 32, 112, 117, 116, 115, -32, 36, 111, 117, 116, 32, 34, 35, 32, 116, 111, 32, 115, 101, 101, 32, 116, 104, 101, 32, -103, 114, 97, 112, 104, 105, 99, 97, 108, 32, 100, 105, 102, 102, 46, 92, 110, 35, 34, 10, -32, 32, 112, 117, 116, 115, 32, 36, 111, 117, 116, 32, 34, 115, 101, 116, 32, 102, 111, 115, -115, 105, 108, 99, 109, 100, 32, 123, 125, 34, 10, 32, 32, 112, 117, 116, 115, 32, 36, 111, -117, 116, 32, 34, 115, 101, 116, 32, 112, 114, 111, 103, 32, 91, 108, 105, 115, 116, 32, 36, -58, 58, 112, 114, 111, 103, 93, 34, 10, 32, 32, 112, 117, 116, 115, 32, 36, 111, 117, 116, -32, 34, 115, 101, 116, 32, 100, 105, 102, 102, 116, 120, 116, 32, 92, 49, 55, 51, 34, 10, -32, 32, 102, 111, 114, 101, 97, 99, 104, 32, 101, 32, 36, 58, 58, 100, 105, 102, 102, 116, -120, 116, 32, 123, 112, 117, 116, 115, 32, 36, 111, 117, 116, 32, 91, 108, 105, 115, 116, 32, -36, 101, 93, 125, 10, 32, 32, 112, 117, 116, 115, 32, 36, 111, 117, 116, 32, 34, 92, 49, -55, 53, 34, 10, 32, 32, 112, 117, 116, 115, 32, 36, 111, 117, 116, 32, 34, 101, 118, 97, -108, 32, 92, 36, 112, 114, 111, 103, 34, 10, 32, 32, 99, 108, 111, 115, 101, 32, 36, 111, -117, 116, 10, 125, 10, 112, 114, 111, 99, 32, 105, 110, 118, 101, 114, 116, 68, 105, 102, 102, -32, 123, 125, 32, 123, 10, 32, 32, 103, 108, 111, 98, 97, 108, 32, 67, 70, 71, 10, 32, -32, 97, 114, 114, 97, 121, 32, 115, 101, 116, 32, 120, 32, 91, 103, 114, 105, 100, 32, 105, -110, 102, 111, 32, 46, 116, 120, 116, 65, 93, 10, 32, 32, 105, 102, 32, 123, 36, 120, 40, -45, 99, 111, 108, 117, 109, 110, 41, 61, 61, 49, 125, 32, 123, 10, 32, 32, 32, 32, 103, -114, 105, 100, 32, 99, 111, 110, 102, 105, 103, 32, 46, 108, 110, 66, 32, 45, 99, 111, 108, -117, 109, 110, 32, 48, 10, 32, 32, 32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, 105, -103, 32, 46, 116, 120, 116, 66, 32, 45, 99, 111, 108, 117, 109, 110, 32, 49, 10, 32, 32, -32, 32, 46, 116, 120, 116, 66, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 97, -100, 100, 32, 45, 98, 97, 99, 107, 103, 114, 111, 117, 110, 100, 32, 36, 67, 70, 71, 40, -82, 77, 95, 66, 71, 41, 10, 32, 32, 32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, -105, 103, 32, 46, 108, 110, 65, 32, 45, 99, 111, 108, 117, 109, 110, 32, 51, 10, 32, 32, -32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, 105, 103, 32, 46, 116, 120, 116, 65, 32, -45, 99, 111, 108, 117, 109, 110, 32, 52, 10, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, -116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 114, 109, 32, 45, 98, 97, 99, 107, 103, -114, 111, 117, 110, 100, 32, 36, 67, 70, 71, 40, 65, 68, 68, 95, 66, 71, 41, 10, 32, -32, 32, 32, 46, 98, 98, 46, 105, 110, 118, 101, 114, 116, 32, 99, 111, 110, 102, 105, 103, -32, 45, 116, 101, 120, 116, 32, 85, 110, 105, 110, 118, 101, 114, 116, 10, 32, 32, 125, 32, -101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, -105, 103, 32, 46, 108, 110, 65, 32, 45, 99, 111, 108, 117, 109, 110, 32, 48, 10, 32, 32, -32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, 105, 103, 32, 46, 116, 120, 116, 65, 32, -45, 99, 111, 108, 117, 109, 110, 32, 49, 10, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, -116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 114, 109, 32, 45, 98, 97, 99, 107, 103, -114, 111, 117, 110, 100, 32, 36, 67, 70, 71, 40, 82, 77, 95, 66, 71, 41, 10, 32, 32, -32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, 105, 103, 32, 46, 108, 110, 66, 32, 45, -99, 111, 108, 117, 109, 110, 32, 51, 10, 32, 32, 32, 32, 103, 114, 105, 100, 32, 99, 111, -110, 102, 105, 103, 32, 46, 116, 120, 116, 66, 32, 45, 99, 111, 108, 117, 109, 110, 32, 52, -10, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, -103, 32, 97, 100, 100, 32, 45, 98, 97, 99, 107, 103, 114, 111, 117, 110, 100, 32, 36, 67, -70, 71, 40, 65, 68, 68, 95, 66, 71, 41, 10, 32, 32, 32, 32, 46, 98, 98, 46, 105, -110, 118, 101, 114, 116, 32, 99, 111, 110, 102, 105, 103, 32, 45, 116, 101, 120, 116, 32, 73, -110, 118, 101, 114, 116, 10, 32, 32, 125, 10, 32, 32, 46, 109, 107, 114, 32, 99, 111, 110, -102, 105, 103, 32, 45, 115, 116, 97, 116, 101, 32, 110, 111, 114, 109, 97, 108, 10, 32, 32, -115, 101, 116, 32, 99, 108, 116, 32, 91, 46, 109, 107, 114, 32, 115, 101, 97, 114, 99, 104, -32, 45, 97, 108, 108, 32, 60, 32, 49, 46, 48, 32, 101, 110, 100, 93, 10, 32, 32, 115, -101, 116, 32, 99, 103, 116, 32, 91, 46, 109, 107, 114, 32, 115, 101, 97, 114, 99, 104, 32, -45, 97, 108, 108, 32, 62, 32, 49, 46, 48, 32, 101, 110, 100, 93, 10, 32, 32, 102, 111, -114, 101, 97, 99, 104, 32, 99, 32, 36, 99, 108, 116, 32, 123, 46, 109, 107, 114, 32, 114, -101, 112, 108, 97, 99, 101, 32, 36, 99, 32, 34, 36, 99, 32, 43, 49, 32, 99, 104, 97, -114, 115, 34, 32, 62, 125, 10, 32, 32, 102, 111, 114, 101, 97, 99, 104, 32, 99, 32, 36, -99, 103, 116, 32, 123, 46, 109, 107, 114, 32, 114, 101, 112, 108, 97, 99, 101, 32, 36, 99, -32, 34, 36, 99, 32, 43, 49, 32, 99, 104, 97, 114, 115, 34, 32, 60, 125, 10, 32, 32, -46, 109, 107, 114, 32, 99, 111, 110, 102, 105, 103, 32, 45, 115, 116, 97, 116, 101, 32, 100, -105, 115, 97, 98, 108, 101, 100, 10, 125, 10, 112, 114, 111, 99, 32, 115, 101, 97, 114, 99, -104, 79, 110, 79, 102, 102, 32, 123, 125, 32, 123, 10, 32, 32, 105, 102, 32, 123, 91, 105, -110, 102, 111, 32, 101, 120, 105, 115, 116, 115, 32, 58, 58, 115, 101, 97, 114, 99, 104, 93, -125, 32, 123, 10, 32, 32, 32, 32, 117, 110, 115, 101, 116, 32, 58, 58, 115, 101, 97, 114, -99, 104, 10, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 116, 97, 103, 32, 114, 101, 109, -111, 118, 101, 32, 115, 101, 97, 114, 99, 104, 32, 49, 46, 48, 32, 101, 110, 100, 10, 32, -32, 32, 32, 46, 116, 120, 116, 66, 32, 116, 97, 103, 32, 114, 101, 109, 111, 118, 101, 32, -115, 101, 97, 114, 99, 104, 32, 49, 46, 48, 32, 101, 110, 100, 10, 32, 32, 32, 32, 112, -97, 99, 107, 32, 102, 111, 114, 103, 101, 116, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, -101, 10, 32, 32, 32, 32, 102, 111, 99, 117, 115, 32, 46, 10, 32, 32, 125, 32, 101, 108, -115, 101, 32, 123, 10, 32, 32, 32, 32, 115, 101, 116, 32, 58, 58, 115, 101, 97, 114, 99, -104, 32, 46, 116, 120, 116, 65, 10, 32, 32, 32, 32, 105, 102, 32, 123, 33, 91, 119, 105, -110, 102, 111, 32, 101, 120, 105, 115, 116, 115, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, -101, 93, 125, 32, 123, 10, 32, 32, 32, 32, 32, 32, 102, 114, 97, 109, 101, 32, 46, 98, -98, 46, 115, 102, 114, 97, 109, 101, 10, 32, 32, 32, 32, 32, 32, 58, 58, 116, 116, 107, -58, 58, 101, 110, 116, 114, 121, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 101, -32, 45, 119, 105, 100, 116, 104, 32, 49, 48, 10, 32, 32, 32, 32, 32, 32, 112, 97, 99, -107, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 101, 32, 45, 115, 105, 100, 101, -32, 108, 101, 102, 116, 32, 45, 102, 105, 108, 108, 32, 121, 32, 45, 101, 120, 112, 97, 110, -100, 32, 49, 10, 32, 32, 32, 32, 32, 32, 98, 105, 110, 100, 32, 46, 98, 98, 46, 115, -102, 114, 97, 109, 101, 46, 101, 32, 60, 82, 101, 116, 117, 114, 110, 62, 32, 123, 115, 101, -97, 114, 99, 104, 78, 101, 120, 116, 59, 32, 98, 114, 101, 97, 107, 125, 10, 32, 32, 32, -32, 32, 32, 58, 58, 116, 116, 107, 58, 58, 98, 117, 116, 116, 111, 110, 32, 46, 98, 98, -46, 115, 102, 114, 97, 109, 101, 46, 110, 120, 32, 45, 116, 101, 120, 116, 32, 92, 117, 50, -49, 57, 51, 32, 45, 119, 105, 100, 116, 104, 32, 49, 32, 45, 99, 111, 109, 109, 97, 110, -100, 32, 115, 101, 97, 114, 99, 104, 78, 101, 120, 116, 10, 32, 32, 32, 32, 32, 32, 58, -58, 116, 116, 107, 58, 58, 98, 117, 116, 116, 111, 110, 32, 46, 98, 98, 46, 115, 102, 114, -97, 109, 101, 46, 112, 118, 32, 45, 116, 101, 120, 116, 32, 92, 117, 50, 49, 57, 49, 32, -45, 119, 105, 100, 116, 104, 32, 49, 32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 115, 101, -97, 114, 99, 104, 80, 114, 101, 118, 10, 32, 32, 32, 32, 32, 32, 116, 107, 95, 111, 112, -116, 105, 111, 110, 77, 101, 110, 117, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, -116, 121, 112, 32, 58, 58, 115, 101, 97, 114, 99, 104, 95, 116, 121, 112, 101, 32, 92, 10, -32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 69, 120, 97, 99, 116, 32, 123, 78, 111, -32, 67, 97, 115, 101, 125, 32, 123, 82, 101, 103, 69, 120, 112, 125, 32, 123, 87, 104, 111, -108, 101, 32, 87, 111, 114, 100, 125, 10, 32, 32, 32, 32, 32, 32, 46, 98, 98, 46, 115, -102, 114, 97, 109, 101, 46, 116, 121, 112, 32, 99, 111, 110, 102, 105, 103, 32, 45, 119, 105, -100, 116, 104, 32, 49, 48, 10, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 58, 58, 115, -101, 97, 114, 99, 104, 95, 116, 121, 112, 101, 32, 69, 120, 97, 99, 116, 10, 32, 32, 32, -32, 32, 32, 112, 97, 99, 107, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 110, -120, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 112, 118, 32, 46, 98, 98, 46, -115, 102, 114, 97, 109, 101, 46, 116, 121, 112, 32, 45, 115, 105, 100, 101, 32, 108, 101, 102, -116, 10, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 112, 97, 99, 107, 32, 46, 98, 98, -46, 115, 102, 114, 97, 109, 101, 32, 45, 115, 105, 100, 101, 32, 108, 101, 102, 116, 10, 32, -32, 32, 32, 97, 102, 116, 101, 114, 32, 105, 100, 108, 101, 32, 123, 102, 111, 99, 117, 115, -32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 101, 125, 10, 32, 32, 125, 10, 125, -10, 112, 114, 111, 99, 32, 115, 101, 97, 114, 99, 104, 78, 101, 120, 116, 32, 123, 125, 32, -123, 115, 101, 97, 114, 99, 104, 83, 116, 101, 112, 32, 45, 102, 111, 114, 119, 97, 114, 100, -115, 32, 43, 49, 32, 49, 46, 48, 32, 101, 110, 100, 125, 10, 112, 114, 111, 99, 32, 115, -101, 97, 114, 99, 104, 80, 114, 101, 118, 32, 123, 125, 32, 123, 115, 101, 97, 114, 99, 104, -83, 116, 101, 112, 32, 45, 98, 97, 99, 107, 119, 97, 114, 100, 115, 32, 45, 49, 32, 101, -110, 100, 32, 49, 46, 48, 125, 10, 112, 114, 111, 99, 32, 115, 101, 97, 114, 99, 104, 83, -116, 101, 112, 32, 123, 100, 105, 114, 101, 99, 116, 105, 111, 110, 32, 105, 110, 99, 114, 32, -115, 116, 97, 114, 116, 32, 115, 116, 111, 112, 125, 32, 123, 10, 32, 32, 115, 101, 116, 32, -112, 97, 116, 116, 101, 114, 110, 32, 91, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, -101, 32, 103, 101, 116, 93, 10, 32, 32, 105, 102, 32, 123, 36, 112, 97, 116, 116, 101, 114, -110, 61, 61, 34, 34, 125, 32, 114, 101, 116, 117, 114, 110, 10, 32, 32, 115, 101, 116, 32, -99, 111, 117, 110, 116, 32, 48, 10, 32, 32, 115, 101, 116, 32, 119, 32, 36, 58, 58, 115, -101, 97, 114, 99, 104, 10, 32, 32, 105, 102, 32, 123, 34, 36, 119, 34, 61, 61, 34, 46, -116, 120, 116, 65, 34, 125, 32, 123, 115, 101, 116, 32, 111, 116, 104, 101, 114, 32, 46, 116, -120, 116, 66, 125, 32, 123, 115, 101, 116, 32, 111, 116, 104, 101, 114, 32, 46, 116, 120, 116, -65, 125, 10, 32, 32, 105, 102, 32, 123, 91, 108, 115, 101, 97, 114, 99, 104, 32, 91, 36, -119, 32, 109, 97, 114, 107, 32, 110, 97, 109, 101, 115, 93, 32, 115, 101, 97, 114, 99, 104, -93, 60, 48, 125, 32, 123, 10, 32, 32, 32, 32, 36, 119, 32, 109, 97, 114, 107, 32, 115, -101, 116, 32, 115, 101, 97, 114, 99, 104, 32, 36, 115, 116, 97, 114, 116, 10, 32, 32, 125, -10, 32, 32, 115, 119, 105, 116, 99, 104, 32, 36, 58, 58, 115, 101, 97, 114, 99, 104, 95, -116, 121, 112, 101, 32, 123, 10, 32, 32, 32, 32, 69, 120, 97, 99, 116, 32, 32, 32, 32, -32, 32, 32, 32, 123, 115, 101, 116, 32, 115, 116, 32, 45, 101, 120, 97, 99, 116, 125, 10, -32, 32, 32, 32, 123, 78, 111, 32, 67, 97, 115, 101, 125, 32, 32, 32, 32, 123, 115, 101, -116, 32, 115, 116, 32, 45, 110, 111, 99, 97, 115, 101, 125, 10, 32, 32, 32, 32, 123, 82, -101, 103, 69, 120, 112, 125, 32, 32, 32, 32, 32, 123, 115, 101, 116, 32, 115, 116, 32, 45, -114, 101, 103, 101, 120, 112, 125, 10, 32, 32, 32, 32, 123, 87, 104, 111, 108, 101, 32, 87, -111, 114, 100, 125, 32, 123, 115, 101, 116, 32, 115, 116, 32, 45, 114, 101, 103, 101, 120, 112, -59, 32, 115, 101, 116, 32, 112, 97, 116, 116, 101, 114, 110, 32, 92, 92, 121, 36, 112, 97, -116, 116, 101, 114, 110, 92, 92, 121, 125, 10, 32, 32, 125, 10, 32, 32, 115, 101, 116, 32, -105, 100, 120, 32, 91, 36, 119, 32, 115, 101, 97, 114, 99, 104, 32, 45, 99, 111, 117, 110, -116, 32, 99, 111, 117, 110, 116, 32, 36, 100, 105, 114, 101, 99, 116, 105, 111, 110, 32, 36, -115, 116, 32, 45, 45, 32, 92, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, -32, 32, 36, 112, 97, 116, 116, 101, 114, 110, 32, 34, 115, 101, 97, 114, 99, 104, 32, 36, -105, 110, 99, 114, 32, 99, 104, 97, 114, 115, 34, 32, 36, 115, 116, 111, 112, 93, 10, 32, -32, 105, 102, 32, 123, 34, 36, 105, 100, 120, 34, 61, 61, 34, 34, 125, 32, 123, 10, 32, -32, 32, 32, 115, 101, 116, 32, 105, 100, 120, 32, 91, 36, 111, 116, 104, 101, 114, 32, 115, -101, 97, 114, 99, 104, 32, 45, 99, 111, 117, 110, 116, 32, 99, 111, 117, 110, 116, 32, 36, -100, 105, 114, 101, 99, 116, 105, 111, 110, 32, 36, 115, 116, 32, 45, 45, 32, 36, 112, 97, -116, 116, 101, 114, 110, 32, 36, 115, 116, 97, 114, 116, 32, 36, 115, 116, 111, 112, 93, 10, -32, 32, 32, 32, 105, 102, 32, 123, 34, 36, 105, 100, 120, 34, 33, 61, 34, 34, 125, 32, -123, 10, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 116, 104, 105, 115, 32, 36, 119, 10, -32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 119, 32, 36, 111, 116, 104, 101, 114, 10, 32, -32, 32, 32, 32, 32, 115, 101, 116, 32, 111, 116, 104, 101, 114, 32, 36, 116, 104, 105, 115, -10, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 32, 32, -115, 101, 116, 32, 105, 100, 120, 32, 91, 36, 119, 32, 115, 101, 97, 114, 99, 104, 32, 45, -99, 111, 117, 110, 116, 32, 99, 111, 117, 110, 116, 32, 36, 100, 105, 114, 101, 99, 116, 105, -111, 110, 32, 36, 115, 116, 32, 45, 45, 32, 36, 112, 97, 116, 116, 101, 114, 110, 32, 36, -115, 116, 97, 114, 116, 32, 36, 115, 116, 111, 112, 93, 10, 32, 32, 32, 32, 125, 10, 32, -32, 125, 10, 32, 32, 36, 119, 32, 116, 97, 103, 32, 114, 101, 109, 111, 118, 101, 32, 115, -101, 97, 114, 99, 104, 32, 49, 46, 48, 32, 101, 110, 100, 10, 32, 32, 36, 119, 32, 109, -97, 114, 107, 32, 117, 110, 115, 101, 116, 32, 115, 101, 97, 114, 99, 104, 10, 32, 32, 36, -111, 116, 104, 101, 114, 32, 116, 97, 103, 32, 114, 101, 109, 111, 118, 101, 32, 115, 101, 97, -114, 99, 104, 32, 49, 46, 48, 32, 101, 110, 100, 10, 32, 32, 36, 111, 116, 104, 101, 114, -32, 109, 97, 114, 107, 32, 117, 110, 115, 101, 116, 32, 115, 101, 97, 114, 99, 104, 10, 32, -32, 105, 102, 32, 123, 34, 36, 105, 100, 120, 34, 33, 61, 34, 34, 125, 32, 123, 10, 32, -32, 32, 32, 36, 119, 32, 109, 97, 114, 107, 32, 115, 101, 116, 32, 115, 101, 97, 114, 99, -104, 32, 36, 105, 100, 120, 10, 32, 32, 32, 32, 36, 119, 32, 121, 118, 105, 101, 119, 32, -45, 112, 105, 99, 107, 112, 108, 97, 99, 101, 32, 36, 105, 100, 120, 10, 32, 32, 32, 32, -36, 119, 32, 116, 97, 103, 32, 97, 100, 100, 32, 115, 101, 97, 114, 99, 104, 32, 115, 101, -97, 114, 99, 104, 32, 34, 36, 105, 100, 120, 32, 43, 36, 99, 111, 117, 110, 116, 32, 99, -104, 97, 114, 115, 34, 10, 32, 32, 32, 32, 36, 119, 32, 116, 97, 103, 32, 99, 111, 110, -102, 105, 103, 32, 115, 101, 97, 114, 99, 104, 32, 45, 98, 97, 99, 107, 103, 114, 111, 117, -110, 100, 32, 123, 35, 102, 99, 99, 48, 48, 48, 125, 10, 32, 32, 125, 10, 32, 32, 115, -101, 116, 32, 58, 58, 115, 101, 97, 114, 99, 104, 32, 36, 119, 10, 125, 10, 58, 58, 116, -116, 107, 58, 58, 98, 117, 116, 116, 111, 110, 32, 46, 98, 98, 46, 113, 117, 105, 116, 32, -45, 116, 101, 120, 116, 32, 123, 81, 117, 105, 116, 125, 32, 45, 99, 111, 109, 109, 97, 110, -100, 32, 101, 120, 105, 116, 10, 58, 58, 116, 116, 107, 58, 58, 98, 117, 116, 116, 111, 110, -32, 46, 98, 98, 46, 105, 110, 118, 101, 114, 116, 32, 45, 116, 101, 120, 116, 32, 123, 73, -110, 118, 101, 114, 116, 125, 32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 105, 110, 118, 101, -114, 116, 68, 105, 102, 102, 10, 58, 58, 116, 116, 107, 58, 58, 98, 117, 116, 116, 111, 110, -32, 46, 98, 98, 46, 115, 97, 118, 101, 32, 45, 116, 101, 120, 116, 32, 123, 83, 97, 118, -101, 32, 65, 115, 46, 46, 46, 125, 32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 115, 97, -118, 101, 68, 105, 102, 102, 10, 58, 58, 116, 116, 107, 58, 58, 98, 117, 116, 116, 111, 110, -32, 46, 98, 98, 46, 115, 101, 97, 114, 99, 104, 32, 45, 116, 101, 120, 116, 32, 123, 83, -101, 97, 114, 99, 104, 125, 32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 115, 101, 97, 114, -99, 104, 79, 110, 79, 102, 102, 10, 112, 97, 99, 107, 32, 46, 98, 98, 46, 113, 117, 105, -116, 32, 46, 98, 98, 46, 105, 110, 118, 101, 114, 116, 32, 45, 115, 105, 100, 101, 32, 108, -101, 102, 116, 10, 105, 102, 32, 123, 36, 102, 111, 115, 115, 105, 108, 99, 109, 100, 33, 61, -34, 34, 125, 32, 123, 112, 97, 99, 107, 32, 46, 98, 98, 46, 115, 97, 118, 101, 32, 45, -115, 105, 100, 101, 32, 108, 101, 102, 116, 125, 10, 112, 97, 99, 107, 32, 46, 98, 98, 46, -102, 105, 108, 101, 115, 32, 46, 98, 98, 46, 115, 101, 97, 114, 99, 104, 32, 45, 115, 105, -100, 101, 32, 108, 101, 102, 116, 10, 103, 114, 105, 100, 32, 114, 111, 119, 99, 111, 110, 102, -105, 103, 117, 114, 101, 32, 46, 32, 49, 32, 45, 119, 101, 105, 103, 104, 116, 32, 49, 10, -103, 114, 105, 100, 32, 99, 111, 108, 117, 109, 110, 99, 111, 110, 102, 105, 103, 117, 114, 101, -32, 46, 32, 49, 32, 45, 119, 101, 105, 103, 104, 116, 32, 49, 10, 103, 114, 105, 100, 32, -99, 111, 108, 117, 109, 110, 99, 111, 110, 102, 105, 103, 117, 114, 101, 32, 46, 32, 52, 32, -45, 119, 101, 105, 103, 104, 116, 32, 49, 10, 103, 114, 105, 100, 32, 46, 98, 98, 32, 45, -114, 111, 119, 32, 48, 32, 45, 99, 111, 108, 117, 109, 110, 115, 112, 97, 110, 32, 54, 10, -101, 118, 97, 108, 32, 103, 114, 105, 100, 32, 91, 99, 111, 108, 115, 93, 32, 45, 114, 111, -119, 32, 49, 32, 45, 115, 116, 105, 99, 107, 121, 32, 110, 115, 101, 119, 10, 103, 114, 105, -100, 32, 46, 115, 98, 121, 32, 45, 114, 111, 119, 32, 49, 32, 45, 99, 111, 108, 117, 109, -110, 32, 53, 32, 45, 115, 116, 105, 99, 107, 121, 32, 110, 115, 10, 103, 114, 105, 100, 32, -46, 115, 98, 120, 65, 32, 45, 114, 111, 119, 32, 50, 32, 45, 99, 111, 108, 117, 109, 110, -115, 112, 97, 110, 32, 50, 32, 45, 115, 116, 105, 99, 107, 121, 32, 101, 119, 10, 103, 114, -105, 100, 32, 46, 115, 112, 97, 99, 101, 114, 32, 45, 114, 111, 119, 32, 50, 32, 45, 99, -111, 108, 117, 109, 110, 32, 50, 10, 103, 114, 105, 100, 32, 46, 115, 98, 120, 66, 32, 45, -114, 111, 119, 32, 50, 32, 45, 99, 111, 108, 117, 109, 110, 32, 51, 32, 45, 99, 111, 108, -117, 109, 110, 115, 112, 97, 110, 32, 50, 32, 45, 115, 116, 105, 99, 107, 121, 32, 101, 119, -10, 10, 46, 115, 112, 97, 99, 101, 114, 32, 99, 111, 110, 102, 105, 103, 32, 45, 104, 101, -105, 103, 104, 116, 32, 91, 119, 105, 110, 102, 111, 32, 104, 101, 105, 103, 104, 116, 32, 46, -115, 98, 120, 65, 93, 10, 119, 109, 32, 100, 101, 105, 99, 111, 110, 105, 102, 121, 32, 46, -10, 125, 10, 101, 118, 97, 108, 32, 36, 112, 114, 111, 103, 10, -0}; -char const * fsl_difftk_cstr = fsl_difftk_cstr_a; -/* end of ./src/difftk.tcl */ -/* end of file ./src/difftk_cstr.c */ -/* start of file ./src/schema_config_cstr.c */ -/** @page page_schema_config_cstr config.sql - -Binary form of file ./sql/config.sql. - +/* end of file zip.c */ +/* start of file schema_config_cstr.c */ +/* Binary form of file ../sql/config.sql */ +/** @page page_schema_config_cstr Schema: config.sql +@code +-- This file contains the schema for the database that is kept in the +-- ~/.fossil file and that stores information about the users setup. +-- +CREATE TABLE cfg.global_config( + name TEXT PRIMARY KEY, + value TEXT +); + +-- Identifier for this file type. +-- The integer is the same as 'FSLG'. +PRAGMA cfg.application_id=252006675; + @endcode + @see schema_config() */ /* auto-generated code - edit at your own risk! (Good luck with that!) */ static char const fsl_schema_config_cstr_a[] = { 45, 45, 32, 84, 104, 105, 115, 32, 102, 105, 108, 101, 32, 99, 111, 110, 116, 97, 105, 110, 115, 32, 116, 104, 101, 32, 115, 99, 104, 101, 109, 97, 32, 102, 111, 114, 32, 116, 104, 101, @@ -43966,17 +40520,151 @@ 39, 70, 83, 76, 71, 39, 46, 10, 80, 82, 65, 71, 77, 65, 32, 99, 102, 103, 46, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 95, 105, 100, 61, 50, 53, 50, 48, 48, 54, 54, 55, 53, 59, 10, 0}; char const * fsl_schema_config_cstr = fsl_schema_config_cstr_a; -/* end of ./sql/config.sql */ -/* end of file ./src/schema_config_cstr.c */ -/* start of file ./src/schema_repo1_cstr.c */ -/** @page page_schema_repo1_cstr repo-static.sql +/* end of ../sql/config.sql */ +/* end of file schema_config_cstr.c */ +/* start of file schema_repo1_cstr.c */ +/* Binary form of file ../sql/repo-static.sql */ +/** @page page_schema_repo1_cstr Schema: repo-static.sql +@code +-- This file contains parts of the schema that are fixed and +-- unchanging across Fossil versions. + + +-- The BLOB and DELTA tables contain all records held in the repository. +-- +-- The BLOB.CONTENT column is always compressed using zlib. This +-- column might hold the full text of the record or it might hold +-- a delta that is able to reconstruct the record from some other +-- record. If BLOB.CONTENT holds a delta, then a DELTA table entry +-- will exist for the record and that entry will point to another +-- entry that holds the source of the delta. Deltas can be chained. +-- +-- The blob and delta tables collectively hold the "global state" of +-- a Fossil repository. +-- +CREATE TABLE repo.blob( + rid INTEGER PRIMARY KEY, -- Record ID + rcvid INTEGER, -- Origin of this record + size INTEGER, -- Size of content. -1 for a phantom. + uuid TEXT UNIQUE NOT NULL, -- SHA1 hash of the content + content BLOB, -- Compressed content of this record + CHECK( length(uuid)>=40 AND rid>0 ) +); +CREATE TABLE repo.delta( + rid INTEGER PRIMARY KEY, -- Record ID + srcid INTEGER NOT NULL REFERENCES blob -- Record holding source document +); +CREATE INDEX repo.delta_i1 ON delta(srcid); + +------------------------------------------------------------------------- +-- The BLOB and DELTA tables above hold the "global state" of a Fossil +-- project; the stuff that is normally exchanged during "sync". The +-- "local state" of a repository is contained in the remaining tables of +-- the zRepositorySchema1 string. +------------------------------------------------------------------------- + +-- Whenever new blobs are received into the repository, an entry +-- in this table records the source of the blob. +-- +CREATE TABLE repo.rcvfrom( + rcvid INTEGER PRIMARY KEY, -- Received-From ID + uid INTEGER REFERENCES user, -- User login + mtime DATETIME, -- Time of receipt. Julian day. + nonce TEXT UNIQUE, -- Nonce used for login + ipaddr TEXT -- Remote IP address. NULL for direct. +); +INSERT INTO repo.rcvfrom(rcvid,uid,mtime,nonce,ipaddr) +VALUES (1, 1, julianday('now'), NULL, NULL); + +-- Information about users +-- +-- The user.pw field can be either cleartext of the password, or +-- a SHA1 hash of the password. If the user.pw field is exactly 40 +-- characters long we assume it is a SHA1 hash. Otherwise, it is +-- cleartext. The sha1_shared_secret() routine computes the password +-- hash based on the project-code, the user login, and the cleartext +-- password. +-- +CREATE TABLE repo.user( + uid INTEGER PRIMARY KEY, -- User ID + login TEXT UNIQUE, -- login name of the user + pw TEXT, -- password + cap TEXT, -- Capabilities of this user + cookie TEXT, -- WWW login cookie + ipaddr TEXT, -- IP address for which cookie is valid + cexpire DATETIME, -- Time when cookie expires + info TEXT, -- contact information + mtime DATE, -- last change. seconds since 1970 + photo BLOB -- JPEG image of this user +); + +-- The VAR table holds miscellanous information about the repository. +-- in the form of name-value pairs. +-- +CREATE TABLE repo.config( + name TEXT PRIMARY KEY NOT NULL, -- Primary name of the entry + value CLOB, -- Content of the named parameter + mtime DATE, -- last modified. seconds since 1970 + CHECK( typeof(name)='text' AND length(name)>=1 ) +); + +-- Artifacts that should not be processed are identified in the +-- "shun" table. Artifacts that are control-file forgeries or +-- spam or artifacts whose contents violate administrative policy +-- can be shunned in order to prevent them from contaminating +-- the repository. +-- +-- Shunned artifacts do not exist in the blob table. Hence they +-- have not artifact ID (rid) and we thus must store their full +-- UUID. +-- +CREATE TABLE repo.shun( + uuid UNIQUE, -- UUID of artifact to be shunned. Canonical form + mtime DATE, -- When added. seconds since 1970 + scom TEXT -- Optional text explaining why the shun occurred +); + +-- Artifacts that should not be pushed are stored in the "private" +-- table. Private artifacts are omitted from the "unclustered" and +-- "unsent" tables. +-- +CREATE TABLE repo.private(rid INTEGER PRIMARY KEY); + +-- An entry in this table describes a database query that generates a +-- table of tickets. +-- +CREATE TABLE repo.reportfmt( + rn INTEGER PRIMARY KEY, -- Report number + owner TEXT, -- Owner of this report format (not used) + title TEXT UNIQUE, -- Title of this report + mtime DATE, -- Last modified. seconds since 1970 + cols TEXT, -- A color-key specification + sqlcode TEXT -- An SQL SELECT statement for this report +); + +-- Some ticket content (such as the originators email address or contact +-- information) needs to be obscured to protect privacy. This is achieved +-- by storing an SHA1 hash of the content. For display, the hash is +-- mapped back into the original text using this table. +-- +-- This table contains sensitive information and should not be shared +-- with unauthorized users. +-- +CREATE TABLE repo.concealed( + hash TEXT PRIMARY KEY, -- The SHA1 hash of content + mtime DATE, -- Time created. Seconds since 1970 + content TEXT -- Content intended to be concealed +); -Binary form of file ./sql/repo-static.sql. - +-- The application ID helps the unix "file" command to identify the +-- database as a fossil repository. +PRAGMA repo.application_id=252006673; + @endcode + @see schema_repo1() */ /* auto-generated code - edit at your own risk! (Good luck with that!) */ static char const fsl_schema_repo1_cstr_a[] = { 45, 45, 32, 84, 104, 105, 115, 32, 102, 105, 108, 101, 32, 99, 111, 110, 116, 97, 105, 110, 115, 32, 112, 97, 114, 116, 115, 32, 111, 102, 32, 116, 104, 101, 32, 115, 99, 104, 101, 109, @@ -44263,17 +40951,232 @@ 97, 32, 102, 111, 115, 115, 105, 108, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 46, 10, 80, 82, 65, 71, 77, 65, 32, 114, 101, 112, 111, 46, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 95, 105, 100, 61, 50, 53, 50, 48, 48, 54, 54, 55, 51, 59, 10, 0}; char const * fsl_schema_repo1_cstr = fsl_schema_repo1_cstr_a; -/* end of ./sql/repo-static.sql */ -/* end of file ./src/schema_repo1_cstr.c */ -/* start of file ./src/schema_repo2_cstr.c */ -/** @page page_schema_repo2_cstr repo-transient.sql +/* end of ../sql/repo-static.sql */ +/* end of file schema_repo1_cstr.c */ +/* start of file schema_repo2_cstr.c */ +/* Binary form of file ../sql/repo-transient.sql */ +/** @page page_schema_repo2_cstr Schema: repo-transient.sql +@code +-- This file contains parts of the schema that can change from one +-- version to the next. The data stored in these tables is +-- reconstructed from the information in the main repo schema by the +-- "rebuild" operation. + +-- Filenames +-- +CREATE TABLE repo.filename( + fnid INTEGER PRIMARY KEY, -- Filename ID + name TEXT UNIQUE -- Name of file page +); + +-- Linkages between check-ins, files created by each check-in, and +-- the names of those files. +-- +-- Each entry represents a file that changed content from pid to fid +-- due to the check-in that goes from pmid to mid. fnid is the name +-- of the file in the mid check-in. If the file was renamed as part +-- of the mid check-in, then pfnid is the previous filename. +-- +-- There can be multiple entries for (mid,fid) if the mid check-in was +-- a merge. Entries with isaux==0 are from the primary parent. Merge +-- parents have isaux set to true. +-- +-- Field name mnemonics: +-- mid = Manifest ID. (Each check-in is stored as a "Manifest") +-- fid = File ID. +-- pmid = Parent Manifest ID. +-- pid = Parent file ID. +-- fnid = File Name ID. +-- pfnid = Parent File Name ID. +-- isaux = pmid IS AUXiliary parent, not primary parent +-- +-- pid==0 if the file is added by check-in mid. +-- pid==(-1) if the file exists in a merge parents but not in the primary +-- parent. In other words, if the file file was added by merge. +-- (TODO: confirm if/where this is used in fossil and then make sure +-- libfossil does so, too.) +-- fid==0 if the file is removed by check-in mid. +-- +CREATE TABLE repo.mlink( + mid INTEGER, -- Check-in that contains fid + fid INTEGER, -- New file content RID. 0 if deleted + pmid INTEGER, -- Check-in RID that contains pid + pid INTEGER, -- Prev file content RID. 0 if new. -1 if from a merge + fnid INTEGER REFERENCES filename, -- Name of the file + pfnid INTEGER, -- Previous name. 0 if unchanged + mperm INTEGER, -- File permissions. 1==exec + isaux BOOLEAN DEFAULT 0 -- TRUE if pmid is the primary +); +CREATE INDEX repo.mlink_i1 ON mlink(mid); +CREATE INDEX repo.mlink_i2 ON mlink(fnid); +CREATE INDEX repo.mlink_i3 ON mlink(fid); +CREATE INDEX repo.mlink_i4 ON mlink(pid); + +-- Parent/child linkages between checkins +-- +CREATE TABLE repo.plink( + pid INTEGER REFERENCES blob, -- Parent manifest + cid INTEGER REFERENCES blob, -- Child manifest + isprim BOOLEAN, -- pid is the primary parent of cid + mtime DATETIME, -- the date/time stamp on cid. Julian day. + baseid INTEGER REFERENCES blob, -- Baseline if cid is a delta manifest. + UNIQUE(pid, cid) +); +CREATE INDEX repo.plink_i2 ON plink(cid,pid); + +-- A "leaf" checkin is a checkin that has no children in the same +-- branch. The set of all leaves is easily computed with a join, +-- between the plink and tagxref tables, but it is a slower join for +-- very large repositories (repositories with 100,000 or more checkins) +-- and so it makes sense to precompute the set of leaves. There is +-- one entry in the following table for each leaf. +-- +CREATE TABLE repo.leaf(rid INTEGER PRIMARY KEY); + +-- Events used to generate a timeline +-- +CREATE TABLE repo.event( + type TEXT, -- Type of event: 'ci', 'w', 'e', 't', 'g' + mtime DATETIME, -- Time of occurrence. Julian day. + objid INTEGER PRIMARY KEY, -- Associated record ID + tagid INTEGER, -- Associated ticket or wiki name tag + uid INTEGER REFERENCES user, -- User who caused the event + bgcolor TEXT, -- Color set by 'bgcolor' property + euser TEXT, -- User set by 'user' property + user TEXT, -- Name of the user + ecomment TEXT, -- Comment set by 'comment' property + comment TEXT, -- Comment describing the event + brief TEXT, -- Short comment when tagid already seen + omtime DATETIME -- Original unchanged date+time, or NULL +); +CREATE INDEX repo.event_i1 ON event(mtime); + +-- A record of phantoms. A phantom is a record for which we know the +-- UUID but we do not (yet) know the file content. +-- +CREATE TABLE repo.phantom( + rid INTEGER PRIMARY KEY -- Record ID of the phantom +); + +-- A record of orphaned delta-manifests. An orphan is a delta-manifest +-- for which we have content, but its baseline-manifest is a phantom. +-- We have to track all orphan manifests so that when the baseline arrives, +-- we know to process the orphaned deltas. +CREATE TABLE repo.orphan( + rid INTEGER PRIMARY KEY, -- Delta manifest with a phantom baseline + baseline INTEGER -- Phantom baseline of this orphan +); +CREATE INDEX repo.orphan_baseline ON orphan(baseline); + +-- Unclustered records. An unclustered record is a record (including +-- a cluster records themselves) that is not mentioned by some other +-- cluster. +-- +-- Phantoms are usually included in the unclustered table. A new cluster +-- will never be created that contains a phantom. But another repository +-- might send us a cluster that contains entries that are phantoms to +-- us. +-- +CREATE TABLE repo.unclustered( + rid INTEGER PRIMARY KEY -- Record ID of the unclustered file +); + +-- Records which have never been pushed to another server. This is +-- used to reduce push operations to a single HTTP request in the +-- common case when one repository only talks to a single server. +-- +CREATE TABLE repo.unsent( + rid INTEGER PRIMARY KEY -- Record ID of the phantom +); + +-- Each baseline or manifest can have one or more tags. A tag +-- is defined by a row in the next table. +-- +-- Wiki pages are tagged with "wiki-NAME" where NAME is the name of +-- the wiki page. Tickets changes are tagged with "ticket-UUID" where +-- UUID is the indentifier of the ticket. Tags used to assign symbolic +-- names to baselines are branches are of the form "sym-NAME" where +-- NAME is the symbolic name. +-- +CREATE TABLE repo.tag( + tagid INTEGER PRIMARY KEY, -- Numeric tag ID + tagname TEXT UNIQUE -- Tag name. +); +INSERT INTO repo.tag VALUES(1, 'bgcolor'); -- FSL_TAGID_BGCOLOR +INSERT INTO repo.tag VALUES(2, 'comment'); -- FSL_TAGID_COMMENT +INSERT INTO repo.tag VALUES(3, 'user'); -- FSL_TAGID_USER +INSERT INTO repo.tag VALUES(4, 'date'); -- FSL_TAGID_DATE +INSERT INTO repo.tag VALUES(5, 'hidden'); -- FSL_TAGID_HIDDEN +INSERT INTO repo.tag VALUES(6, 'private'); -- FSL_TAGID_PRIVATE +INSERT INTO repo.tag VALUES(7, 'cluster'); -- FSL_TAGID_CLUSTER +INSERT INTO repo.tag VALUES(8, 'branch'); -- FSL_TAGID_BRANCH +INSERT INTO repo.tag VALUES(9, 'closed'); -- FSL_TAGID_CLOSED +INSERT INTO repo.tag VALUES(10,'parent'); -- FSL_TAGID_PARENT +INSERT INTO repo.tag VALUES(11,'note'); -- FSL_TAG_NOTE +-- arguable, to force auto-increment to start at 100: +-- INSERT INTO tag VALUES(99,'FSL_TAGID_MAX_INTERNAL'); + +-- Assignments of tags to baselines. Note that we allow tags to +-- have values assigned to them. So we are not really dealing with +-- tags here. These are really properties. But we are going to +-- keep calling them tags because in many cases the value is ignored. +-- +CREATE TABLE repo.tagxref( + tagid INTEGER REFERENCES tag, -- The tag that was added or removed + tagtype INTEGER, -- 0:-,cancel 1:+,single 2:*,propagate + srcid INTEGER REFERENCES blob, -- Artifact of tag. 0 for propagated tags + origid INTEGER REFERENCES blob, -- check-in holding propagated tag + value TEXT, -- Value of the tag. Might be NULL. + mtime TIMESTAMP, -- Time of addition or removal. Julian day + rid INTEGER REFERENCE blob, -- Artifact tag is applied to + UNIQUE(rid, tagid) +); +CREATE INDEX repo.tagxref_i1 ON tagxref(tagid, mtime); + +-- When a hyperlink occurs from one artifact to another (for example +-- when a check-in comment refers to a ticket) an entry is made in +-- the following table for that hyperlink. This table is used to +-- facilitate the display of "back links". +-- +CREATE TABLE repo.backlink( + target TEXT, -- Where the hyperlink points to + srctype INT, -- 0: check-in 1: ticket 2: wiki + srcid INT, -- rid for checkin or wiki. tkt_id for ticket. + mtime TIMESTAMP, -- time that the hyperlink was added. Julian day. + UNIQUE(target, srctype, srcid) +); +CREATE INDEX repo.backlink_src ON backlink(srcid, srctype); + +-- Each attachment is an entry in the following table. Only +-- the most recent attachment (identified by the D card) is saved. +-- +CREATE TABLE repo.attachment( + attachid INTEGER PRIMARY KEY, -- Local id for this attachment + isLatest BOOLEAN DEFAULT 0, -- True if this is the one to use + mtime TIMESTAMP, -- Last changed. Julian day. + src TEXT, -- UUID of the attachment. NULL to delete + target TEXT, -- Object attached to. Wikiname or Tkt UUID + filename TEXT, -- Filename for the attachment + comment TEXT, -- Comment associated with this attachment + user TEXT -- Name of user adding attachment +); +CREATE INDEX repo.attachment_idx1 ON attachment(target, filename, mtime); +CREATE INDEX repo.attachment_idx2 ON attachment(src); -Binary form of file ./sql/repo-transient.sql. - +-- For tracking cherrypick merges +CREATE TABLE repo.cherrypick( + parentid INT, + childid INT, + isExclude BOOLEAN DEFAULT false, + PRIMARY KEY(parentid, childid) +) WITHOUT ROWID; +CREATE INDEX repo.cherrypick_cid ON cherrypick(childid); + @endcode + @see schema_repo2() */ /* auto-generated code - edit at your own risk! (Good luck with that!) */ static char const fsl_schema_repo2_cstr_a[] = { 45, 45, 32, 84, 104, 105, 115, 32, 102, 105, 108, 101, 32, 99, 111, 110, 116, 97, 105, 110, 115, 32, 112, 97, 114, 116, 115, 32, 111, 102, 32, 116, 104, 101, 32, 115, 99, 104, 101, 109, @@ -44759,17 +41662,94 @@ 111, 46, 99, 104, 101, 114, 114, 121, 112, 105, 99, 107, 95, 99, 105, 100, 32, 79, 78, 32, 99, 104, 101, 114, 114, 121, 112, 105, 99, 107, 40, 99, 104, 105, 108, 100, 105, 100, 41, 59, 10, 0}; char const * fsl_schema_repo2_cstr = fsl_schema_repo2_cstr_a; -/* end of ./sql/repo-transient.sql */ -/* end of file ./src/schema_repo2_cstr.c */ -/* start of file ./src/schema_ckout_cstr.c */ -/** @page page_schema_ckout_cstr checkout.sql +/* end of ../sql/repo-transient.sql */ +/* end of file schema_repo2_cstr.c */ +/* start of file schema_ckout_cstr.c */ +/* Binary form of file ../sql/checkout.sql */ +/** @page page_schema_ckout_cstr Schema: checkout.sql +@code +-- The VVAR table holds miscellanous information about the local database +-- in the form of name-value pairs. This is similar to the VAR table +-- table in the repository except that this table holds information that +-- is specific to the local checkout. +-- +-- Important Variables: +-- +-- repository Full pathname of the repository database +-- user-id Userid to use +-- +CREATE TABLE ckout.vvar( + name TEXT PRIMARY KEY NOT NULL, -- Primary name of the entry + value CLOB, -- Content of the named parameter + CHECK( typeof(name)='text' AND length(name)>=1 ) +); + +-- Each entry in the vfile table represents a single file in the +-- current checkout. +-- +-- The file.rid field is 0 for files or folders that have been +-- added but not yet committed. +-- +-- Vfile.chnged is 0 for unmodified files, 1 for files that have +-- been edited or which have been subjected to a 3-way merge. +-- Vfile.chnged is 2 if the file has been replaced from a different +-- version by the merge and 3 if the file has been added by a merge. +-- Vfile.chnged is 4|5 is the same as 2|3, but the operation has been +-- done by an --integrate merge. The difference between vfile.chnged==2|4 +-- and a regular add is that with vfile.chnged==2|4 we know that the +-- current version of the file is already in the repository. +-- +CREATE TABLE ckout.vfile( + id INTEGER PRIMARY KEY, -- ID of the checked out file + vid INTEGER REFERENCES blob, -- The baseline this file is part of. + chnged INT DEFAULT 0, -- 0:unchnged 1:edited 2:m-chng 3:m-add 4:i-chng 5:i-add + deleted BOOLEAN DEFAULT 0, -- True if deleted + isexe BOOLEAN, -- True if file should be executable + islink BOOLEAN, -- True if file should be symlink + rid INTEGER, -- Originally from this repository record + mrid INTEGER, -- Based on this record due to a merge + mtime INTEGER, -- Mtime of file on disk. sec since 1970 + pathname TEXT, -- Full pathname relative to root + origname TEXT, -- Original pathname. NULL if unchanged + mhash TEXT, -- Hash of mrid iff mrid!=rid. Added 2019-01-19. + UNIQUE(pathname,vid) +); + +-- This table holds a record of uncommitted merges in the local +-- file tree. If a VFILE entry with id has merged with another +-- record, there is an entry in this table with (id,merge) where +-- merge is the RECORD table entry that the file merged against. +-- An id of 0 or <-3 here means the version record itself. When +-- id==(-1) that is a cherrypick merge, id==(-2) that is a +-- backout merge and id==(-4) is a integrate merge. + +CREATE TABLE ckout.vmerge( + id INTEGER REFERENCES vfile, -- VFILE entry that has been merged + merge INTEGER, -- Merged with this record + mhash TEXT -- SHA1/SHA3 hash for merge object +); +CREATE UNIQUE INDEX ckout.vmergex1 ON vmerge(id,mhash); + +-- The following trigger will prevent older versions of Fossil that +-- do not know about the new vmerge.mhash column from updating the +-- vmerge table. This must be done with a trigger, since legacy Fossil +-- uses INSERT OR IGNORE to update vmerge, and the OR IGNORE will cause +-- a NOT NULL constraint to be silently ignored. +CREATE TRIGGER ckout.vmerge_ck1 AFTER INSERT ON vmerge +WHEN new.mhash IS NULL BEGIN + SELECT raise(FAIL, + 'trying to update a newer checkout with an older version of Fossil'); +END; -Binary form of file ./sql/checkout.sql. - +-- Identifier for this file type. +-- The integer is the same as 'FSLC'. +PRAGMA ckout.application_id=252006674; + @endcode + @see schema_ckout() */ /* auto-generated code - edit at your own risk! (Good luck with that!) */ static char const fsl_schema_ckout_cstr_a[] = { 45, 45, 32, 84, 104, 101, 32, 86, 86, 65, 82, 32, 116, 97, 98, 108, 101, 32, 104, 111, 108, 100, 115, 32, 109, 105, 115, 99, 101, 108, 108, 97, 110, 111, 117, 115, 32, 105, 110, 102, @@ -44953,17 +41933,49 @@ 97, 115, 32, 39, 70, 83, 76, 67, 39, 46, 10, 80, 82, 65, 71, 77, 65, 32, 99, 107, 111, 117, 116, 46, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 95, 105, 100, 61, 50, 53, 50, 48, 48, 54, 54, 55, 52, 59, 10, 0}; char const * fsl_schema_ckout_cstr = fsl_schema_ckout_cstr_a; -/* end of ./sql/checkout.sql */ -/* end of file ./src/schema_ckout_cstr.c */ -/* start of file ./src/schema_ticket_cstr.c */ -/** @page page_schema_ticket_cstr ticket.sql - -Binary form of file ./sql/ticket.sql. - +/* end of ../sql/checkout.sql */ +/* end of file schema_ckout_cstr.c */ +/* start of file schema_ticket_cstr.c */ +/* Binary form of file ../sql/ticket.sql */ +/** @page page_schema_ticket_cstr Schema: ticket.sql +@code +-- Template for the TICKET table +CREATE TABLE repo.ticket( + -- Do not change any column that begins with tkt_ + tkt_id INTEGER PRIMARY KEY, + tkt_uuid TEXT UNIQUE, + tkt_mtime DATE, + tkt_ctime DATE, + -- Add as many field as required below this line + type TEXT, + status TEXT, + subsystem TEXT, + priority TEXT, + severity TEXT, + foundin TEXT, + private_contact TEXT, + resolution TEXT, + title TEXT, + comment TEXT +); +CREATE TABLE repo.ticketchng( + -- Do not change any column that begins with tkt_ + tkt_id INTEGER REFERENCES ticket, + tkt_rid INTEGER REFERENCES blob, + tkt_mtime DATE, + -- Add as many fields as required below this line + login TEXT, + username TEXT, + mimetype TEXT, + icomment TEXT +); +CREATE INDEX repo.ticketchng_idx1 ON ticketchng(tkt_id, tkt_mtime); + @endcode + @see schema_ticket() */ /* auto-generated code - edit at your own risk! (Good luck with that!) */ static char const fsl_schema_ticket_cstr_a[] = { 45, 45, 32, 84, 101, 109, 112, 108, 97, 116, 101, 32, 102, 111, 114, 32, 116, 104, 101, 32, 84, 73, 67, 75, 69, 84, 32, 116, 97, 98, 108, 101, 10, 67, 82, 69, 65, 84, 69, 32, @@ -45005,17 +42017,39 @@ 103, 95, 105, 100, 120, 49, 32, 79, 78, 32, 116, 105, 99, 107, 101, 116, 99, 104, 110, 103, 40, 116, 107, 116, 95, 105, 100, 44, 32, 116, 107, 116, 95, 109, 116, 105, 109, 101, 41, 59, 10, 0}; char const * fsl_schema_ticket_cstr = fsl_schema_ticket_cstr_a; -/* end of ./sql/ticket.sql */ -/* end of file ./src/schema_ticket_cstr.c */ -/* start of file ./src/schema_ticket_reports_cstr.c */ -/** @page page_schema_ticket_reports_cstr ticket-reports.sql - -Binary form of file ./sql/ticket-reports.sql. - +/* end of ../sql/ticket.sql */ +/* end of file schema_ticket_cstr.c */ +/* start of file schema_ticket_reports_cstr.c */ +/* Binary form of file ../sql/ticket-reports.sql */ +/** @page page_schema_ticket_reports_cstr Schema: ticket-reports.sql +@code +INSERT INTO reportfmt(title,mtime,cols,sqlcode) +VALUES('All Tickets',julianday('1970-01-01'),'#ffffff Key: +#f2dcdc Active +#e8e8e8 Review +#cfe8bd Fixed +#bde5d6 Tested +#cacae5 Deferred +#c8c8c8 Closed','SELECT + CASE WHEN status IN (''Open'',''Verified'') THEN ''#f2dcdc'' + WHEN status=''Review'' THEN ''#e8e8e8'' + WHEN status=''Fixed'' THEN ''#cfe8bd'' + WHEN status=''Tested'' THEN ''#bde5d6'' + WHEN status=''Deferred'' THEN ''#cacae5'' + ELSE ''#c8c8c8'' END AS ''bgcolor'', + substr(tkt_uuid,1,10) AS ''#'', + datetime(tkt_mtime) AS ''mtime'', + type, + status, + subsystem, + title +FROM ticket'); + @endcode + @see schema_ticket_reports() */ /* auto-generated code - edit at your own risk! (Good luck with that!) */ static char const fsl_schema_ticket_reports_cstr_a[] = { 73, 78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 32, 114, 101, 112, 111, 114, 116, 102, 109, 116, 40, 116, 105, 116, 108, 101, 44, 109, 116, 105, 109, 101, 44, 99, 111, 108, 115, 44, 115, @@ -45049,17 +42083,26 @@ 44, 10, 32, 32, 115, 116, 97, 116, 117, 115, 44, 10, 32, 32, 115, 117, 98, 115, 121, 115, 116, 101, 109, 44, 10, 32, 32, 116, 105, 116, 108, 101, 10, 70, 82, 79, 77, 32, 116, 105, 99, 107, 101, 116, 39, 41, 59, 10, 0}; char const * fsl_schema_ticket_reports_cstr = fsl_schema_ticket_reports_cstr_a; -/* end of ./sql/ticket-reports.sql */ -/* end of file ./src/schema_ticket_reports_cstr.c */ -/* start of file ./src/schema_forum_cstr.c */ -/** @page page_schema_forum_cstr forum.sql - -Binary form of file ./sql/forum.sql. - +/* end of ../sql/ticket-reports.sql */ +/* end of file schema_ticket_reports_cstr.c */ +/* start of file schema_forum_cstr.c */ +/* Binary form of file ../sql/forum.sql */ +/** @page page_schema_forum_cstr Schema: forum.sql +@code +CREATE TABLE repo.forumpost( + fpid INTEGER PRIMARY KEY, -- BLOB.rid for the artifact + froot INT, -- fpid of the thread root + fprev INT, -- Previous version of this same post + firt INT, -- This post is in-reply-to + fmtime REAL -- When posted. Julian day +); +CREATE INDEX repo.forumthread ON forumpost(froot,fmtime); + @endcode + @see schema_forum() */ /* auto-generated code - edit at your own risk! (Good luck with that!) */ static char const fsl_schema_forum_cstr_a[] = { 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 114, 101, 112, 111, 46, 102, 111, 114, 117, 109, 112, 111, 115, 116, 40, 10, 32, 32, 102, 112, 105, 100, 32, 73, 78, 84, 69, @@ -45081,7 +42124,7 @@ 114, 101, 112, 111, 46, 102, 111, 114, 117, 109, 116, 104, 114, 101, 97, 100, 32, 79, 78, 32, 102, 111, 114, 117, 109, 112, 111, 115, 116, 40, 102, 114, 111, 111, 116, 44, 102, 109, 116, 105, 109, 101, 41, 59, 10, 0}; char const * fsl_schema_forum_cstr = fsl_schema_forum_cstr_a; -/* end of ./sql/forum.sql */ -/* end of file ./src/schema_forum_cstr.c */ +/* end of ../sql/forum.sql */ +/* end of file schema_forum_cstr.c */ Index: lib/libfossil.h ================================================================== --- lib/libfossil.h +++ lib/libfossil.h @@ -3,12 +3,11 @@ #endif #if defined(HAVE_CONFIG_H) # include "config.h" #endif #include "libfossil-config.h" -#include "sqlite3.h" -/* start of file ./include/fossil-scm/config.h */ +/* start of file ../include/fossil-scm/fossil-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 @@ -19,10 +18,11 @@ Heavily indebted to the Fossil SCM project (https://fossil-scm.org). */ #if defined(_MSC_VER) && !defined(FSL_AMALGAMATION_BUILD) +# include "config-win32.h" /* manually generated */ #else #endif #if !defined(_ISOC99_SOURCE) /* glibc apparently guards snprintf() on this #define, even though @@ -248,12 +248,43 @@ #define FSL_CONFIG_ENABLE_TIMER 1 #endif /* ORG_FOSSIL_SCM_FSL_CONFIG_H_INCLUDED */ -/* end of file ./include/fossil-scm/config.h */ -/* start of file ./include/fossil-scm/util.h */ +/* end of file ../include/fossil-scm/fossil-config.h */ +/* start of file ../include/fossil-scm/fossil.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_LIBFOSSIL_H_INCLUDED) +#define ORG_FOSSIL_SCM_LIBFOSSIL_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-ArtifactOfProjectName: Libfossil + SPDX-FileType: Code + + Heavily indebted to the Fossil SCM project (https://fossil-scm.org). +*/ +/** @file fossil.h + + This file is the primary header for the public APIs. It includes + various other header files. They are split into multiple headers + primarily becuase my lower-end systems choke on syntax-highlighting + them and browsing their (large) Doxygen output. +*/ + +/* + fossil-config.h MUST be included first so we can set some + portability flags and config-dependent typedefs! +*/ + +#endif +/* ORG_FOSSIL_SCM_LIBFOSSIL_H_INCLUDED */ +/* end of file ../include/fossil-scm/fossil.h */ +/* start of file ../include/fossil-scm/fossil-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 /* @@ -266,11 +297,11 @@ Heavily indebted to the Fossil SCM project (https://fossil-scm.org). */ -/** @file util.h +/** @file fossil-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. */ @@ -833,37 +864,29 @@ - ALWAYS fsl_buffer_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 on error cases. - - The `capacity` member specifies how much memory the buffer - current 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 - owned elsewhere. (See fsl_buffer_external() and - fsl_buffer_materialize().) + - The 'capacity' member specifies how much memory the buffer + current holds in its 'mem' member. - - The `used` member specifies how much of the memory is actually + - The 'used' member specifies how much of the memory is actually "in use" by the client. - - As a rule, the public APIs keep (`used`<`capacity`) and always + - As a rule, the API tries to keep (used=20); // it may reserve more! assert(0==b.used); rc = fsl_buffer_append(&b, "abc", 3); @@ -870,14 +893,27 @@ assert(0==rc); assert(3==b.used); assert(0==b.mem[b.used]); // API always NUL-terminates ``` + Potential TODO: add an allocator member which gets internally used + for allocation of the buffer member. fossil(1) uses this approach, + and swaps the allocator out as needed, to support a buffer pointing + to memory it does not own, e.g. a slice of another buffer or to + static memory, and then (re)allocate as necessary, e.g. to switch + from static memory to dynamic. That may be useful in order to + effectively port over some of the memory-intensive algos such as + merging. That would not affect [much of] the public API, just how + the buffer internally manages the memory. Certain API members would + need to specify that the memory is not owned by the blob and needs + to outlive the blob, though. We could potentially implement this + same thing without a new member by using the convention that a + `capacity` value of 0 when `mem` is!=00 means that the pointed-to + memory is owned by someone else and must be copied before + modification (effectively what fossil's approach does). + @see fsl_buffer_reserve() - @see fsl_buffer_resize() - @see fsl_buffer_external() - @see fsl_buffer_materialize() @see fsl_buffer_append() @see fsl_buffer_appendf() @see fsl_buffer_cstr() @see fsl_buffer_size() @see fsl_buffer_capacity() @@ -884,43 +920,21 @@ @see fsl_buffer_clear() @see fsl_buffer_reuse() */ struct fsl_buffer { /** - 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_buffer_external() and - fsl_buffer_materialize(). - - `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. + The raw memory owned by this buffer. It is this->capacity bytes + long, of which this->used are considered "used" by the client. + 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 + Number of bytes allocated for this buffer. */ 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 @@ -1148,125 +1162,49 @@ 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); + /** Reserves at least n bytes of capacity in buf. Returns 0 on success, FSL_RC_OOM if allocation fails, FSL_RC_MISUSE if !buf. - 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) and sets b->capacity - and buf->used to 0. + This does not change buf->used, nor will it shrink the buffer + (reduce buf->capacity) unless n is 0, in which case it + immediately frees buf->mem and sets buf->capacity and buf->used + to 0. @see fsl_buffer_resize() - @see fsl_buffer_materialize() @see fsl_buffer_clear() */ -FSL_EXPORT int fsl_buffer_reserve( fsl_buffer * const b, fsl_size_t n ); - -/** - If b is a "managed" buffer, this is a no-op and returns 0, 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. - - b is thereby transformed to a managed buffer. - - Returns 0 on success, FSL_RC_OOM on allocation error. - - Note that materialization happens automatically on demand by - fsl_buffer APIs which write to the buffer but clients can use this - to ensure that it is managed memory before they manipulate b->mem - directly. - - @see fsl_buffer_external() -*/ -FSL_EXPORT int fsl_buffer_materialize( fsl_buffer * const 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_buffer_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_buffer_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_buffer_empty or (when appropriate) fsl_buffer_empty_m. - - @see fsl_buffer_materialize() -*/ -FSL_EXPORT void fsl_buffer_external( fsl_buffer * const b, void const * mem, fsl_int_t n ); - -/** - Convenience equivalent of fsl_buffer_reserve(b,0). -*/ -FSL_EXPORT void fsl_buffer_clear( fsl_buffer * const 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_buffer_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. - - Returns b. +FSL_EXPORT int fsl_buffer_reserve( fsl_buffer * buf, fsl_size_t n ); + +/** + Convenience equivalent of fsl_buffer_reserve(buf,0). + This a no-op if buf==NULL. +*/ +FSL_EXPORT void fsl_buffer_clear( fsl_buffer * buf ); + +/** + Resets buf->used to 0 and sets buf->mem[0] (if buf->mem is not + NULL) to 0. Does not (de)allocate memory, only changes the + logical "used" size of the buffer. Returns its argument. Achtung for fossil(1) porters: this function's semantics are much different from the fossil's blob_reset(). To get those semantics, use fsl_buffer_reserve(buf, 0) or its convenience form fsl_buffer_clear(). (This function _used_ to be called fsl_buffer_reset(), but it was renamed in the hope of avoiding related confusion.) */ -FSL_EXPORT fsl_buffer * fsl_buffer_reuse( fsl_buffer * const b ); +FSL_EXPORT fsl_buffer * fsl_buffer_reuse( fsl_buffer * buf ); /** Similar to fsl_buffer_reserve() except that... - 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 (ncapacity). @@ -1275,30 +1213,17 @@ 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_buffer_external(buf,"",0) - and returns 0. - - - Else it materializes the buffer, as per fsl_buffer_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. + Returns 0 on success, FSL_RC_MISUSE if !buf, FSL_RC_OOM if + (re)allocation fails. @see fsl_buffer_reserve() - @see fsl_buffer_materialize() @see fsl_buffer_clear() */ -FSL_EXPORT int fsl_buffer_resize( fsl_buffer * const buf, fsl_size_t n ); +FSL_EXPORT int fsl_buffer_resize( fsl_buffer * buf, fsl_size_t n ); /** Swaps the contents of the left and right arguments. Results are undefined if either argument is NULL or points to uninitialized memory. @@ -1338,28 +1263,28 @@ 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 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. + src may only be NULL if n==0. If passed (src==NULL, n!=0) then + FSL_RC_RANGE is returned. - If this function succeeds, it guarantees that it NUL-terminates the - buffer (but that the NUL terminator is not counted in b->used). + Returns 0 on success, FSL_RC_MISUSE if !f, !b, or !src, + 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). @see fsl_buffer_appendf() @see fsl_buffer_reserve() */ -FSL_EXPORT int fsl_buffer_append( fsl_buffer * const b, +FSL_EXPORT int fsl_buffer_append( fsl_buffer * b, void const * src, fsl_int_t n ); /** Uses fsl_appendf() to append formatted output to the given buffer. Returns 0 on success and FSL_RC_OOM if an allocation fails while @@ -1423,36 +1348,27 @@ fsl_buffer const *pIn2, fsl_buffer *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). - - 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. + pIn and pOut to be the same buffer. Returns 0 on success. On + error pOut is not modified. + + pOut must be either cleanly initialized/empty or the same as pIn. Results are undefined if any argument is NULL. Returns 0 on success, FSL_RC_OOM on allocation error, and - some other code if the lower-level decompression routines fail. + FSL_RC_ERROR if the lower-level decompression routines fail. - 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_buffer_is_compressed() returns - false for pIn then this is a no-op. + TODO: if pOut!=(pIn1 or pIn2) then re-use its memory, if it has any. @see fsl_buffer_compress() @see fsl_buffer_compress2() @see fsl_buffer_is_compressed() */ -FSL_EXPORT int fsl_buffer_uncompress(fsl_buffer const * const pIn, - fsl_buffer * const pOut); +FSL_EXPORT int fsl_buffer_uncompress(fsl_buffer const *pIn, fsl_buffer *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_buffer_compress() or equivalent. This is not a @@ -1460,11 +1376,11 @@ on certain inputs, but that is thought to be unlikely (at least for text data). Returns 0 if mem is NULL. */ -FSL_EXPORT bool fsl_data_is_compressed(unsigned char const * const mem, fsl_size_t len); +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_buffer_is_compressed(fsl_buffer const * buf); @@ -1480,80 +1396,57 @@ The fsl_buffer counterpart of fsl_data_uncompressed_size(). */ FSL_EXPORT fsl_int_t fsl_buffer_uncompressed_size(fsl_buffer const * b); /** - Equivalent to ((char const *)b->mem). 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. + Equivalent to ((char const *)b->mem), but returns NULL if + !b. 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_). @see fsl_buffer_str() @see fsl_buffer_cstr2() */ -FSL_EXPORT char const * fsl_buffer_cstr(fsl_buffer const * const b); +FSL_EXPORT char const * fsl_buffer_cstr(fsl_buffer const *b); /** - If b has any memory allocated to it, that memory is returned. If - len is not NULL then *len is set to b->used. If b has no memory - then NULL is returned and *len (if len is not NULL) is set to 0. + If buf is not NULL and has any memory allocated to it, that + memory is returned. If both b and len are not NULL then *len is + set to b->used. If b has no dynamic memory then NULL is returned + and *len (if len is not NULL) is set to 0. @see fsl_buffer_str() @see fsl_buffer_cstr() */ -FSL_EXPORT char const * fsl_buffer_cstr2(fsl_buffer const * const b, fsl_size_t * const len); +FSL_EXPORT char const * fsl_buffer_cstr2(fsl_buffer const *b, fsl_size_t * len); /** Equivalent to ((char *)b->mem). 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_buffer_materialize() - to transform it to a managed buffer before using this routine, - noting that any of the public fsl_buffer APIs which write to a - buffer will materialize it on demand if needed. - - @see fsl_buffer_take() */ -FSL_EXPORT char * fsl_buffer_str(fsl_buffer const * const b); - +FSL_EXPORT char * fsl_buffer_str(fsl_buffer 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_buffer_materialize() - @see fsl_buffer_str() - @see fsl_buffer_cstr() - @see fsl_buffer_cstr2() + empty. */ -FSL_EXPORT char * fsl_buffer_take(fsl_buffer * const b); +FSL_EXPORT char * fsl_buffer_take(fsl_buffer *b); /** Returns the "used" size of b, or 0 if !b. */ -#define fsl_buffer_size(b) (b)->used -#if 0 -FSL_EXPORT fsl_size_t fsl_buffer_size(fsl_buffer const * const b); -#endif +FSL_EXPORT fsl_size_t fsl_buffer_size(fsl_buffer const * b); /** Returns the current capacity of b, or 0 if !b. */ -#define fsl_buffer_capacity(b) (b)->capacity -#if 0 -FSL_EXPORT fsl_size_t fsl_buffer_capacity(fsl_buffer const * const b); -#endif +FSL_EXPORT fsl_size_t fsl_buffer_capacity(fsl_buffer const * b); + /** Compares the contents of buffers lhs and rhs using memcmp(3) semantics. Return 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. @@ -1560,11 +1453,11 @@ 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_buffer_compare(fsl_buffer const * const lhs, fsl_buffer const * const rhs); +FSL_EXPORT int fsl_buffer_compare(fsl_buffer const * lhs, fsl_buffer const * rhs); /** 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 @@ -1594,11 +1487,11 @@ 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_buffer_compare_O1(fsl_buffer const * const lhs, fsl_buffer const * const rhs); +FSL_EXPORT int fsl_buffer_compare_O1(fsl_buffer const * lhs, fsl_buffer 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, @@ -1619,13 +1512,13 @@ @see fsl_buffer_delta_apply() @see fsl_delta_apply() @see fsl_delta_apply2() */ -FSL_EXPORT int fsl_buffer_delta_apply( fsl_buffer const * const pOriginal, - fsl_buffer const * const pDelta, - fsl_buffer * const pTarget); +FSL_EXPORT int fsl_buffer_delta_apply( fsl_buffer const * pOriginal, + fsl_buffer const * pDelta, + fsl_buffer * pTarget); /** Identical to fsl_buffer_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 @@ -1635,14 +1528,14 @@ @see fsl_buffer_delta_apply() @see fsl_delta_apply() @see fsl_delta_apply2() */ -FSL_EXPORT int fsl_buffer_delta_apply2( fsl_buffer const * const pOriginal, - fsl_buffer const * const pDelta, - fsl_buffer * const pTarget, - fsl_error * const pErr); +FSL_EXPORT int fsl_buffer_delta_apply2( fsl_buffer const * pOriginal, + fsl_buffer const * pDelta, + fsl_buffer * pTarget, + fsl_error * pErr); /** Uses a fsl_input_f() function to buffer input into a fsl_buffer. @@ -1740,11 +1633,11 @@ FSL_RC_MISUSE if !b or !fname, FSL_RC_IO if opening or writing fails. Uses fsl_fopen() to open the file, so it supports the name '-' as an alias for stdout. */ -FSL_EXPORT int fsl_buffer_to_filename( fsl_buffer const * const b, +FSL_EXPORT int fsl_buffer_to_filename( fsl_buffer const * b, char const * fname ); /** Copy N lines of text from pFrom into pTo. The copy begins at the current pFrom->cursor position. pFrom->cursor is left pointing at @@ -1888,25 +1781,18 @@ /** 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 @@ -2161,11 +2047,11 @@ ``` @see fsl_list_clear() @see fsl_list_visit_free() */ -FSL_EXPORT int fsl_list_reserve( fsl_list * const self, fsl_size_t n ); +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. @@ -2172,18 +2058,18 @@ Ownership of cp is unchanged by this call. cp may not be NULL. Returns 0 on success, FSL_RC_MISUSE if any argument is NULL, or FSL_RC_OOM on allocation error. */ -FSL_EXPORT int fsl_list_append( fsl_list * const self, void * cp ); +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 * const lhs, fsl_list * const rhs ); +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 @@ -2245,12 +2131,11 @@ 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 * const list, - fsl_list_visitor_f childFinalizer, +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 @@ -2263,11 +2148,11 @@ Results are undefined if list is NULL. @see fsl_list_clear() */ -FSL_EXPORT void fsl_list_visit_free( fsl_list * const list, bool freeListMem ); +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 @@ -2275,22 +2160,21 @@ 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 * const self, int order, - bool shiftIfNulled, +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 * const li, fsl_generic_cmp_f cmp); +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 @@ -2363,21 +2247,20 @@ fsl_buffer_clear(&buf); ``` */ FSL_EXPORT int fsl_file_canonical_name2(const char *zRoot, const char *zOrigName, - fsl_buffer * const pOut, - bool slash); + fsl_buffer *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_buffer * const pOut, bool slash); + fsl_buffer *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 (non-0) then the @@ -2400,11 +2283,11 @@ 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_buffer * const pOut, bool leaveSlash); + fsl_buffer * pOut, bool leaveSlash); /** Writes the absolute path name of the current directory to zBuf, which must be at least nBuf bytes long (nBuf includes the space @@ -2491,12 +2374,11 @@ */ 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. + may be absolute or relative to the current working dir. */ FSL_EXPORT bool fsl_is_symlink(const char *zFilename); /** Returns true if the given filename refers to a plain file or @@ -2519,21 +2401,14 @@ * 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. + Changes are made in-place. Return the new name length. If the + slash parameter is non-zero, the trailing slash, if any, is + retained. If n is <0 then fsl_strlen() is used to calculate the + length. */ FSL_EXPORT fsl_size_t fsl_file_simplify_name(char *z, fsl_int_t n_, bool slash); /** Return true (non-zero) if string z matches glob pattern zGlob @@ -2574,11 +2449,11 @@ @see fsl_glob_list_append() @see fsl_glob_list_matches() @see fsl_glob_list_clear() */ -FSL_EXPORT int fsl_glob_list_parse( fsl_list * const tgt, char const * zPatternList ); +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. @@ -2588,11 +2463,11 @@ @see fsl_glob_list_parse() @see fsl_glob_list_matches() @see fsl_glob_list_clear() */ -FSL_EXPORT int fsl_glob_list_append( fsl_list * const tgt, char const * zGlob ); +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 @@ -2785,113 +2660,10 @@ 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 populates the given buffer - with it. 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. - - - 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_buffer * const tgt, char const *zPrefix, - char * const * 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. @@ -2919,18 +2691,18 @@ 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()). + Renames zFrom to zTo, as per rename(3). Returns 0 on success. On + error it returns FSL_RC_OOM on allocation error when converting the + names to platforms-specific character sets (on platforms where that + happens) or an FSL_RC_xxx value approximating an errno value, 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 @@ -2967,31 +2739,10 @@ 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. @@ -3045,67 +2796,15 @@ 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". + /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_buffer_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_buffer * const 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 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); /** 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 @@ -3251,11 +2950,11 @@ /** 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 + Runs the OS's stat(2) equivalent to populate fst with information about the given file. Returns 0 on success, FSL_RC_MISUSE if zFilename is NULL, and FSL_RC_RANGE if zFilename starts with a NUL byte. Returns FSL_RC_NOT_FOUND if no filesystem entry is found for the given @@ -3274,11 +2973,11 @@ 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 * const fst, +FSL_EXPORT int fsl_stat(const char *zFilename, fsl_fstat * fst, bool derefSymlinks); /** Create a new delta between the memory zIn and zOut. @@ -3369,42 +3068,41 @@ 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. + - Returns FSL_RC_MISUSE if any of (zSrc, zOut, 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_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); +FSL_EXPORT int fsl_delta_create2( unsigned char const *zSrc, fsl_size_t lenSrc, + unsigned char const *zOut, fsl_size_t lenOut, + 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 the output buffer (delta) is the same as src or newVers, FSL_RC_MISUSE is returned, and results are undefined if delta - indirectly refers to the same buffer as either src or newVers - or if any argument is NULL. + indirectly refers to the same buffer as either src or newVers. Returns 0 on success. */ -FSL_EXPORT int fsl_buffer_delta_create( fsl_buffer const * const src, - fsl_buffer const * const newVers, - fsl_buffer * const delta); +FSL_EXPORT int fsl_buffer_delta_create( fsl_buffer const * src, + fsl_buffer const * newVers, + fsl_buffer * delta); /** Apply a delta created using fsl_delta_create(). The output buffer must be big enough to hold the whole output @@ -3522,11 +3220,11 @@ /** Defossilizes the contents of b. Equivalent to: fsl_bytes_defossilize( b->mem, &b->used ); */ -FSL_EXPORT void fsl_buffer_defossilize( fsl_buffer * const b ); +FSL_EXPORT void fsl_buffer_defossilize( fsl_buffer * 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. @@ -3646,34 +3344,134 @@ Results are undefined if xlate is NULL. */ FSL_EXPORT fsl_size_t fsl_htmlize_xlate(int c, char const ** xlate); +/** + Flags for use with text-diff generation APIs, + e.g. fsl_diff_text(). + + Maintenance reminder: these values are holy and must not be + changed without also changing the corresponding code in + diff.c. + + @deprecated Prefer fsl_diff2_flag_e and fsl_diff_v2() instead. +*/ +enum fsl_diff_flag_e { +/** Ignore end-of-line whitespace */ +FSL_DIFF_IGNORE_EOLWS = 0x01, +/** Ignore end-of-line whitespace */ +FSL_DIFF_IGNORE_ALLWS = 0x03, +/** Generate a side-by-side diff */ +FSL_DIFF_SIDEBYSIDE = 0x04, +/** Missing shown as empty files */ +FSL_DIFF_VERBOSE = 0x08, +/** Show filenames only. Not used in this impl! */ +FSL_DIFF_BRIEF = 0x10, +/** Render HTML. */ +FSL_DIFF_HTML = 0x20, +/** Show line numbers. */ +FSL_DIFF_LINENO = 0x40, +/** Suppress optimizations (debug). */ +FSL_DIFF_NOOPT = 0x0100, +/** Invert the diff (debug). */ +FSL_DIFF_INVERT = 0x0200, +/** Only display if not "too big." */ +FSL_DIFF_NOTTOOBIG = 0x0800, +/** Strip trailing CR */ +FSL_DIFF_STRIP_EOLCR = 0x1000, +/** + This flag tells text-mode diff generation to add ANSI color + sequences to some output. The colors are currently hard-coded + and non-configurable. This has no effect for HTML output, and + that flag trumps this one. It also currently only affects + unified diffs, not side-by-side. + + Maintenance reminder: this one currently has no counterpart in + fossil(1), is not tracked in the same way, and need not map to an + internal flag value. +*/ +FSL_DIFF_ANSI_COLOR = 0x2000 +}; + +/** + Generates a textual diff from two text inputs and writes + it to the given output function. + + pA and pB are the buffers to diff. + + contextLines is the number of lines of context to output. This + parameter has a built-in limit of 2^16, and values larger than + that get truncated. A value of 0 is legal, in which case no + surrounding context is provided. A negative value translates to + some unspecified default value. + + sbsWidth specifies the width (in characters) of the side-by-side + columns. If sbsWidth is not 0 then this function behaves as if + diffFlags contains the FSL_DIFF_SIDEBYSIDE flag. If sbsWidth is + negative, OR if diffFlags explicitly contains + FSL_DIFF_SIDEBYSIDE and sbsWidth is 0, then some default width + is used. This parameter has a built-in limit of 255, and values + larger than that get truncated to 255. + + diffFlags is a mask of fsl_diff_flag_t values. Not all of the + fsl_diff_flag_t flags are yet [sup]ported. + + The output is sent to out(outState,...). If out() returns non-0 + during processing, processing stops and that result is returned + to the caller of this function. + + Returns 0 on success, FSL_RC_OOM on allocation error, + FSL_RC_MISUSE if any arguments are invalid, FSL_RC_TYPE if any + of the content appears to be binary (contains embedded NUL + bytes), FSL_RC_RANGE if some range is exceeded (e.g. the maximum + number of input lines). + + None of (pA, pB, out) may be NULL. + + TODOs: + + - Add a predicate function for outputing only matching + differences, analog to fossil(1)'s regex support (but more + flexible). + + - Expose the raw diff-generation bits via the internal API + to facilitate/enable the creation of custom diff formats. + + @see fsl_diff_v2() + @deprecated Prefer fsl_diff_v2() for new code. +*/ +FSL_EXPORT int fsl_diff_text(fsl_buffer const *pA, fsl_buffer const *pB, + fsl_output_f out, void * outState, + short contextLines, short sbsWidth, + int diffFlags ); + +/** + Functionally equivalent to: + + ``` + fsl_diff_text(pA, pB, fsl_output_f_buffer, pOut, + contextLines, sbsWidth, diffFlags); + ``` + + Except that it returns FSL_RC_MISUSE if !pOut. + + @see fsl_diff_v2() + @deprecated Prefer fsl_diff_v2() for new code. +*/ +FSL_EXPORT int fsl_diff_text_to_buffer(fsl_buffer const *pA, fsl_buffer const *pB, + fsl_buffer *pOut, short contextLines, + short sbsWidth, int diffFlags ); /** @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 + (fsl_diff_builder 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. + Maintenance reminder: some of these values are holy and must not be + changed without also changing the corresponding code in diff2.c. */ enum fsl_diff2_flag_e { /** Ignore end-of-line whitespace. Applies to all diff builders. */ FSL_DIFF2_IGNORE_EOLWS = 0x01, @@ -3697,19 +3495,15 @@ 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, +FSL_DIFF2_SLOW_SBS = 0x2000, /** Tells diff builders which support it to include line numbers in their output. */ FSL_DIFF2_LINE_NUMBERS = 0x10000, @@ -3717,10 +3511,16 @@ Tells diff builders which optionally support an "index" line to NOT include it in their output. */ FSL_DIFF2_NOINDEX = 0x20000, +/** + Tells the TCL diff builder that the complete output and each line + should be wrapped in {...}. +*/ +FSL_DIFF2_TCL_BRACES = 0x40000, + /** Reserved for client-defined diff builder use. */ FSL_DIFF2_CLIENT1 = 0x01000000, /** @@ -3735,56 +3535,22 @@ 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 + fsl_diff_builder objects. Some of this state is configuration provided by the client and some is volatile, used for communicating common state to diff builder instances during the diff rendering process. - Certain fsl_dibu implementations may require that some + Certain fsl_diff_builder implementations may require that some ostensibly optional fields be filled out. Documenting that is TODO, as the builders get developed. */ -struct fsl_dibu_opt { +struct fsl_diff_opt { /** Flags from the fsl_diff2_flag_e enum. */ uint32_t diffFlags; /** @@ -3791,13 +3557,13 @@ 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. + Maximum column width for side-by-side, a.k.a. split, diffs. - FSL_DIBU_SPLIT_TEXT truncates its content columns (as + FSL_DIFF_BUILDER_SPLIT_TEXT truncates its content columns (as opposed to line numbers and its modification marker) to, at most, this width. By default it uses as much width as is necessary to render whole lines. It treats this limit as UTF8 characters, not bytes. @@ -3833,24 +3599,20 @@ 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 @@ -3862,11 +3624,11 @@ 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 { + struct fsl_diff_opt_ansi { /** Color escape sequence for inserted lines. */ char const * insertion; /** @@ -3887,31 +3649,31 @@ char const * reset; } ansiColor; }; /** Convenience typedef. */ -typedef struct fsl_dibu_opt fsl_dibu_opt; +typedef struct fsl_diff_opt fsl_diff_opt; -/** Initialized-with-defaults fsl_dibu_opt structure, intended for +/** Initialized-with-defaults fsl_diff_opt structure, intended for const-copy initialization. */ -#define fsl_dibu_opt_empty_m {\ +#define fsl_diff_opt_empty_m {\ 0/*diffFlags*/, 5/*contextLines*/, 0/*columnWidth*/,\ NULL/*nameLHS*/,NULL/*hashLHS*/, \ NULL/*nameRHS*/, NULL/*hashRHS*/, \ NULL/*out*/, NULL/*outState*/, \ {/*ansiColor*/ ""/*insertion*/,""/*edit*/,""/*deletion*/,\ ""/*reset*/} \ } -/** Initialized-with-defaults fsl_dibu_opt structure, intended for +/** Initialized-with-defaults fsl_diff_opt structure, intended for non-const copy initialization. */ -extern const fsl_dibu_opt fsl_dibu_opt_empty; +extern const fsl_diff_opt fsl_diff_opt_empty; /** Information about each line of a file being diffed. - This type is only in the public API for use by the fsl_dibu + This type is only in the public API for use by the fsl_diff_builder interface, specifically for use with fsl_dline_change_spans(). It is not otherwise intended for public use. None of its members are considered even remotely public except for this->z and this->n. */ struct fsl_dline { @@ -3955,11 +3717,11 @@ /** 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. + fsl_diff_builder implementations. */ struct fsl_dline_change { /** Number of change spans (number of used elements in this->a). */ unsigned char n; /** Array of change spans, in left-to-right order */ @@ -4003,11 +3765,11 @@ 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 + fsl_diff_builder objects. It is not a requirement for such objects but can be used to provide more detailed diff changes than marking whole lines as simply changed or not. */ FSL_EXPORT void fsl_dline_change_spans(const fsl_dline *pLeft, const fsl_dline *pRight, @@ -4059,16 +3821,15 @@ 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; +typedef struct fsl_diff_builder fsl_diff_builder; /** This class is the basis of libfossil's port of the diff engine - added to fossil(1) in 2021-09, colloquially known as the "diff - builder." + added to fossil(1) in 2021-09. A diff builder is an object responsible for formatting low-level diff info another form, typically for human readability but also for machine readability (patches). The library generates a low-level diff then feeds that through an algorithm which @@ -4076,12 +3837,23 @@ rendering of the diff to an instance of this class. The internal APIs which drive each instance of this class guaranty that if any method of this class returns non-0 (an error code) then no futher methods will be called except for finalize(). + + Potential TODO: add a two-phase option to this interface. If + builder->passes is greater than 0, builder->currentPass gets set to + the current pass number (1 or 2) then it gets passed the diff once + for each pass the builder needs, updating the currentPass flag + between runs. The first phase is simply for it to analyze what + needs to be done and the second is to do it. That would allow, + e.g. the split-mode impl to avoid buffering all of the output + because the first pass would allow it to calculate the width it + needs for outputing the text columns. It would also allow for it to + dynamically resize the line number columns more easily. */ -struct fsl_dibu { +struct fsl_diff_builder { /** Config info, owned by higher-level routines. Every diff builder requires one of these. Builders are prohibited from modifying these but the diff driver will. @@ -4090,26 +3862,18 @@ 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 * 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. + fsl_diff_opt * opt; + /** + If not NULL, this is called once per diff to give the builder a + chance to perform any bootstrapping initialization or header + output. At the point this is called, this->cfg is assumed to have + been filled out properly. Diff builder implementations which + require dynamic resource allocation may perform it here or in + their factory routine(s). This method should also reset any dynamic state of a builder so that it may be reused for subsequent diffs. This enables the API to use a single builder for a collection of logically grouped files without having to destroy and reallocate the builder. @@ -4119,11 +3883,11 @@ is finalize(). The diff driver sets this->lnLHS and this->lnRHS to 0 before calling this. */ - int (*start)(fsl_dibu * const b); + int (*start)(fsl_diff_builder* const); /** If this is not NULL, it is called one time at the start of each chunk of diff for a given file and is passed the line number of each half of the diff and the number of lines in that chunk for @@ -4144,11 +3908,11 @@ 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* const, + int (*chunkHeader)(fsl_diff_builder* const, uint32_t A, uint32_t B, uint32_t C, uint32_t D); /** Tells the builder that n lines of common output are to be @@ -4157,39 +3921,39 @@ Typical common implementation details: - Increment both this->lnLHS and this->lnRHS by n. */ - int (*skip)(fsl_dibu* const, uint32_t n); + int (*skip)(fsl_diff_builder* const, uint32_t n); /** Tells the builder that the given line represents one line of common output. Must return 0 on success, non-0 on error. Typical common implementation details: - Increment both this->lnLHS and this->lnRHS by 1. */ - int (*common)(fsl_dibu* const, fsl_dline const * line); + int (*common)(fsl_diff_builder* const, fsl_dline const * line); /** Tells the builder that the given line represents an "insert" into the RHS. Must return 0 on success, non-0 on error. Typical common implementation details: - Increment this->lnRHS by 1. */ - int (*insertion)(fsl_dibu* const, fsl_dline const * line); + int (*insertion)(fsl_diff_builder* const, fsl_dline const * line); /** Tells the builder that the given line represents a "deletion" - a line removed from the LHS. Must return 0 on success, non-0 on error. Typical common implementation details: - Increment this->lnLHS by 1. */ - int (*deletion)(fsl_dibu* const, fsl_dline const * line); + int (*deletion)(fsl_diff_builder* const, fsl_dline const * line); /** Tells the builder that the given line represents a replacement from the LHS to the RHS. Must return 0 on success, non-0 on error. This differs from an "edit" in that the line being replaced seems to have on relationship to the replacement. Even @@ -4199,11 +3963,11 @@ Typical common implementation details: - Increment both this->lnLHS and this->lnRHS by 1. */ - int (*replacement)(fsl_dibu* const, fsl_dline const * lineLhs, + int (*replacement)(fsl_diff_builder* const, fsl_dline const * lineLhs, fsl_dline const * lineRhs); /** Tells the builder that the given line represents an "edit" from the LHS to the RHS. Must return 0 on success, non-0 on error. Builders are free, syntax permitting, to usse the @@ -4215,11 +3979,11 @@ Typical common implementation details: - Increment both this->lnLHS and this->lnRHS by 1. */ - int (*edit)(fsl_dibu* const, fsl_dline const * lineLhs, + int (*edit)(fsl_diff_builder* const, fsl_dline const * lineLhs, fsl_dline const * lineRhs); /** Must "finish" the diff process. Depending on the diff impl, this might flush any pending output or may be a no-op. This is only called if the rest of the diff was generated without producing an @@ -4231,82 +3995,53 @@ 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* const 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* const b); + */ + int (*finish)(fsl_diff_builder* const); /** Must free any state owned by this builder, including the builder object. It must not generate any output. + + Must return 0 on success, non-0 on error (e.g. output flushing + fails), but must clean up its own state and the builder object in + either case. */ - void (*finalize)(fsl_dibu* const); + void (*finalize)(fsl_diff_builder* const); + /** If true, this builder gets passed through the diff generation process twice. See this->passNumber for details. */ bool twoPass; + /** Gets set to the "pass number" immediately before this->start() is called, starting with pass number 1. This value is only relevant for two-pass builders, which can use this to control their mode of operation, e.g. data collection in pass 1 and actual work in - pass 2. Note that all of the diff-building API methods are called + pass 2. Note that all of the diff-building API methods are call for both passes, including start() and finish(). Only finalize() - and finally() are not affected by this. + is not affected by this. */ unsigned short passNumber; /** Impl-specific diff-generation state. If it is owned by this instance then this->finalize() must clean it up. */ void * pimpl; /** - 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. + Impl-specific int for tracking basic output state, e.g. of + opening/closing tags. This must not be modified by clients. */ unsigned int implFlags; /** A place to store the number of files seen by this builder so far, for builders which need to distinguish that somehow (e.g. adding a separator before each file after the first). Implementations which use this should increment it in their start() method. - - 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 @@ -4317,68 +4052,38 @@ 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 +/** Initialized-with-defaults fsl_diff_builder structure, intended for const-copy initialization. */ -#define fsl_dibu_empty_m { \ - NULL/*opt*/,NULL/*typeID*/, \ +#define fsl_diff_builder_empty_m { \ + NULL/*cfg*/, \ NULL/*start()*/,NULL/*chunkHeader()*/,NULL/*skip()*/, NULL/*common()*/, \ NULL/*insertion()*/,NULL/*deletion()*/, NULL/*replacement()*/, \ - NULL/*edit()*/, NULL/*finish()*/, NULL/*finally()*/,NULL/*finalize()*/, \ + NULL/*edit()*/, NULL/*finish()*/, NULL/*finalize()*/, \ false/*twoPass*/,0U/*passNumber*/, \ - NULL/*pimpl*/, 0U/*pimplFlags*/,0U/*implFlags*/,0U/*fileCount*/, \ - 0/*lnLHS*/,0/*lnRHS*/, \ - {/*metric*/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, + NULL/*pimpl*/, 0U/*implFlags*/,0U/*fileCount*/, \ + 0/*lnLHS*/,0/*lnRHS*/ \ +} + +/** Initialized-with-defaults fsl_diff_builder structure, intended for + non-const copy initialization. */ +extern const fsl_diff_builder fsl_diff_builder_empty; + +/** + Type IDs for use with fsl_diff_builder_factory(). +*/ +enum fsl_diff_builder_e { /** A "dummy" diff builder intended only for testing the - fsl_dibu interface and related APIs. It does not produce + fsl_diff_builder interface and related APIs. It does not produce output which is generically useful. */ -FSL_DIBU_DEBUG = 1, +FSL_DIFF_BUILDER_DEBUG = 1, /** Generates diffs in a compact low(ist)-level form originally designed for use by diff renderers implemented in JavaScript. This diff builder outputs a JSON object with the following @@ -4414,25 +4119,25 @@ 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, +FSL_DIFF_BUILDER_JSON1, /** A diff builder which produces output compatible with the patch(1) command. Its output is functionally identical to fossil(1)'s default diff output except that by default includes an Index line at the top of each file (use the FSL_DIFF2_NOINDEX flag in its - fsl_dibu_opt::diffFlags to disable that). + fsl_diff_opt::diffFlags to disable that). Supported flags: - FSL_DIFF2_LINE_NUMBERS (makes it incompatible with patch(1)) - FSL_DIFF2_NOINDEX */ -FSL_DIBU_UNIFIED_TEXT, +FSL_DIFF_BUILDER_UNIFIED_TEXT, /** A diff builder which outputs a description of the diff in a TCL-readable form. It requires external TCL code in order to function. @@ -4439,23 +4144,23 @@ TODO: a flag which includes the tcl/tk script as part of the output. We first need to compile fossil's diff.tcl into the library. */ -FSL_DIBU_TCL, +FSL_DIFF_BUILDER_TCL, /** A pain-text side-by-side (a.k.a. split) diff view. This diff always behaves as if the FSL_DIFF2_LINE_NUMBERS flag were set because its output is fairly useless without line numbers. It optionally supports ANSI coloring. */ -FSL_DIBU_SPLIT_TEXT +FSL_DIFF_BUILDER_SPLIT_TEXT }; -typedef enum fsl_dibu_e fsl_dibu_e; +typedef enum fsl_diff_builder_e fsl_diff_builder_e; /** - A factory for creating fsl_dibu instances of types which + A factory for creating fsl_diff_builder instances of types which are built in to the library. This does not preclude the creation of client-side diff builders (e.g. ones which write to ncurses widgets or similar special-case output). On success, returns 0 and assigns *pOut to a new builder instance @@ -4462,51 +4167,16 @@ 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 * const b); +FSL_EXPORT int fsl_diff_builder_factory( fsl_diff_builder_e type, + fsl_diff_builder **pOut ); /** This counterpart of fsl_diff_text() defines its output format in - terms of a fsl_dibu instance which the caller must provide. + terms of a fsl_diff_builder instance which the caller must provide. The caller is responsible for pointing pBuilder->cfg to a configuration object suitable for the desired diff. In particular, pBuilder->cfg->out and (if necessary) pBuilder->cfg->outState must be set to non-NULL values. @@ -4529,17 +4199,17 @@ 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_builder_factory() @see fsl_diff_text() - @see fsl_diff_v2_raw() + @see fsl_diff_raw_v2() */ FSL_EXPORT int fsl_diff_v2(fsl_buffer const * pv1, fsl_buffer const * pv2, - fsl_dibu * const pBuilder); + fsl_diff_builder * const pBuilder); /** Performs a diff, as for fsl_diff_v2(), but returns the results in the form of an array of COPY, DELETE, INSERT triples terminated by 3 entries with the value 0. @@ -4552,23 +4222,22 @@ 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_buffer const * pv1, fsl_buffer const * pv2, - fsl_dibu_opt const * const cfg, + fsl_diff_opt const * const cfg, int **outRaw ); + /** If zDate is an ISO8601-format string, optionally with a .NNN fractional suffix, then this function returns true and sets *pOut (if pOut is not NULL) to the corresponding Julian @@ -5368,22 +5037,22 @@ /** 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_buffer * const b ); +FSL_EXPORT fsl_size_t fsl_simplify_sql_buffer( fsl_buffer * 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. + isatty(). i.e. it returns a true value (non-0) if it thinks that + the given file descriptor value is attached to an interactive + terminal, else it returns false. +*/ +FSL_EXPORT char fsl_isatty(int fd); - 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 @@ -5531,14 +5200,11 @@ 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_TYPE if any input - appears to be binary. - - FIXME/TODO: return FSL_RC_DIFF_BINARY instead of FSL_RC_TYPE when - encountering binary inputs. + appears to be binary. @see fsl_buffer_contains_merge_marker() */ FSL_EXPORT int fsl_buffer_merge3(fsl_buffer * const pPivot, fsl_buffer * const pV1, @@ -5548,19 +5214,12 @@ /** 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 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_buffer_append_tcl_literal(fsl_buffer * const b, - bool escapeSquigglies, char const * z, fsl_int_t n); /** Event IDs for use with fsl_confirm_callback_f implementations. @@ -5863,19 +5522,13 @@ /** Callback type for use with fsl_dircrawl(). It gets passed the absolute name of the target directory, the name of the directory entry (no path part), the type of the entry, and the client state pointer which is passed to that routine. It 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. + success or another FSL_RC_xxx value on error. Returning + FSL_RC_BREAK will cause directory-crawling to stop without an + error. 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. */ @@ -5911,17 +5564,16 @@ 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 + "reasonable" internally hard-coded limit), in order to prevent 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. + result code unless the result is FSL_RC_BREAK, which stops + iteration but causes 0 to be returned from this function. */ FSL_EXPORT int fsl_dircrawl(char const * dirName, fsl_dircrawl_f callback, void * callbackState); /** @@ -5979,11 +5631,11 @@ 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. + else returns true. */ FSL_EXPORT bool fsl_looks_like_binary(fsl_buffer const * const b); /** If b appears to contain any non-UTF8 content, returns a truthy @@ -6047,18 +5699,10 @@ (always 3), regardless of whether or not the function returns true or false. */ FSL_EXPORT bool fsl_starts_with_bom_utf8(fsl_buffer const * const b, unsigned int *pBomSize); -/** - 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); - #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. @@ -6090,12 +5734,12 @@ #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 */ +/* end of file ../include/fossil-scm/fossil-util.h */ +/* start of file ../include/fossil-scm/fossil-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 /* @@ -6107,11 +5751,11 @@ SPDX-FileType: Code Heavily indebted to the Fossil SCM project (https://fossil-scm.org). */ -/** @file core.h +/** @file fossil-core.h This file declares the core SCM-related public APIs. */ #include /* struct tm, time_t */ @@ -6210,11 +5854,12 @@ 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_db_role_label() + @see fsl_cx_db_name_for_role() @see fsl_cx_db_file_for_role() */ enum fsl_dbrole_e { /** Sentinel "no role" value. @@ -6306,14 +5951,10 @@ /** 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 @@ -6624,11 +6265,11 @@ */ FSL_RC_DIFF_BINARY, /** Triggered by some diff APIs to indicate that only whitespace changes we found and the diff was requested to ignore whitespace. -*/ + */ FSL_RC_DIFF_WS_ONLY, /** Intended to be used with fsl_cx_interrupt() by signal handlers and UI threads. @@ -6679,20 +6320,18 @@ 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. + compatibility between repository versions and it also currently + does no explicit checking to disallow incompatible versions. */ FSL_EXPORT char const * fsl_library_version(); /** - Returns true (non-0) if yourLibVersion compares lexically equal to - FSL_LIBRARY_VERSION, else it returns false (0). It is intended to - be passed the FSL_LIBRARY_VERSION string the client code was built - with. + Returns true (non-0) if yourLibVersion compares lexically + equal to FSL_LIBRARY_VERSION, else it returns false (0). */ FSL_EXPORT bool fsl_library_version_matches(char const * yourLibVersion); /** This type, accessible to clients via the ::fsl_lib_configurable @@ -6727,13 +6366,11 @@ 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. - - TODO: replace this with a FILE pointer. + will be traced to the fsl_output()-configured channel. */ 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. @@ -6918,11 +6555,13 @@ FSL_EXPORT int fsl_cx_err_get( fsl_cx * const f, char const ** str, fsl_size_t * len ); /** Returns f's error state object. This pointer is guaranteed by the API to be stable until f is finalized, but its contents are - modified by many routines as part of the error reporting process. + modified my routines as part of the error reporting process. + + Returns NULL if !f. */ FSL_EXPORT fsl_error const * fsl_cx_err_get_e(fsl_cx const * f); /** Resets's f's error state, basically equivalent to @@ -7039,10 +6678,70 @@ /** va_list counterpart to fsl_outputf(). */ FSL_EXPORT int fsl_outputfv( fsl_cx * const f, char const * fmt, va_list args ); +/** + 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. + + 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() +*/ +FSL_EXPORT int fsl_repo_open( fsl_cx * const f, char const * repoDbFile/*, char readOnlyCurrentlyIgnored*/ ); + +/** + If fsl_repo_open_xxx() has been used to open a respository db, this + call closes that db. + + Returns 0 on success or if no config 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 or + if f still has a checkout opened (a checkout db is only valid in + conjunction with its repository db). + + If a repository is opened "indirectly" via fsl_ckout_open_dir() + then attempting to close it using this function will result in + FSL_RC_MISUSE and f's error state will hold a description of the + problem (the checkout must be closed before closing its + repository). Such a repository will be closed implicitly when the + checkout db is closed. + + @see fsl_repo_open() + @see fsl_repo_create() +*/ +FSL_EXPORT int fsl_repo_close( fsl_cx * const f ); + /** 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, @@ -7082,14 +6781,278 @@ @see fsl_cx_user_guess() */ FSL_EXPORT char const * fsl_cx_user_get( fsl_cx const * const f ); /** - Functionally equivalent to calling fsl_config_close() and - fsl_close_scm_dbs(). + 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. - This will fail if any transactions are pending. Any databases which are + 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. + + The default value (when copy-initialized) is "egg". There's a + story behind the use of "egg" as the initial checkin comment, + and it all started with a typo: "initial chicken" + */ + char const * commitMessage; + + /** + Mime type for the commit message (manifest N-card). Manifests + support this but fossil(1) has never (as of 2021-02) 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". The system users are: 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; + +}; +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 { \ + NULL/*filename*/, \ + NULL/*username*/, \ + "egg"/*commitMessage*/, \ + NULL/*commitMessageMimetype*/, \ + NULL/*configRepo*/, \ + false/*allowOverwrite*/ \ + } + +/** 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. + + 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 char fsl_repo_is_readonly(fsl_cx const * f); + +/** + Tries to open a checked-out fossil repository db in the given + directory. The (dirName, checkParentDirs) parameters are passed on + as-is 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 and opened checkout. + + - FSL_RC_OOM if an allocation fails. + + - FSL_RC_NOT_FOUND if no checkout is foud or if a checkout's + repository is not found. + + - 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. We would need to add the working directory path to the + checkout db's config (`vvar` table), but should otherwise require + no trickery or incompatibilities with fossil(1). +*/ +FSL_EXPORT int fsl_ckout_open_dir( fsl_cx * 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). Wether 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. + +*/ +FSL_EXPORT int fsl_ckout_db_search( char const * dirName, + bool checkParentDirs, + fsl_buffer * const pOut ); + + +/** + If fsl_ckout_open_dir() (or similar) has been used to open a + checkout db, this call closes that db. + + Returns 0 on success or if no config 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. +*/ +FSL_EXPORT int fsl_ckout_close( fsl_cx * const f ); + +/** + Attempts to close any opened databases (repo/checkout/config). This + will fail if any transactions are pending. Any databases which are already closed are silently skipped. This will fail if any cached statements are currently active for the being-closed db(s). "Active" means that fsl_db_prepare_cached() was used without a corresponding call to fsl_stmt_cached_yield(). */ @@ -7145,10 +7108,40 @@ */ FSL_EXPORT char const * fsl_cx_db_file_for_role(fsl_cx const * f, fsl_dbrole_e r, fsl_size_t * len); +/** + Similar to fsl_cx_db_file_ckout() and friends except that it + 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 static and + NUL-terminated. + + 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, which is actually a + transient DB in this API, so it's important to use the correct DB + name when creating such constructs. + + Note that the role of FSL_DBROLE_TEMP is invalid here. +*/ +FSL_EXPORT char const * fsl_cx_db_name_for_role(fsl_cx const * f, + fsl_dbrole_e r, + fsl_size_t * len); + /** If f has an opened checkout db (from fsl_ckout_open_dir()) then 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 @@ -7166,13 +7159,12 @@ 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: + unspecified!), or NULL if !f. 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_transaction_begin() and friends. @@ -7181,24 +7173,20 @@ owning context. Clients MAY add new user-defined functions, use the handle with fsl_db_prepare(), and other "mundane" db-related tasks. - Note that the global config db uses a separate db handle accessible - via fsl_cx_db_config(). - Design notes: The current architecture uses an in-memory db as the "main" db and - attaches the repo and checkout dbs using well-defined names. Even - so, it uses separate fsl_db instances to track each one so that we - "could," if needed, switch back to a multi-db-instance approach if - needed. + attaches the repo, checkout, and config dbs using well-defined + names. Even so, it uses separate fsl_db instances to track each one + so that we "could," if needed, switch back to a multi-db-instance + approach if needed. @see fsl_cx_db_repo() @see fsl_cx_db_ckout() - @see fsl_cx_db_config() */ FSL_EXPORT fsl_db * fsl_cx_db( fsl_cx * const f ); /** If f is not NULL and has had its repo opened via @@ -7255,11 +7243,11 @@ 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. + function returns 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. @@ -7268,48 +7256,45 @@ fsl_config_global_preferred_name()). To get the name of the database after it has been opened/attached, use fsl_cx_db_file_config(). Results are undefined if f is NULL or not properly initialized. + + TODO(?): strongly consider supporting non-attached + (i.e. sqlite3_open()'d) use of the config db. Comments in fossil(1) + suggest that it is possible to lock the config db for other apps + when it is attached to a long-running op by a fossil process. That + change is easier said than done, as it affects many different + functions and rules out any SQL JOINs against the rest of the + repository state (whether any such joins are needed is as yet + unknown). @see fsl_cx_db_config() @see fsl_config_close() @see fsl_config_global_preferred_name() */ FSL_EXPORT int fsl_config_open( fsl_cx * const 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. + fsl_config_open(). Returns 0 on success or if no config + db is opened. It may propagate an error from the db layer + if closing/detaching the db fails. + + ACHTUNG: the config handle cannot be closed if any active + (stepped-but-not-reset) statements are opened on any of f's db + handles because the attached config db will be locked for the + duration of such statements. In such cases, this routine WILL FAIL. @see fsl_cx_db_config() @see fsl_config_open() */ FSL_EXPORT int fsl_config_close( fsl_cx * const 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). + If f has an opened/attached configuration db then its handle is + returned, else 0 is returned. @see fsl_config_open() @see fsl_config_close() */ FSL_EXPORT fsl_db * fsl_cx_db_config( fsl_cx * const f ); @@ -7434,11 +7419,11 @@ may fail. If zName ends with a trailing slash, that slash is retained in nameOut. - This function DOES NOT resolve symlinks, stat()ing the link instead + This function DOES NOT resolve symlinks, stat()nig the link instead of what it points to. @see fsl_cx_stat() */ FSL_EXPORT int fsl_cx_stat2( fsl_cx * const f, bool relativeToCwd, @@ -7447,33 +7432,26 @@ fsl_buffer * const nameOut, bool fullPath); /** - Sets the case-sensitivity flag for f to the given value. This flag - alters how some filename-search/comparison operations operate. This - option is only intended to have an effect on plaforms with - case-insensitive filesystems. - - 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. + 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. @see fsl_cx_is_case_sensitive() */ -FSL_EXPORT void fsl_cx_case_sensitive_set(fsl_cx * const f, bool caseSensitive); +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. + Returns true (non-0) if f is set for case-sensitive filename + handling, else 0. Returns 0 if !f. @see fsl_cx_case_sensitive_set() */ -FSL_EXPORT bool fsl_cx_is_case_sensitive(fsl_cx * const f, bool forceRecheck); +FSL_EXPORT bool fsl_cx_is_case_sensitive(fsl_cx const * f); /** 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. @@ -7673,11 +7651,11 @@ - "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"`. + e.g. `"igore"` 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 @@ -7760,11 +7738,11 @@ /** 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 * const f, fsl_buffer * const pOut); +FSL_EXPORT int fsl_cx_getcwd(fsl_cx * f, fsl_buffer * pOut); /** Returns the same as passing fsl_cx_db() to fsl_db_transaction_level(), or 0 if f has no db opened. @@ -7909,34 +7887,15 @@ FSL_EXPORT int fsl_cx_interruptv(fsl_cx * const 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 + 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 * 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 * const f, bool forceRecheck); - -/** - Closes any opened repository and/or checkout database(s) opened by - f. 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 * const f); - #if 0 /** DO NOT USE - not yet tested and ready. Returns the result of either localtime(clock) or gmtime(clock), @@ -7972,13 +7931,14 @@ #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 */ +#endif +/* ORG_FOSSIL_SCM_FSL_CORE_H_INCLUDED */ +/* end of file ../include/fossil-scm/fossil-core.h */ +/* start of file ../include/fossil-scm/fossil-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 /* @@ -8000,10 +7960,11 @@ /* 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. */ +#include "sqlite3.h" #if defined(__cplusplus) extern "C" { #endif @@ -8024,11 +7985,11 @@ /* extern const fsl_commit_hook fsl_commit_hook_empty; */ /** Potential TODO. */ -FSL_EXPORT int fsl_db_before_commit_hook( fsl_db * const db, fsl_commit_hook_f f, +FSL_EXPORT int fsl_db_before_commit_hook( fsl_db * db, fsl_commit_hook_f f, int sequence, void * state ); #endif #if 0 /* We can't do this because it breaks when clients include both @@ -8067,38 +8028,24 @@ */ FSL_OPEN_F_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_OPEN_F_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_OPEN_F_CREATE. */ FSL_OPEN_F_CREATE = 0x04, /** Shorthand for RW+CREATE flags. */ FSL_OPEN_F_RWC = FSL_OPEN_F_RW | FSL_OPEN_F_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. + Tells fsl_repo_open_xxx() to confirm that the db + is a repository. */ FSL_OPEN_F_SCHEMA_VALIDATE = 0x20, /** - Used by fsl_db_open() to to tell the underlying db connection to + Used by fsl_db_open() to to tell 1the 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_OPEN_F_TRACE_SQL = 0x40 }; @@ -8492,12 +8439,13 @@ */ FSL_EXPORT fsl_stmt * fsl_stmt_malloc(); /** - Behaves like fsl_error_get(), using the db's underlying error - state. Results are undefined if !db. + If db is not NULL this behaves like fsl_error_get(), using the + db's underlying error state. If !db then it returns + FSL_RC_MISUSE. */ FSL_EXPORT int fsl_db_err_get( fsl_db const * const db, char const ** msg, fsl_size_t * len ); /** @@ -8707,30 +8655,24 @@ has already been finalized (but was not freed). */ FSL_EXPORT int fsl_stmt_finalize( fsl_stmt * const 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 + "Steps" the given SQL cursor one time and returns one of the + following: FSL_RC_STEP_ROW, FSL_RC_STEP_DONE, FSL_RC_STEP_ERROR. + 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). + ending iteration or if there is no iteration to perform (e.g. a + UPDATE or INSERT). - 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() */ @@ -8799,20 +8741,20 @@ */ FSL_EXPORT int fsl_stmt_reset( fsl_stmt * const stmt ); /** Returns the db handle which prepared the given statement, or - NULL if stmt has not been prepared. + NULL if !stmt or stmt has not been prepared. */ FSL_EXPORT fsl_db * fsl_stmt_db( fsl_stmt * const 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. + Returns the SQL string used to prepare the given statement, or + NULL if !stmt or 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 * const stmt, fsl_size_t * const len ); /** @@ -8835,14 +8777,13 @@ /** 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. + (e.g. INSERT and UPDATE) have a column count of 0. Some non-SELECT + constructs, e.g. PRAGMA table_info(tname), behave like 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 * const stmt ); @@ -9037,14 +8978,12 @@ (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. + 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_text( fsl_stmt * const stmt, int index, char const **out, fsl_size_t * outLen ); /** @@ -9051,14 +8990,12 @@ 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. + 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_blob( fsl_stmt * const stmt, int index, void const **out, fsl_size_t * outLen ); /** Executes multiple SQL statements, ignoring any results they might @@ -9071,16 +9008,13 @@ va_list counterpart of db_exec_multi(). */ FSL_EXPORT int fsl_db_exec_multiv( fsl_db * const 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). + 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. */ FSL_EXPORT int fsl_db_exec( fsl_db * const db, char const * sql, ... ); /** va_list counterpart of fs_db_exec(). @@ -9134,23 +9068,19 @@ Equivalent to fsl_db_transaction_end(db, 1). */ FSL_EXPORT int fsl_db_transaction_rollback(fsl_db * const db); /** - 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. + Forces a rollback of any pending transaction in db, regardless + of the internal transaction begin/end counter. Returns + FSL_RC_MISUSE if !db or 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 8+ 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 * const db); /** Decrements the transaction counter incremented by @@ -9166,32 +9096,19 @@ doRollback 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 like a rollback even if they pass 0 for the second argument. - 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. - - Unfortunate low-level co-dependency: if db->f is not NULL then this - function may perform extra repository-related post-processing on - any commit, and checking the result code is particularly important - for those cases. - - Sidebar: this APIs pseudo-nested transaction support was initially - a direct port of that from fossil(1). sqlite3 added SAVEPOINT - support, which is essentially named, nested transaction, much later - on. That support may have been a better basis for this API, but it - didn't exist at the time and an overhaul would be both time-consuming - and risk all sorts of new bugs. - - SAVEPOINTS: https://sqlite.org/lang_savepoint.html - - Though this API does not prohibit the use of savepoints (like it - does direct use of BEGIN/COMMIT/ROLLBACK from SQL code), it is - untested with them and undesired side effects vis a vis this API's - transaction support cannot be entirely ruled out. + Returns FSL_RC_MISUSE if !db or the db is not opened, 0 if + the transaction counter is above 0, else the result of the + (potentially many) underlying database operations. + + Unfortunate low-level co-dependency: if db->f is not NULL and + (db->role & FSL_DBROLE_REPO) then this function may perform + extra repository-related post-processing on any commit, and + checking the result code is particularly important for those + cases. */ FSL_EXPORT int fsl_db_transaction_end(fsl_db * const db, bool doRollback); /** Returns the given db's current transaction depth. If the value is @@ -9249,93 +9166,92 @@ /** The int64 counterpart of fsl_db_get_int32(). See that function for the semantics. */ -FSL_EXPORT int fsl_db_get_int64( fsl_db * const db, int64_t * rv, +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 * const db, int64_t * rv, +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 * const db, int64_t defaultValue, +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 * const db, fsl_id_t * rv, +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 * const db, fsl_id_t * rv, +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 * const db, fsl_id_t defaultValue, +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 * const db, fsl_size_t * rv, +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 * const db, fsl_size_t * rv, +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 * const db, - fsl_size_t defaultValue, - char const * sql, ... ); +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 * const db, double * rv, +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 * const db, double * rv, +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 * const db, double defaultValue, +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 @@ -9344,17 +9260,17 @@ 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 * const db, char ** rv, fsl_size_t * rvLen, +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 * const db, char ** rv, fsl_size_t * rvLen, +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, @@ -9361,11 +9277,11 @@ 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 * const db, fsl_size_t * len, +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 @@ -9376,49 +9292,49 @@ 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 * const db, void ** rv, fsl_size_t * len, +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 * const db, void ** rv, fsl_size_t * stmtLen, +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 * const db, fsl_size_t * len, +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, overwriting (not appending to) any existing + its result to tgt, overwriting (not appennding to) any existing memory it might hold. 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. */ -FSL_EXPORT int fsl_db_get_buffer( fsl_db * const db, fsl_buffer * const tgt, - bool asBlob, char const * sql, - ... ); +FSL_EXPORT int fsl_db_get_buffer( fsl_db * db, fsl_buffer * tgt, + char asBlob, + char const * sql, ... ); /** va_list counterpart of fsl_db_get_buffer(). */ -FSL_EXPORT int fsl_db_get_bufferv( fsl_db * const db, fsl_buffer * const tgt, - bool asBlob, char const * sql, - va_list args ); +FSL_EXPORT int fsl_db_get_bufferv( fsl_db * db, fsl_buffer * tgt, + char 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 @@ -9426,20 +9342,20 @@ 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, + Returns FSL_RC_MISUSE if !db, db is not opened, !callback, !sql. Returns FSL_RC_RANGE if !*sql. */ -FSL_EXPORT int fsl_db_each( fsl_db * const db, fsl_stmt_each_f callback, +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 * const db, fsl_stmt_each_f callback, +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 @@ -9478,11 +9394,11 @@ /** 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 * const db); +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: @@ -9493,11 +9409,11 @@ 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 * const db, char const * str); +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 @@ -9547,12 +9463,17 @@ db is validated to see if it has a fossil schema. If that validation fails, FSL_RC_REPO_NEEDS_REBUILD or FSL_RC_NOT_A_REPO will be returned and db's error state will be updated. db->f does not need to be set for that check to work. - If db->f is not NULL when this function is called then any error - triggered during opening is _copied_ into db->f's error state. + + If db->f is not NULL when this function is called then a number of + fossil-specific SQL-accessible functions are installed. See the + file doc/db-udf.md in the libfossil source tree for complete + docs. Note that functions in those docs described as "triggering a + db error" will propagate that error, such that fsl_db_err_get() can + report it to the client. @see fsl_db_close() @see fsl_db_prepare() @see fsl_db_malloc() */ @@ -9559,12 +9480,11 @@ FSL_EXPORT int fsl_db_open( fsl_db * const db, char const * dbFile, int openFlags ); /** Closes the given db handle and frees any resources owned by - db. Results are undefined if db is NULL. If db is not opened, - this is a harmless no-op. + db. This 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. @@ -9586,20 +9506,11 @@ As a special case, if db->f is not NULL _before_ it is is fsl_db_open()ed, then this function automatically gets installed if the SQL tracing option is enabled for that fsl_cx instance before the db is opened. - This is a no-op if db is not opened. - - 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). + This is a no-op if !db or db is not opened. */ FSL_EXPORT void fsl_db_sqltrace_enable( fsl_db * const db, FILE * outStream ); /** Returns the row ID of the most recent insertion, @@ -9627,14 +9538,15 @@ /** 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. + returns NULL (or asserts in debug builds) 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); +FSL_EXPORT const char * fsl_db_role_label(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 @@ -9678,11 +9590,11 @@ /** 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 + Returns 0 on success, FSL_RC_MISUSE if !db, !tgt, or !fmt, 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. @@ -9714,41 +9626,43 @@ 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 * const db, fsl_list * const tgt, +FSL_EXPORT int fsl_db_select_slist( fsl_db * const 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 * const db, fsl_list * const tgt, +FSL_EXPORT int fsl_db_select_slistv( fsl_db * const 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_free(). Returns NULL if !db, !n, or on a db-level error. */ -FSL_EXPORT char * fsl_db_random_hex(fsl_db * const db, fsl_size_t n); +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. + 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 or if db is not + opened. See: https://sqlite.org/c3ref/changes.html */ FSL_EXPORT int fsl_db_changes_recent(fsl_db * const 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. + quote the underlying APIs). Returns 0 if !db or if db is not + opened. See; https://sqlite.org/c3ref/total_changes.html */ FSL_EXPORT int fsl_db_changes_total(fsl_db * const db); @@ -9873,12 +9787,12 @@ #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 */ +/* end of file ../include/fossil-scm/fossil-db.h */ +/* start of file ../include/fossil-scm/fossil-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 /* @@ -10415,12 +10329,12 @@ #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 */ +/* end of file ../include/fossil-scm/fossil-hash.h */ +/* start of file ../include/fossil-scm/fossil-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 /* @@ -10432,11 +10346,11 @@ SPDX-FileType: Code Heavily indebted to the Fossil SCM project (https://fossil-scm.org). */ -/** @file repo.h +/** @file fossil-repo.h fossil-repo.h declares APIs specifically dealing with repository-db-side state, as opposed to specifically checkout-side state or non-content-related APIs. */ @@ -10451,50 +10365,10 @@ 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; - -/** - 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. - - 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 * const f, char const * repoDbFile/*, char readOnlyCurrentlyIgnored*/ ); - /** This function is a programmatic interpretation of this table: https://fossil-scm.org/index.html/doc/trunk/www/fileformat.wiki#summary @@ -10625,11 +10499,11 @@ 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. + This pointer may change any time the list is reallocated.a */ fsl_card_F * list; /** The number of entries in this->list which are in use. */ @@ -11207,20 +11081,10 @@ 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). @@ -11227,40 +11091,38 @@ @see fsl_deck_F_set() @see fsl_deck_F_add() @see fsl_deck_derive() */ -FSL_EXPORT int fsl_deck_F_set_content( fsl_deck * const d, char const * name, - fsl_buffer const * const src, +FSL_EXPORT int fsl_deck_F_set_content( fsl_deck * d, char const * name, + fsl_buffer const * src, fsl_fileperm_e perm, char const * priorName); /** UNDER CONSTRUCTION! EXPERIMENTAL! 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. + version of itself. Requires that d be a loaded + from a repository, complete with a UUID and an RID, else + FSL_RC_MISUSE is returned. In short, this function peforms the following: - Clears d->P - - Assigns d->P[0] to the UUID of d->rid + - Moves d->uuid into d->P - 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 baselin - (see below). + child/derived version. - 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 (fixing that for 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(). + was not loaded from the db. If d->type is not FSL_SATYPE_CHECKIN, + FSL_RC_TYPE is returned. 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 checkin. @@ -11268,18 +11130,11 @@ 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. + 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 * const d); @@ -11307,13 +11162,12 @@ 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 * const d, - fsl_card_F_visitor_f cb, - void * const visitorState ); +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), @@ -11426,11 +11280,11 @@ 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_buffer * const dest ); + fsl_buffer * dest ); /** Sets the 'G' card on a forum-post deck to a copy of the given UUID. */ @@ -11460,19 +11314,17 @@ Returns 0 on success, FSL_RC_MISUSE if !mf or !key, FSL_RC_RANGE if !*field, 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 * const mf, bool isAppend, +FSL_EXPORT int fsl_deck_J_add( fsl_deck * const mf, char 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. + Semantically identical fsl_deck_B_set() but sets the K-card and + does not accept a NULL value. uuid must be the UUID of the ticket + this change is being applied to. */ FSL_EXPORT int fsl_deck_K_set( fsl_deck * const mf, fsl_uuid_cstr uuid); /** Semantically identical fsl_deck_B_set() but sets the L-card. @@ -11563,18 +11415,18 @@ this function returns FSL_RC_RANGE. 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 + Returns 0 on success. Returns FSL_RC_MISUE if !mf or + !name. Returns FSL_RC_TYPE (and update's mf's error state with a + message) if the T card is not legal for mf (see fsl_card_is_legal()). Returns FSL_RC_RANGE if !*name, tagType is invalid, or if uuid is not NULL and fsl_is_uuid(uuid) return false. Returns FSL_RC_OOM if an allocation fails. */ -FSL_EXPORT int fsl_deck_T_add( fsl_deck * const d, fsl_tagtype_e tagType, +FSL_EXPORT int fsl_deck_T_add( fsl_deck * const mf, fsl_tagtype_e tagType, fsl_uuid_cstr uuid, char const * name, char const * value); /** Adds the given tag instance to the given manifest. @@ -11594,18 +11446,12 @@ 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 natively 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 cancelation 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 * const d, char const * branchName ); +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). @@ -11626,11 +11472,11 @@ 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 * const d); +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: @@ -11767,20 +11613,17 @@ integrity-related checks, and is somewhat superfluous. @see fsl_deck_output() @see fsl_deck_save() */ -FSL_EXPORT int fsl_deck_unshuffle( fsl_deck * const d, bool calculateRCard ); +FSL_EXPORT int fsl_deck_unshuffle( fsl_deck * d, bool calculateRCard ); /** Renders the given control 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, @@ -11797,17 +11640,17 @@ 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 + mf->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 * const d, fsl_output_f out, +FSL_EXPORT int fsl_deck_output( fsl_deck * d, fsl_output_f out, void * outputState ); /** Saves the given deck into f's repository database as new control @@ -11934,46 +11777,24 @@ 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. Note that fossil's 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 - not an artifact). - - 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 + - FSL_RC_SYNTAX on syntax errors. + + - FSL_RC_CONSISTENCY if validation of a Z-card fails. - Any number of errors coming from the allocator, database, or - fsl_deck APIs used here. + 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 * const d, fsl_buffer * const src); /** @@ -11992,12 +11813,12 @@ /** 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 + 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_buffer const * const src); @@ -12120,15 +11941,15 @@ - Iterating over F-cards, which requires calling fsl_deck_F_rewind() before doing so. - Loading a checkin's baseline (required for F-card iteration and - performed automatically by fsl_deck_F_rewind()). + 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. + undergoing crosslinking. It is legal to modify its error state. 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. @@ -12136,18 +11957,14 @@ @see fsl_xlink_listener() */ typedef int (*fsl_deck_xlink_f)(fsl_deck * const d, void * state); /** - A type for holding state for artifact crosslinking callbacks. + A type for holding a callback/state pair for manifest + 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; @@ -12226,23 +12043,16 @@ 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() + 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 @@ -12265,20 +12075,10 @@ - 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 @@ -12318,11 +12118,11 @@ catastrophe). @see fsl_content_blob() @see fsl_content_get() */ -FSL_EXPORT fsl_int_t fsl_content_size( fsl_cx * const f, fsl_id_t blobRid ); +FSL_EXPORT fsl_int_t fsl_content_size( fsl_cx * f, fsl_id_t blobRid ); /** 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 @@ -12430,11 +12230,11 @@ @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 * const f, fsl_deck_visitor_f cb, void * state ); +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 @@ -12448,11 +12248,11 @@ @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 * const f, char const * pageName, fsl_id_t * const newRid ); +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. @@ -12464,11 +12264,11 @@ @see fsl_wiki_latest_rid() @see fsl_wiki_names_get() @see fsl_wiki_page_exists() */ -FSL_EXPORT int fsl_wiki_load_latest( fsl_cx * const f, char const * pageName, fsl_deck * d ); +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. @@ -12475,11 +12275,11 @@ @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 * const f, char const * pageName); +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. */ @@ -12638,11 +12438,11 @@ 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; + char append; /** For internal use only. */ unsigned char flags; /** @@ -12653,11 +12453,11 @@ 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} +#define fsl_card_J_empty_m {0,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. @@ -12832,22 +12632,21 @@ 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. + Returns non-0 on error, FSL_RC_MISUSE if !f, !tgt. On other + errors error tgt might have been partially populated and the + list contents should not be considered valid/complete. 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 * const f, fsl_id_t rid, - fsl_list * const tgt, bool addSlash ); +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 @@ -12855,37 +12654,38 @@ 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. + If progressVisitor is not NULL then it is called once just + before each file is processed, passed the F-card for the file + about to be zipped and the progressState parameter. If it + returns non-0, ZIPping is cancelled and that error code is + returned. This is intended primarily for providing feedback on + the update process, but could also be used to cancel the + operation between files. As of 2021-09-05 this routine automatically adds the files (manifest, manifest.uuid, manifest.tags) to the zip file, regardless of repository-level settings regarding those pseudo-files (see fsl_ckout_manifest_write()). As there are no F-cards associated with those non-files, the progressVisitor is not called for those. - BUG/FIXME: this function does not honor symlink content in a - fossil-compatible fashion. If it encounters a symlink entry during - ZIP generation, it will fail and f's error state will be updated - with an explanation of this shortcoming. + BUG: this function does not honor symlink content in a + fossil-compatible fashion. If it encounters a symlink entry + during ZIP generation, it will fail and f's error state will be + updated with an explanation of this shortcoming. @see fsl_zip_writer @see fsl_card_F_visitor_f() */ -FSL_EXPORT int fsl_repo_zip_sym_to_filename( fsl_cx * const f, char const * sym, - char const * vRootDir, - char const * fileName, - fsl_card_F_visitor_f progressVisitor, - void * progressState); +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 file's, one file at a @@ -13041,11 +12841,11 @@ 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, + Extracts the contents of a single checkin from 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, @@ -13057,29 +12857,33 @@ 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. + + Files deleted by the given version are NOT reported to the callback + (because getting sane semantics has proven to be tricker and more + costly than it's worth). 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. Note that upper-case letters + Fossil's internal metadata format guarantees that files will passed + 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. Note 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 * const f, - fsl_repo_extract_opt const * const opt ); +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. @@ -13183,15 +12987,13 @@ 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_src_id( fsl_cx * const f, fsl_id_t deltaRid, - fsl_id_t * const rv ); + fsl_id_t * rv ); /** Return true if the given artifact ID should is listed in f's shun table, else false. @@ -13222,22 +13024,20 @@ 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 * const f, fsl_id_t vid, fsl_id_t fid, - fsl_time_t * const pMTime); +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 * const f, fsl_id_t vid, fsl_card_F const * const fc, - fsl_time_t * const pMTime); +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 the capacity is currently equal to or less than n, this is a no-op unless n is 0, in which case li->list is freed and the list is @@ -13287,11 +13087,11 @@ */ double mtime; /** If true, the branch will be marked as private. */ - bool isPrivate; + char isPrivate; }; typedef struct fsl_branch_opt fsl_branch_opt; #define fsl_branch_opt_empty_m { \ 0/*basisRid*/, NULL/*name*/, \ NULL/*user*/, NULL/*comment*/, \ @@ -13622,12 +13422,11 @@ If FSL_RC_NOT_FOUND is returned and hashOut is not NULL, *hashOut is set to the value of f's preferred hash. *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 * const f, fsl_buffer const * const src, - fsl_id_t * const ridOut, +FSL_EXPORT int fsl_repo_blob_lookup( fsl_cx * f, fsl_buffer 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. @@ -13671,19 +13470,19 @@ 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. + TODO/FIXME: if f's 'manifest' config setting is set to true AND + zPath refers to the top of the checkout root, treat the files + (manifest, manifest.uuid, manifest.tags) as reserved. If it is a + string with any of the letters "r", "u", or "t", check only the + file(s) which those letters represent (see + add.c:fossil_reserved_name() in fossil). Apply these only at the top + of the tree - allow them in subdirectories. */ -FSL_EXPORT int fsl_reserved_fn_check(fsl_cx * const f, const char *zPath, +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 @@ -13690,14 +13489,14 @@ "just in case," here it is. 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. + Returns 0 on success. Error may indicate that f has no repo db + opened. On error f's error state may be updated. */ -FSL_EXPORT int fsl_repo_leaves_rebuild(fsl_cx * const f); +FSL_EXPORT int fsl_repo_leaves_rebuild(fsl_cx * f); /** Flags for use with fsl_leaves_compute(). */ enum fsl_leaves_compute_e { @@ -13739,11 +13538,11 @@ @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 * const f, fsl_id_t vid, +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. @@ -13750,11 +13549,11 @@ 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 * const f); +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. @@ -13761,11 +13560,11 @@ 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 * const f); +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. @@ -13773,18 +13572,18 @@ 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 * const f); +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 * const f); +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 @@ -13794,11 +13593,11 @@ those which are injected into the db via lower-level means (e.g. a direct blob import or from a remote sync). Results are undefined if f has no opened repository. */ -FSL_EXPORT bool fsl_repo_forbids_delta_manifests(fsl_cx * const f); +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 @@ -13811,11 +13610,11 @@ 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 * const f, +FSL_EXPORT int fsl_repo_manifest_write(fsl_cx *f, fsl_id_t manifestRid, fsl_buffer * const manifest, fsl_buffer * const manifestUuid, fsl_buffer * const manifestTags ); @@ -13981,10 +13780,14 @@ and originRid. */ fsl_id_t originRid; /** The maximum number of versions to search through. + + Note that fossil(1) offers the ability to limit the calculation + based on processing time, e.g. to 1500ms. We may or may not add + that in this library. */ uint32_t limitVersions; /** An approximate number of milliseconds of processing time to limit @@ -14164,20 +13967,21 @@ 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. + the library's code). + + NOT YET IMPLEMENTED. */ bool randomize; /** True if clusters should be created. NOT YET IMPLEMENTED. */ - bool createClusters; + bool clustering; /** If true, the transaction started by the rebuild process will end in a rollback even on success. In that case, if a transaction is started before the rebuild is initiated, it will be left in the rolling-back state after rebuild completes. @@ -14195,15 +13999,16 @@ void * callbackState; }; /** Initialized-with-defaults fsl_rebuild_opt structure, intended for const-copy initialization. */ -#define fsl_rebuild_opt_empty_m {false,false,false,NULL,NULL} +#define fsl_rebuild_opt_empty_m {false,false,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: @@ -14249,429 +14054,17 @@ flag is _not_ set on f, this routine _will fail_ if it encounters any ticket artifacts. */ FSL_EXPORT int fsl_repo_rebuild(fsl_cx * const f, fsl_rebuild_opt const * const opt); -/** - 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" is 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. 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 * const f, fsl_int_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} - -/** 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 * const f, fsl_cidiff_opt const * 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. - - The default value (when copy-initialized) is "egg". There's a - story behind the use of "egg" as the initial checkin comment, - and it all started with a typo: "initial chicken" - */ - char const * commitMessage; - - /** - Mime type for the commit message (manifest N-card). Manifests - support this but fossil(1) has never (as of 2021-02) 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". The system users are: 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; - -}; -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 { \ - NULL/*filename*/, \ - NULL/*username*/, \ - "egg"/*commitMessage*/, \ - NULL/*commitMessageMimetype*/, \ - NULL/*configRepo*/, \ - false/*allowOverwrite*/ \ - } - -/** 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. - - 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 char fsl_repo_is_readonly(fsl_cx const * f); - #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 */ +/* end of file ../include/fossil-scm/fossil-repo.h */ +/* start of file ../include/fossil-scm/fossil-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 /* @@ -14683,11 +14076,11 @@ SPDX-FileType: Code Heavily indebted to the Fossil SCM project (https://fossil-scm.org). */ -/** @file checkout.h +/** @file fossil-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. */ @@ -14696,98 +14089,10 @@ #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 and opened checkout. - - - FSL_RC_OOM if an allocation fails. - - - FSL_RC_NOT_FOUND if no checkout is foud or if a checkout's - repository is not found. - - - 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_buffer * const pOut ); - /** Returns version information for the current checkout. If f has an opened checkout then... @@ -14808,15 +14113,15 @@ */ FSL_EXPORT void fsl_ckout_version_info(fsl_cx * const f, fsl_id_t * const rid, fsl_uuid_cstr * const uuid ); /** - Given a fsl_cx with an opened checkout, and a file/directory name, - this function canonicalizes zOrigName to a form suitable for use as + Given a fsl_cx with an opened checkout, and a filename, this + function canonicalizes zOrigName to a form suitable for use as an in-repo filename, _appending_ the results to pOut. If pOut is - NULL, it performs its normal checking but does not write a result, - other than to return 0 for success. + 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. @@ -14845,79 +14150,33 @@ 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_buffer * 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_buffer_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; +FSL_EXPORT int fsl_ckout_filename_check( fsl_cx * f, bool relativeToCwd, + char const * zOrigName, fsl_buffer * pOut ); /** Callback type for use with fsl_ckout_manage_opt(). It should - inspect the given (`mst->filename`) using whatever criteria it likes, set + inspect the given 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. + come from the FSL_RC_xxx family. 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); +typedef int (*fsl_ckout_manage_f)(const char *zFilename, + bool *include, + void *state); /** Options for use with fsl_ckout_manage(). */ struct fsl_ckout_manage_opt { /** @@ -14999,10 +14258,11 @@ - The client-provided callback says not to include the file. */ uint32_t skipped; } counts; }; +typedef struct fsl_ckout_manage_opt fsl_ckout_manage_opt; /** Initialized-with-defaults fsl_ckout_manage_opt instance, intended for use in const-copy initialization. */ #define fsl_ckout_manage_opt_empty_m {\ @@ -15047,82 +14307,35 @@ 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_buffer_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. - ``` - */ - 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); + 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. + + It will be passed a name which is 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 + + The final argument is not used by the library, but is passed on + as-is from the callbackState pointer which + is passed to fsl_ckout_unmanage(). +*/ +typedef int (*fsl_ckout_unmanage_f)(const char *zFilename, void *state); /** Options for use with fsl_ckout_unmanage(). */ struct fsl_ckout_unmanage_opt { @@ -15169,11 +14382,13 @@ fsl_ckout_unmanage_f callback; /** State to be passed to this->callback. */ void * callbackState; + }; +typedef struct fsl_ckout_unmanage_opt fsl_ckout_unmanage_opt; /** Initialized-with-defaults fsl_ckout_unmanage_opt instance, intended for use in const-copy initialization. */ #define fsl_ckout_unmanage_opt_empty_m {\ @@ -15645,20 +14860,20 @@ @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); +FSL_EXPORT int fsl_checkin_dequeue(fsl_cx * 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. + Returns true (non-0) 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. @@ -15672,19 +14887,16 @@ 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, +FSL_EXPORT bool fsl_checkin_is_enqueued(fsl_cx * f, char const * zName, bool relativeToCwd); /** Discards any state accumulated for a pending checking, including any files queued via fsl_checkin_enqueue() @@ -15694,11 +14906,11 @@ @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); +FSL_EXPORT void fsl_checkin_discard(fsl_cx * f); /** Parameters for fsl_checkin_commit(). Checkins are created in a multi-step process: @@ -16182,14 +15394,15 @@ fsl_repo_open_ckout_opt instances for sane default values. */ FSL_EXPORT const fsl_repo_open_ckout_opt fsl_repo_open_ckout_opt_empty; /** + Work in progress... + 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. + or creates a new one. 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. @@ -16207,12 +15420,11 @@ - 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 ); +FSL_EXPORT int fsl_repo_open_ckout( fsl_cx * 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 @@ -16269,11 +15481,11 @@ 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 +/** Special case of FSL_CKUP_FCHANGE_UPDATED. Merge was performed and conflicts were detected. The newly-updated file will contain conflict markers. @see fsl_buffer_contains_merge_marker() */ @@ -16293,25 +15505,16 @@ 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 + 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 @@ -16587,11 +15790,11 @@ 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() + @see fsl_repo_ckout_open() */ FSL_EXPORT int fsl_repo_ckout(fsl_cx * f, fsl_ckup_opt const * cOpt); /** @@ -16642,15 +15845,12 @@ /** 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; /** @@ -16732,15 +15932,15 @@ 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, +FSL_EXPORT int fsl_ckout_manifest_write(fsl_cx *f, int manifest, int manifestUuid, int manifestTags, - int * const wroteWhat ); + int *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 @@ -16748,19 +15948,19 @@ 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); +FSL_EXPORT bool fsl_is_rooted_in_ckout(fsl_cx *f, char 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); +FSL_EXPORT int fsl_is_rooted_in_ckout2(fsl_cx *f, char const *zAbsPath); /** Change-type values for use with fsl_ckout_revert_f() callbacks. */ enum fsl_ckout_revert_e { @@ -16980,23 +16180,17 @@ 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 + 2) 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. + Returns 0 on success, 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_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 ); @@ -17103,11 +16297,11 @@ 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); +FSL_EXPORT int fsl_ckout_fingerprint_check(fsl_cx * f); /** Looks for the given file in f's current checkout. If relativeToCwd then the name is resolved from the current directory, otherwise it is assumed to be relative to the checkout root or an absolute path @@ -17132,11 +16326,11 @@ /** 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. + 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. @@ -17156,249 +16350,64 @@ FSL_EXPORT int fsl_card_F_ckout_mtime(fsl_cx * const f, fsl_id_t vid, fsl_card_F const * const fc, fsl_time_t * repoMtime, fsl_time_t * localMtime); -/** - 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_buffer_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, -/** - Indicates that the given file cannot be merged because no common - ancestor can be found for it. This condition is not strictly fatal - but does indicate a problem with the input data. Merging will - continue unless the fsl_merge_f() to which this is reported returns - non-0 to cancel it. This particular status is reported very early - in the fsl_ckout_merge() process, before any files have been - written by the merge, thus the callback can effectively abort the - merge without side-effects by returning non-0 if this status is - reported to it. If the fsl_ckout_merge() call has no callback set, - this case will go silently undiagnosed! - - Potential TODO: add a flag to fsl_merge_opt to tell it to treat any - of these cases as merge-fatal. -*/ -FSL_MERGE_FCHANGE_CONFLICT_ANCESTOR, -/** - 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. - */ + State to be passed to this->callback via the + fsl_merge_state::callbackState member. + */ + void * callbackState; + + fsl_ckup_fchange_e fileChangeType; + fsl_ckup_rm_state_e fileRmInfo; }; typedef struct fsl_merge_state fsl_merge_state; +/** + Callback type for use with fsl_merge_opt and fsl_merge(). -/** - Callback type for use with fsl_merge_opt and fsl_ckout_merge(). + TODO: figure out whether we can use fsl_ckout_state for this or + whether we need a new type. Merge and update are quite similar, so + the current thinking is that we can recycling this. */ 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, +FSL_MERGE_TYPE_NORMAL, /** 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: + Certain merge-time state will force this merge type to 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, +FSL_MERGE_TYPE_INTEGRATE, /** Indicates a cherrypick merge, pulling in only the changes made to a specific checkin without otherwise inheriting its lineage. */ -FSL_MERGE_TYPE_CHERRYPICK = -1, +FSL_MERGE_TYPE_CHERRYPICK, /** Indicates a backout merge, a reverse cherrypick, backing out any - changes which were added by the corresponding - fsl_merge_opt::mergeRid. + changes which were added by this->checkinRid. */ -FSL_MERGE_TYPE_BACKOUT = -2 +FSL_MERGE_TYPE_BACKOUT }; typedef enum fsl_merge_type_e fsl_merge_type_e; /** UNDER CONSTRUCTION. @@ -17406,73 +16415,59 @@ 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. + 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. + This corresponds to fossil(1)'s --baseline merge flag. */ 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. + Specifies the merge type to perform. */ 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. + metadata. May be NULL. */ fsl_merge_f callback; /** - Client-defined state for use with this->callback. + State to be passed to this->callback via the + fsl_merge_state::callbackState member. */ 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, + A hint to fsl_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. + fsl_merge(), as that function require a non-stale changes scan in + order to function properly. */ bool scanForChanges; + /** + If true, on merge conflict retain the temporary files used for + mergin: `*-baseline`, `*-original`, and `*-merge`. By default + these are removed because they're very rarely useful. + */ + bool keepMergeFiles; /** 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. + 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; + /** 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; @@ -17479,42 +16474,42 @@ /** 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. */ }; +/** Convenience typedef. */ +typedef struct fsl_merge_opt fsl_merge_opt; /** 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*/, \ + true/*scanForChanges*/, false/*keepMergeFiles*/, \ 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. + UNDER CONSTRUCTION and NOT YET IMPLEMENTED for the foreseeable + future. 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_: + 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_TYPE if opt->mergeRid does 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 @@ -17527,54 +16522,25 @@ - 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. - + For most errors, f's error state will be updated with a description + of the problem. + + Reminder: there are certain illegal combinations of merge state + which may require adding new result codes for. e.g. a no-op merge. */ 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); - #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/confdb.h */ +/* end of file ../include/fossil-scm/fossil-checkout.h */ +/* start of file ../include/fossil-scm/fossil-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 /* @@ -17585,11 +16551,11 @@ SPDX-ArtifactOfProjectName: Libfossil SPDX-FileType: Code Heavily indebted to the Fossil SCM project (https://fossil-scm.org). */ -/** @file confdb.h +/** @file fossil-confdb.h fossil-confdb.h declares APIs dealing with fossil's various configuration option storage backends. */ @@ -17612,16 +16578,10 @@ 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. */ @@ -18055,12 +17015,12 @@ #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 */ +/* end of file ../include/fossil-scm/fossil-confdb.h */ +/* start of file ../include/fossil-scm/fossil-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 /* @@ -18294,12 +17254,12 @@ #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/internal.h */ +/* end of file ../include/fossil-scm/fossil-vpath.h */ +/* start of file ../include/fossil-scm/fossil-internal.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_INTERNAL_H_INCLUDED) #define ORG_FOSSIL_SCM_FSL_INTERNAL_H_INCLUDED /* @@ -18474,12 +17434,11 @@ /** List of cached content, ordered by age. */ fsl__bccache_line * list; /** - RIDs of all artifacts currently in the this->list - cache. + RIDs of all artifacts currently in the cache. */ fsl_id_bag inCache; /** RIDs of known-missing content. */ @@ -18580,70 +17539,70 @@ 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 knowble. - 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 parter is opened, it is ATTACHed to dbMain. - dbMain->role holds a bitmask of fsl_dbrole_e values reflecing - 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 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.) - - 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). + As of this writing (20141027, updated 20211018) the following + applies: + + dbMain always points to &this->dbMem (a temp or ":memory:" + (unspecified!) db opened by fsl_cx_init()), and the + repo/ckout/config DBs get ATTACHed to that one. Their separate + handles (this->{repo,ckout,config}.db) are used to store the name + and file path to each one (even though they have no real db + handle associated with them). 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). + get a handle to the specific db they want. Currently they will + always return NULL or the same handle, but that design decision + might change at some point, so the public API treats them as + separate entities. _That said_: at this point (2021-10-18), + treating them as separate handles often proves to be annoying in + their usage, and newer code will sometimes use (e.g.) + fsl_cx_prepare() in lieu of explicitely using fsl_db_prepare() + with the ostensibly db-specific handle when it knows that the + required db is indeed attached. In other words: the internals, in + some places, are starting to rely on this long-established + convention of having a single sqlite3 object and multiple + attached databases, _and that's okay_. */ fsl_db * dbMain; /** Marker which tells us whether fsl_cx_finalize() needs to fsl_free() this instance or not. */ void const * allocStamp; + /** + A ":memory:" (or "") db to work around + open-vs-attach-vs-main-vs-real-name problems wrt to the + repo/ckout/config dbs. This db handle gets opened automatically + at startup and all others which a fsl_cx manages get ATTACHed to + it. Thus the other internal fsl_db objects, e.g. this->repo.db, + may hold state, such as the path to the current repo db, but they + do NOT hold an sqlite3 db handle. Assigning them the handle of + this->dbMain would indeed simplify certain work but it would + require special care to ensure that we never sqlite3_close() + those out from under this->dbMain. + */ + fsl_db dbMem; + /** Holds info directly related to a checkout database. */ struct { /** Holds the filename of the current checkout db and possibly - related state. + related state. Historically (very historically) it could also + be the `main` db, but that is no longer the case. */ fsl_db db; /** - The directory part of an opened checkout db. This is currently + 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). @@ -18651,11 +17610,11 @@ 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. + dir's length if dir is not NULL. */ 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. @@ -18677,11 +17636,12 @@ Holds info directly related to a repo database. */ struct { /** Holds the filename of the current repo db and possibly related - state. + state. Historically (very historically) it could also be the + `main` db, but that is no longer the case. */ fsl_db db; /** The default user name, for operations which need one. See fsl_cx_user_set(). @@ -18693,21 +17653,18 @@ Holds info directly related to a global config database. */ struct { /** Holds the filename of the current global config db and possibly - related state. 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. + related state. Historically (very historically) it could also + be the `main` db, but that is no longer the case. */ fsl_db db; } config; /** - State for incrementally preparing a checkin operation. + State for incrementally proparing a checkin operation. */ struct { /** Holds a list of "selected files" in the form of vfile.id values. @@ -18731,17 +17688,10 @@ 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 argue for one. */ fsl_outputer output; /** Can be used to tie client-specific data to the context. Its @@ -18762,15 +17712,25 @@ set this should denote it with a comment like "updates the context's error state on error." */ fsl_error error; + /** + 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. + */ + fsl_buffer fileContent; + /** Reuseable scratchpads for low-level file canonicalization buffering and whatnot. Not intended for huge content: use this->fileContent for that. This list should stay relatively - short, as should the buffers (a few kb each, at most). + short. @see fsl__cx_scratchpad() @see fsl__cx_scratchpad_yield() */ struct { @@ -18786,11 +17746,11 @@ 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 + fatally if it needs more than it has, so we won't fail to overlook such a case. */ fsl_buffer buf[8]; /** Flags telling us which of this->buf is currenly in use. @@ -18818,13 +17778,11 @@ int 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. + long-running operation. Not all operations honor this check. */ volatile int interrupted; /** List of callbacks for deck crosslinking purposes. @@ -18833,10 +17791,16 @@ /** A place for caching generic things. */ struct { + /** + If true, SOME repository-level file-name comparisons/searches + will work case-insensitively. + */ + bool caseInsensitive; + /** 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. @@ -18843,12 +17807,12 @@ */ 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. + private. This flag is used for communicating this flag through + multiple levels of API. */ bool markPrivate; /** True if fsl__crosslink_begin() has been called but @@ -18867,17 +17831,10 @@ Is used to tell the content-save internals that a "final verification" (a.k.a. verify-before-commit) is underway. */ bool inFinalVerify; - /** - 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 @@ -18900,11 +17857,11 @@ 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 its otherwise prohibited, e.g. by the - `forbid-delta-manifests` config db setting. + 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 @@ -18920,11 +17877,11 @@ index. <0=undetermined, 0=no, >0=yes. */ short searchIndexExists; /** - Cache for the `manifest` config setting, as used by + 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; @@ -18933,27 +17890,10 @@ Record ID of rcvfrom entry during commits. This is likely to remain unused in libf until/unless the sync protocol is implemented. */ 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. - */ - fsl_buffer 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_buffer deltaContent; /** fsl_content_get() cache. */ fsl__bccache blobContent; @@ -18978,20 +17918,20 @@ 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. We do not currently (2022-01) + The "project-code" config option. We do not currently (2021-03) use this but it will be important if/when the sync protocol is implemented or we want to create hashes, e.g. for user passwords, which depend in part on the project code. */ char * projectCode; /** - Internal optimization to avoid duplicate fsl_stat() calls - across two functions in some cases. + Internal optimization to avoid duplicate stat() calls across + two functions in some cases. */ fsl_fstat fstat; /** Parsed-deck cache. @@ -19021,45 +17961,10 @@ /** Holds the "crnl-glob" globs. */ fsl_list crnl; } globs; - - /** - Very-frequently-used SQL statements. This are not stored as - pointers into the fsl_db_prepare_cached() list because that - cache can be invalidated via a db-close. These particular - statements are potentially prepared so often that we manage - them separate from fsl_db_prepare_cached() as a further - optimization. - - This optimization was single-handedly responsible for cutting - f-rebuild's time in less than half. The rest of that time was - spent building the SQL strings (indirectly via fsl_appendf()) - to figure out if they corresponded to a cached query or not. - */ - struct { - /** Query fetching [delta].[srcid] for a given [delta].[rid]. */ - fsl_stmt deltaSrcId; - /** Query fetching a [blob].[rid] for an exact-match - [blob].[uuid]. */ - fsl_stmt uuidToRid; - /** Query fetching [blob].[rid] for a [blob].[uuid] prefix. */ - fsl_stmt uuidToRidGlob; - /** Query fetching [blob].[size] for a [blob].[rid] */ - fsl_stmt contentSize; - /** Query fetching [blob].[content,size] for a [blob].[rid] */ - fsl_stmt contentBlob; - /** Placeholder. */ - fsl_stmt nextEntry; - } 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; } cache; /** Ticket-related information. */ @@ -19100,21 +18005,10 @@ /** 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; /* Note: no state related to server/user/etc. That is higher-level stuff. We might need to allow the user to set a default user @@ -19128,10 +18022,11 @@ Initialized-with-defaults fsl_cx struct. */ #define fsl_cx_empty_m { \ NULL /*dbMain*/, \ NULL/*allocStamp*/, \ + fsl_db_empty_m /* dbMem */, \ {/*ckout*/ \ fsl_db_empty_m /*db*/, \ NULL /*dir*/, 0/*dirLen*/, \ -1/*rid*/, NULL/*uuid*/, 0/*mtime*/ \ }, \ @@ -19145,10 +18040,11 @@ }, \ fsl_confirmer_empty_m/*confirmer*/, \ fsl_outputer_FILE_m /*output*/, \ fsl_state_empty_m /*clientState*/, \ fsl_error_empty_m /*error*/, \ + fsl_buffer_empty_m /*fileContent*/, \ {/*scratchpads*/ \ {fsl_buffer_empty_m,fsl_buffer_empty_m, \ fsl_buffer_empty_m,fsl_buffer_empty_m, \ fsl_buffer_empty_m,fsl_buffer_empty_m}, \ {false,false,false,false,false,false}, \ @@ -19157,23 +18053,21 @@ fsl_cx_config_empty_m /*cxConfig*/, \ FSL_CX_F_DEFAULTS/*flags*/, \ 0/*interrupted*/, \ fsl_xlinker_list_empty_m/*xlinkers*/, \ {/*cache*/ \ + false/*caseInsensitive*/, \ false/*ignoreDephantomizations*/, \ false/*markPrivate*/, \ false/*isCrosslinking*/, \ false/*xlinkClustersOnly*/, \ false/*inFinalVerify*/, \ - -1/*caseInsensitive*/, \ -1/*allowSymlinks*/, \ -1/*seenDeltaManifest*/, \ -1/*searchIndexExists*/, \ -1/*manifestSetting*/,\ 0/*rcvId*/, \ - fsl_buffer_empty_m /*fileContent*/, \ - fsl_buffer_empty_m /*deltaContent*/, \ fsl__bccache_empty_m/*blobContent*/, \ fsl_id_bag_empty_m/*mfSeen*/, \ fsl_id_bag_empty_m/*leafCheck*/, \ fsl_id_bag_empty_m/*toVerify*/, \ 0/*mtimeManifest*/, \ @@ -19182,29 +18076,18 @@ fsl__mcache_empty_m/*mcache*/, \ {/*globs*/ \ fsl_list_empty_m/*ignore*/, \ fsl_list_empty_m/*binary*/, \ fsl_list_empty_m/*crnl*/ \ - }, \ - {/*stmt*/ \ - fsl_stmt_empty_m/*deltaSrcId*/, \ - fsl_stmt_empty_m/*uuidToRid*/, \ - fsl_stmt_empty_m/*uuidToRidGlob*/, \ - fsl_stmt_empty_m/*contentSize*/, \ - fsl_stmt_empty_m/*contentBlob*/, \ - fsl_stmt_empty_m/*???*/ \ - }, \ - NULL/*tempDirs*/ \ - }/*cache*/, \ + } \ + }/*cache*/, \ {/*ticket*/ \ fsl_list_empty_m/*customFields*/, \ 0/*hasTicket*/, \ 0/*hasCTime*/, \ 0/*hasChng*/, \ - 0/*hasCngRid*/, \ - NULL/*titleColumn*/, \ - NULL/*statusColumn*/ \ + 0/*hasCngRid*/ \ } \ } /** @internal Initialized-with-defaults fsl_cx instance. @@ -19406,11 +18289,11 @@ Returns 0 if a delta is successfully made or none needs to be made, non-0 on error. @see fsl__content_undeltify() */ -int fsl__content_deltify(fsl_cx * const f, fsl_id_t rid, +int fsl__content_deltify(fsl_cx * f, fsl_id_t rid, fsl_id_t srcid, bool force); /** @internal @@ -19423,12 +18306,12 @@ _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__content_new( fsl_cx * const f, fsl_uuid_cstr uuid, - bool isPrivate, fsl_id_t * const newId ); +int fsl__content_new( fsl_cx * f, fsl_uuid_cstr uuid, bool isPrivate, + fsl_id_t * newId ); /** @internal Check to see if checkin "rid" is a leaf and either add it to the LEAF table if it is, or remove it if it is not. @@ -19939,25 +18822,12 @@ */ fsl_card_F * fsl__deck_F_seek(fsl_deck * const d, const char *zName); /** @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_buffer * fsl__cx_content_buffer(fsl_cx * const f); - -/** @internal - - Part of the fsl_cx::cache::fileContent optimization. This sets - f->cache.fileContent.used to 0 and if its capacity is over a certain + Part of the fsl_cx::fileContent optimization. This sets + f->fileContent.used to 0 and if its capacity is over a certain (unspecified, unconfigurable) size then it is trimmed to that size. */ void fsl__cx_content_buffer_yield(fsl_cx * const f); @@ -19980,30 +18850,45 @@ int fsl__search_doc_touch(fsl_cx * const 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. + Performs the same job as fsl_diff_text() but produces the results + in the low-level form of an array of "copy/delete/insert triples." + This is primarily intended for internal use in other + library-internal algorithms, not for client code. Note all + FSL_DIFF_xxx flags apply to this form. + + Returns 0 on success, any number of non-0 codes on error. On + success *outRaw will contain the resulting array, which must + eventually be fsl_free()'d by the caller. On error *outRaw is not + modified. + + @deprecated Use fsl_diff_v2_raw() instead. +*/ +int fsl__diff_text_raw(fsl_buffer const *p1, fsl_buffer const *p2, + int diffFlags, int ** outRaw); + +/** @internal + + If the given file name is a reserved filename (case-insensitive) on + Windows platforms, a pointer to the reserved part of the name, else + NULL is returned. 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 - Clears any pending merge state from the f's checkout db's vmerge - table. Returns 0 on success, non-0 on db error. - - If fullWipe is true, it clears all vfile contents uncondtionally, - else it clears only entries for which the corresponding vfile - entries are marked as unchanged and then cleans up remaining merge - state if no file-level merge changes are pending. -*/ -int fsl__ckout_clear_merge_state( fsl_cx * const f, bool fullWipe ); + Clears any pending merge state from the checkout db's vmerge table. + Returns 0 on success. +*/ +int fsl__ckout_clear_merge_state( fsl_cx *f ); + /** @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 @@ -20013,11 +18898,11 @@ 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 * const f, bool dropIfExists); +int fsl_ckout_install_schema(fsl_cx * const f, bool dropIfExists); /** @internal Attempts to remove empty directories from under a checkout, starting with tgtDir and working upwards until it either cannot @@ -20035,31 +18920,30 @@ 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 * const f, - fsl_buffer const * const tgtDir); +unsigned int fsl_ckout_rm_empty_dirs(fsl_cx * const f, fsl_buffer * 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 + of the checkout is reach. 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 * const f, char const *zAbsPath); +int fsl_ckout_rm_empty_dirs_for_file(fsl_cx * const 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, @@ -20194,11 +19078,11 @@ for $REASONS. That might (might) be reflected long-term in this API by only supporting them in the way fossil does for platforms which do not support symlinks. */ int fsl__ckout_symlink_create(fsl_cx * const f, char const *zTgtFile, - char const * zLinkFile); + char const * zLinkFile); /** Compute all file name changes that occur going from check-in iFrom to check-in iTo. Requires an opened repository. @@ -20296,11 +19180,11 @@ - 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 + possible, but FSL__LOCALMOD_NOFOUND 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. @@ -20431,41 +19315,31 @@ */ int fsl__repo_fingerprint_search(fsl_cx * const f, fsl_id_t rcvid, char ** zOut); /** - 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: + A context for running a raw diff. + + The aEdit[] array describes the raw diff. Each triple of integers in + aEdit[] means: (1) COPY: Number of lines aFrom and aTo have in common (2) DELETE: Number of lines found only in aFrom (3) INSERT: Number of lines found only in aTo - - The triples repeat until all lines of both aFrom and aTo are - accounted for. 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); + + The triples repeat until all lines of both aFrom and aTo are accounted + for. +*/ +struct fsl__diff_cx { + /*TODO unsigned*/ int *aEdit; /* Array of copy/delete/insert triples */ + /*TODO unsigned*/ int nEdit; /* Number of integers (3x num of triples) in aEdit[] */ + /*TODO unsigned*/ int nEditAlloc; /* Space allocated for aEdit[] */ + fsl_dline *aFrom; /* File on left side of the diff */ + /*TODO unsigned*/ int nFrom; /* Number of lines in aFrom[] */ + fsl_dline *aTo; /* File on right side of the diff */ + /*TODO unsigned*/ int nTo; /* Number of lines in aTo[] */ + int (*cmpLine)(const fsl_dline * const, const fsl_dline *const); /* Function to be used for comparing */ }; /** Convenience typeef. */ typedef struct fsl__diff_cx fsl__diff_cx; @@ -20475,10 +19349,12 @@ NULL,0,0,NULL,0,NULL,0,fsl_dline_cmp \ } /** Initialized-with-defaults fsl__diff_cx structure, intended for non-const copy initialization. */ extern const fsl__diff_cx fsl__diff_cx_empty; + + /** @internal Compute the differences between two files already loaded into the fsl__diff_cx structure. @@ -20496,32 +19372,33 @@ Returns 0 on succes, FSL_RC_OOM on an allocation error. */ int fsl__diff_all(fsl__diff_cx * const p); -/** @internal */ +/** @internal + */ void fsl__diff_optimize(fsl__diff_cx * const p); -/** @internal */ +/** @internal + */ void fsl__diff_cx_clean(fsl__diff_cx * const cx); /** @internal Undocumented. For internal debugging only. -*/ + */ void fsl__dump_triples(fsl__diff_cx const * const p, char const * zFile, int ln ); /** @internal 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. + opened. */ int fsl__shunned_remove(fsl_cx * const f); + /** @internal This is a fossil-specific internal detail not needed by the more @@ -20539,148 +19416,28 @@ 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 * const db, int 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 * const f, char const * zTktId); - -/** @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 * const 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 - Clears the contents of f->cache.mcache. -*/ -void fsl__cx_mcache_clear(fsl_cx * const f); - -/** @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 * const db, int sqliteCode); - -/** @internal - - Clears various internal caches and resets various - internally-cached values related to a repository db, but the data - cleared here are not associated directly with a db handle. This is - intended primarily to be used when a db transaction is rolled back - which might have introduced state into those caches which would be - stale after a rollback. -*/ -void fsl__cx_clear_repo_caches(fsl_cx * const f); - -/** @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 * const f, fsl_db * const db); - -/** @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 * const 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 * const f, fsl_dbrole_e r); - -/** @internal - - Frees/clears the non-db state of f->ckout. -*/ -void fsl__cx_ckout_clear(fsl_cx * const f); /** @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<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_buffer_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. + e.g. fsl_strndup()'s second argument. 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 @@ -21579,12 +20327,12 @@ */ #endif /* ORG_FOSSIL_SCM_PAGES_H_INCLUDED */ -/* end of file ./include/fossil-scm/pages.h */ -/* start of file ./include/fossil-scm/cli.h */ +/* end of file ../include/fossil-scm/fossil-pages.h */ +/* start of file ../include/fossil-scm/fossil-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_ /* @@ -21601,12 +20349,17 @@ This file provides a basis for basic libfossil-using apps. It attempts to provide basic services required by a wide variety of fossil-using apps, with the intent of simplifying their creation. */ +/* Force assert() to always work... */ +#if defined(NDEBUG) +#undef NDEBUG +#define DEBUG 1 +#endif +#include /* for the benefit of test apps */ #include /* EXIT_SUCCESS and friends */ -#include /** @page page_fcli fcli (formerly FossilApp) ::fcli (formerly FossilApp) provides a small framework for bootstrapping simple libfossil applications which only need a @@ -22025,11 +20778,11 @@ 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 + equivalent to using the --no-checkout|-C flags. The global --checkout-dir flag will trump that setting, though. */ char const * checkoutDir; /** @@ -22048,11 +20801,11 @@ /** repo db name string from -R/--repo CLI flag. */ const char * repoDbArg; /** - User name from the --user CLI flag. + User name from the -U/--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". @@ -22104,10 +20857,20 @@ (but might not have an opened checkout/repository) if fsl_setup() succeeds. */ FSL_EXPORT fcli_t fcli; +/** + Equivalent to `fcli_setup_v2(argc,argv,NULL,NULL)`. + + @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. +*/ +FSL_EXPORT int fcli_setup(int argc, char const * const * argv ); + /** 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 @@ -22121,24 +20884,21 @@ If the 3rd argument is not NULL, this sets `fcli.cliFlags` to its value. If the 4th argument is not NULL, this sets `fcli.appHelp` to that value. - If argument processing finds either of the (`--help`, `-?`) flags, + If argument processing finds either of the (--help, -?) flags, or the first non-flag argument is "help", it sets fcli.transient.helpRequested to a true value, calls fcli_help(), and returns FCLI_RC_HELP, in which case the application should - exit/return from main with code 0 immediately. 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.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). + exit/return from main with code 0 immediately. + + This function behaves significantly differently if fcli.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. 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 @@ -22472,18 +21232,12 @@ "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); +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). @@ -22625,18 +21379,17 @@ 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. + passed to it have no trailing slashes, and 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, +FSL_EXPORT int fcli_args_to_vfile_ids(fsl_id_bag *tgt, fsl_id_t vid, bool relativeToCwd, bool changedFilesOnly); /** Performs a "fingerprint check" on the current checkout/repo @@ -22675,14 +21428,14 @@ 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 + Populates the given fsl_diff_opt::ansiColors state with values dependend on the second argument. */ -FSL_EXPORT void fcli_diff_colors(fsl_dibu_opt * const tgt, +FSL_EXPORT void fcli_diff_colors(fsl_diff_opt * const tgt, fcli_diff_colors_e theme); /** @internal This function is intented for use in development of libfossil. It @@ -22710,259 +21463,6 @@ #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-ArtifactOfProjectName: Libfossil - 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); - -/** - Flags for use with text-diff generation APIs, - e.g. fsl_diff_text(). - - Maintenance reminders: - - - These values are holy and must not be changed without also - changing the corresponding code in diff.c. - - - Where these entries semantically overlap with their fsl_diff2_flag_e - counterparts, they MUST have the same values because some internal APIs - are used by both of the diff APIs. - - @deprecated Prefer fsl_diff2_flag_e and fsl_diff_v2() instead. -*/ -enum fsl_diff_flag_e { -/** Ignore end-of-line whitespace */ -FSL_DIFF_IGNORE_EOLWS = 0x01, -/** Ignore end-of-line whitespace */ -FSL_DIFF_IGNORE_ALLWS = 0x03, -/** Generate a side-by-side diff */ -FSL_DIFF_SIDEBYSIDE = 0x04, -/** Missing shown as empty files */ -FSL_DIFF_VERBOSE = 0x08, -/** Show filenames only. Not used in this impl! */ -FSL_DIFF_BRIEF = 0x10, -/** Render HTML. */ -FSL_DIFF_HTML = 0x20, -/** Show line numbers. */ -FSL_DIFF_LINENO = 0x40, -/** Suppress optimizations (debug). */ -FSL_DIFF_NOOPT = 0x0100, -/** Invert the diff (debug). */ -FSL_DIFF_INVERT = 0x0200, -/* ACHTUNG: do not use 0x0400 because of semantic - collision with FSL_DIFF2_CONTEXT_ZERO */ -/** Only display if not "too big." */ -FSL_DIFF_NOTTOOBIG = 0x0800, -/** Strip trailing CR */ -FSL_DIFF_STRIP_EOLCR = 0x1000, -/** - This flag tells text-mode diff generation to add ANSI color - sequences to some output. The colors are currently hard-coded - and non-configurable. This has no effect for HTML output, and - that flag trumps this one. It also currently only affects - unified diffs, not side-by-side. - - Maintenance reminder: this one currently has no counterpart in - fossil(1), is not tracked in the same way, and need not map to an - internal flag value. -*/ -FSL_DIFF_ANSI_COLOR = 0x2000 -}; - -/** - Generates a textual diff from two text inputs and writes - it to the given output function. - - pA and pB are the buffers to diff. - - contextLines is the number of lines of context to output. This - parameter has a built-in limit of 2^16, and values larger than - that get truncated. A value of 0 is legal, in which case no - surrounding context is provided. A negative value translates to - some unspecified default value. - - sbsWidth specifies the width (in characters) of the side-by-side - columns. If sbsWidth is not 0 then this function behaves as if - diffFlags contains the FSL_DIFF_SIDEBYSIDE flag. If sbsWidth is - negative, OR if diffFlags explicitly contains - FSL_DIFF_SIDEBYSIDE and sbsWidth is 0, then some default width - is used. This parameter has a built-in limit of 255, and values - larger than that get truncated to 255. - - diffFlags is a mask of fsl_diff_flag_t values. Not all of the - fsl_diff_flag_t flags are yet [sup]ported. - - The output is sent to out(outState,...). If out() returns non-0 - during processing, processing stops and that result is returned - to the caller of this function. - - Returns 0 on success, FSL_RC_OOM on allocation error, - FSL_RC_MISUSE if any arguments are invalid, FSL_RC_TYPE if any - of the content appears to be binary (contains embedded NUL - bytes), FSL_RC_RANGE if some range is exceeded (e.g. the maximum - number of input lines). - - None of (pA, pB, out) may be NULL. - - TODOs: - - - Add a predicate function for outputing only matching - differences, analog to fossil(1)'s regex support (but more - flexible). - - - Expose the raw diff-generation bits via the internal API - to facilitate/enable the creation of custom diff formats. - - @see fsl_diff_v2() - @deprecated Prefer fsl_diff_v2() for new code. -*/ -int fsl_diff_text(fsl_buffer const *pA, fsl_buffer const *pB, - fsl_output_f out, void * outState, - short contextLines, short sbsWidth, - int diffFlags ); - -/** - Functionally equivalent to: - - ``` - fsl_diff_text(pA, pB, fsl_output_f_buffer, pOut, - contextLines, sbsWidth, diffFlags); - ``` - - Except that it returns FSL_RC_MISUSE if !pOut. - - @see fsl_diff_v2() - @deprecated Prefer fsl_diff_v2() for new code. -*/ -int fsl_diff_text_to_buffer(fsl_buffer const *pA, fsl_buffer const *pB, - fsl_buffer *pOut, short contextLines, - short sbsWidth, int diffFlags ); - - -/** - 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 ); - -/** @internal - - Performs the same job as fsl_diff_text() but produces the results - in the low-level form of an array of "copy/delete/insert triples." - This is primarily intended for internal use in other - library-internal algorithms, not for client code. Note all - FSL_DIFF_xxx flags apply to this form. - - Returns 0 on success, any number of non-0 codes on error. On - success *outRaw will contain the resulting array, which must - eventually be fsl_free()'d by the caller. On error *outRaw is not - modified. - - @deprecated Use fsl_diff_v2_raw() instead. -*/ -int fsl__diff_text_raw(fsl_buffer const *p1, fsl_buffer const *p2, - int diffFlags, int ** outRaw); - - -/** @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 */ +/* end of file ../include/fossil-scm/fossil-cli.h */ ADDED signify/fnc-05-release.pub Index: signify/fnc-05-release.pub ================================================================== --- signify/fnc-05-release.pub +++ signify/fnc-05-release.pub @@ -0,0 +1,2 @@ +untrusted comment: fnc 0.5 public key +RWQTvScFdMzcwQlljPIt0yPn6wpR+T1kR1w0/3HMegAaYyO32FMuzMcM DELETED signify/fnc-07-release.pub Index: signify/fnc-07-release.pub ================================================================== --- signify/fnc-07-release.pub +++ signify/fnc-07-release.pub @@ -1,2 +0,0 @@ -untrusted comment: fnc 0.7 public key -RWS7z+k9eoeF8OQp7R9VyUfKlxOODpUYCBM2v/YEbk8YXiSK1FzkIVJD Index: src/fnc.1 ================================================================== --- src/fnc.1 +++ src/fnc.1 @@ -1,7 +1,7 @@ .\" -.\" Copyright (c) 2021, 2022 Mark Jamsek +.\" Copyright (c) 2021 Mark Jamsek .\" .\" Permission to use, copy, modify, and distribute this software for any .\" purpose with or without fee is hereby granted, provided that the above .\" copyright notice and this permission notice appear in all copies. .\" @@ -25,55 +25,49 @@ .Op Fl h | -help .Nm .Op Fl h | -help .Op Fl v | -version .Nm -.Cm config -.Op Fl hu -.Op Fl -ls -.Op Fl R Ar path -.Op Ar setting Op Ar value -.Nm .Cm timeline .Op Fl Cz .Op Fl b Ar branch .Op Fl c Ar commit .Op Fl f Ar glob .Op Fl n Ar number -.Op Fl R Ar path .Op Fl T Ar tag .Op Fl t Ar type .Op Fl u Ar user .Op Ar path .Nm .Cm diff .Op Fl Ciw -.Op Fl R Ar path .Op Fl x Ar number .Op Ar artifact1 Op Ar artifact2 .Op Ar path ... .Nm .Cm tree .Op Fl C .Op Fl c Ar commit -.Op Fl R Ar path .Op Ar path .Nm .Cm blame .Op Fl C .Op Fl c Ar commit Op Fl r .Op Fl n Ar number -.Op Fl R Ar path .Ar path .Nm .Cm branch .Op Fl Ccopr .Op Fl a Ar date | Fl b Ar date -.Op Fl R Ar path .Op Fl s Ar order .Op Ar glob .Nm +.Cm config +.Op Fl hu +.Op Fl -ls +.Op Ar setting Op Ar value +.Nm .Op Ar path .Sh DESCRIPTION .Nm is an interactive read-only browser for .Xr fossil 1 @@ -106,22 +100,15 @@ Display navigable list of all repository branches. .El .Pp .Nm provides both global and command-specific options and in-app key -bindings. Global options are as follows: +bindings. Global options are specified absent a command name, and +are as follows: .Bl -tag -width 6v .It Fl h , -help Display program help and usage information then exit. -.It Fl R , -repo Ar path -Use the -.Xr fossil 1 -repository database at the specified -.Ar path -for the current -.Nm -session. See command specific options for details. .It Fl v , -version Display program version then exit. .El .Pp Note that any global options preceding a command name will be @@ -149,13 +136,13 @@ Commands available to .Nm are as follows: .Bl -tag -width 4v .Tg conf -.It Cm config Oo Fl h | -help Oc Oo Fl -ls Oc Oo Fl R | -repo Ar path Oc \ +.It Cm config Oo Fl h | -help Oc Oo Fl -ls Oc \ Oo Ar setting Op Ar value | Fl -unset Oc -.Dl Pq aliases: Cm conf , Cm cfg , Cm settings , Cm set +.Dl Pq aliases: Cm conf , Cm cfg, settings, set Retrieve the current, or set a new, .Ar value for .Ar setting in the local repository. When specified, @@ -171,54 +158,37 @@ will display a list of all configurable settings. Alternatively, see .Sx ENVIRONMENT for a detailed list of available settings used in the display or processing of data. When no value is found for a given setting in the local repository, environment variables will be searched. -If still not found, default values will be used. Unless the -.Sy --repo -option is used, this command must be executed from within the repository -hierarchy; that is, -.Nm -assumes a local checkout is open in or above the current working directory. -Options for +If still not found, default values will be used. Options for .Cm fnc config are as follows: .Bl -tag -width Ds .It Fl h , -help Display config command help and usage information then exit. .It Fl -ls List all currently defined settings. -.It Fl R , -repo Ar path -Use the -.Xr fossil 1 -repository database at the specified -.Ar path -for the current -.Cm fnc config -invocation. .It Fl u , -unset Clear the specified .Ar setting. .El .Tg log .It Cm timeline Oo Fl C | -no-colour Oc Oo Fl T | -tag Ar tag Oc \ Oo Fl b | -branch Ar branch Oc Oo Fl c | -commit Ar commit Oc \ Oo Fl f | -filter Ar glob Oc Oo Fl h | -help Oc Oo Fl n | -limit Ar n Oc \ -Oo Fl R | -repo Ar path Oc Oo Fl t | -type Ar type Oc \ -Oo Fl u | -username Ar user Oc Oo Fl z | -utc Oc \ +Oo Fl t | -type Ar type Oc Oo Fl u | -username Ar user Oc Oo Fl z | -utc Oc \ Op Ar path .Dl Pq aliases: Cm log , Cm tl , Cm time , Cm ti Display commit history of a repository. If .Ar path is specified, only commits that modified the file(s) at this path will populate the timeline. The .Ar path may be absolute, relative to the current working directory, or relative to the -repository root. Unless the -.Sy --repo -option is used, this command must be executed from within the repository -hierarchy; that is, +repository root. This command must be executed from within or below the top +level directory of the repository; that is, .Nm assumes a local checkout is open in or above the current working directory. .Pp If no command is explicitly specified, this command will be executed by default. @@ -228,16 +198,11 @@ are as follows: .Bl -tag -width Ds .It Fl b , -branch Ar branch Display commits that are members of the specified .Ar branch . -The expected argument is a glob of the symbolic name of a branch, with the most -recent branch to match being selected. Pattern matching is case-insensitive -unless -.Ar branch -has at least one uppercase character, in which case the search will be -case-sensitive. By default, +The expected argument is the symbolic name of a branch. By default, .Nm will display all commits irrespective of the branch on which they reside. .It Fl C , -no-colour Disable colourised timeline, which is enabled by default on supported @@ -260,15 +225,17 @@ .Lk https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki \ "Fossil's Check-in Names". .It Fl f , -filter Ar glob Filter timeline by commits containing .Ar glob -in any of the commit comment, user, or branch fields. Pattern matching is -case-insensitive unless -.Ar glob -has at least one uppercase character, in which case the search will be -case-sensitive. Filtering can also be performed in-session with the +in any of the commit comment, user, or branch fields. Pattern matching depends +on the +.Xr sqlite3 1 +.B +LIKE +operator, which only folds case for the ASCII character set. Filtering can also +be performed in-session with the .Sy F timeline view key binding as documented below. .It Fl h , -help Display timeline command help and usage information then exit. .It Fl n , -limit Ar n @@ -278,39 +245,14 @@ commits. By default, .Nm will load the entire history of the repository's local checkout. Negative values are a no-op. -.It Fl R , -repo Ar path -Use the -.Xr fossil 1 -repository database at the specified -.Ar path -for the current -.Cm fnc timeline -invocation. When this option is used, the checkout-related Fossil special -tags -.Qq current , -.Qq prev , -and -.Qq next -are invalid arguments to the -.Sy --commit -option. When -.Sy --commit -is not specified, -.Nm -will default to populating the timeline from the latest commit. .It Fl T , -tag Ar tag Only display commits with T cards containing .Ar tag . -The expected argument is a glob of a commit manifest's T card argument, with the -most recent tag to match being selected. Pattern matching is case-insensitive -unless -.Ar tag -has at least one uppercase character, in which case the search will be -case-sensitive. By default, +By default, .Nm will indiscriminately display all commits irrespective of which T cards are attached to the commit manifest. .It Fl t , -type Ar type Only display @@ -337,14 +279,10 @@ .Cm -t e -t t Ns ). .It Fl u , -username Ar user Only display commits authored by .Ar user . -The search is case-insensitive by default unless -.Ar user -contains at least one uppercase character, in which case the search will be -case-sensitive. .It Fl z , -utc Use Coordinated Universal Time (UTC) rather than local time when displaying commit dates and timestamps. .El .Pp @@ -355,17 +293,13 @@ .It Cm Arrow-down, j, >, \&. Move selection cursor down the timeline. .It Cm Arrow-up, k, <, \&, Move selection cursor up the timeline. .It Cm C-f, Page-down -Scroll timeline view one page downwards in the buffer. +Move selection cursor one page down the timeline. .It Cm C-b, Page-up -Scroll timeline view one page upwards in the buffer. -.It Cm C-d -Scroll timeline view half a page downwards in the buffer. -.It Cm C-u -Scroll timeline view half a page upwards in the buffer. +Move selection cursor one page up the timeline. .It Cm G, End Move selection cursor to the last commit on the timeline (i.e., oldest commit in the repository). .It Cm gg, Home Move selection cursor to the first commit on the timeline (i.e., newest commit @@ -402,12 +336,12 @@ Find the previous commit that matches the current search term. The search will continue until either a match is found or the latest commit on the timeline is consumed. .El .Tg di -.It Cm diff Oo Fl C | -no-colour Oc Oo Fl h | -help Oc Oo Fl i | -invert Oc \ -Oo Fl R | -repo Ar path Oc Oo Fl w | -whitespace Oc Oo Fl x | -context Ar n Oc \ +.It Cm diff Oo Fl C | -no-colour Oc Oo Fl h | -help Oc Oo Fl i | -invert \ +Oc Oo Fl w | -whitespace Oc Oo Fl x | -context Ar n Oc \ Oo Ar artifact1 Oo Ar artifact2 Oc Oc Op Ar path ... .Dl Pq alias: Cm di Display the differences between two repository artifacts, or between the local changes on disk and a given commit. If neither .Ar artifact1 @@ -434,16 +368,11 @@ .Ar artifact2 must be of the same type, which is expected to be either a symbolic check-in name, tag, (unique abbreviated prefix of) a commit or blob artifact UUID SHA1 or SHA3 hash, or an ISO 8601 formatted date. Both artifact arguments must be supplied when diffing blobs; any following non-option arguments are invalid -and will be ignored. Unless the -.Sy --repo -option is used, this command must be executed from within the repository -hierarchy; that is, -.Nm -assumes a local checkout is open in or above the current working directory. +and will be ignored. .Pp Options for .Cm fnc diff are as follows: .Bl -tag -width Ds @@ -457,29 +386,10 @@ for details. .It Fl h , -help Display diff command help and usage information then exit. .It Fl i , -invert Invert the difference between artifacts when displaying the diff. -.It Fl R , -repo Ar path -Use the -.Xr fossil 1 -repository database at the specified -.Ar path -for the current -.Cm fnc diff -invocation. When this option is used, both -.Ar artifact1 -and -.Ar artifact2 -are required, and the checkout-related Fossil special tags -.Qq current , -.Qq prev , -and -.Qq next -are invalid -.Sy artifact -operands. .It Fl w , -whitespace Ignore whitespace-only changes when displaying the diff. .It Fl x , -context Ar n Set .Ar n @@ -490,41 +400,17 @@ Key bindings for .Cm fnc diff are as follows: .Bl -tag -width Ds .It Cm Arrow-down, j -Move the selection cursor down one line. +Scroll down one line of diff output. .It Cm Arrow-up, k -Move the selection cursor up one line. -.It Cm Arrow-right, l -Scroll the view two columns to the right in the buffer. Diff output moves -left on the screen. -.It Cm Arrow-left, h -Scroll the view two columns to the left in the buffer. Diff output moves -right on the screen. -.It Cm $ -Scroll the view right to the end of the longest line in the diff. -.It Cm 0 -Scroll the view left to the beginning of the line. -.It Cm C-e -Scroll view one line downwards in the buffer. Diff output moves upwards on the -screen. -.It Cm C-y -Scroll view one line upwards in the buffer. Diff output moves downwards on the -screen. -.It Cm C-n -Navigate to next file in the diff. -.It Cm C-p -Navigate to previous file in the diff. +Scroll up one line of diff output. .It Cm C-f, Page-down, Space -Scroll diff view one page downwards in the buffer. +Scroll down one page of diff output. .It Cm C-b, Page-up -Scroll diff view one page upwards in the buffer. -.It Cm C-d -Scroll diff view half a page downwards in the buffer. -.It Cm C-u -Scroll diff view half a page upwards in the buffer. +Scroll up one page of diff output. .It Cm G, End Scroll to the end of the view (i.e., last line of diff output). .It Cm gg, Home Scroll to the top of the view (i.e., first line of diff output). .It Cm C-k, K, <, \&, @@ -539,24 +425,18 @@ if the diff was accessed from the timeline.) .It Cm \&-, \&_ Decrease the number of context lines shown in diff output. .It Cm \&=, \&+ Increase the number of context lines shown in diff output. -.It Cm # -Toggle display of diff view line numbers. .It Cm b Open and populate branch view with all repository branches. .It Cm c Toggle coloured diff output. On supported terminals, .Nm will default to displaying changes and diff metadata in colour. -.It Cm F -Open prompt to enter file number and navigate to that file in the diff. .It Cm i Toggle inversion of diff output. -.It Cm L -Open prompt to enter line number and navigate to line. .It Cm v Toggle verbosity of diff output. By default, .Nm will display the entire content of newly added or deleted files. .It Cm w @@ -572,22 +452,20 @@ .It Cm N Find the previous line that matches the current search term. .El .Tg dir .It Cm tree Oo Fl C | -no-colour Oc Oo Fl c | -commit Ar commit Oc \ -Oo Fl h | -help Oc Oo Fl R | -repo Ar path Oc Op Ar path +Oo Fl h | -help Oc Op Ar path .Dl Pq aliases: Cm dir , Cm tr Display navigable, hierarchical tree of a repository. If a .Ar path is specified, display tree nodes of this path. The .Ar path may be absolute, relative to the current working directory, or relative to the repository root. With no options passed, the tree will reflect the state of the -latest commit on trunk. Unless the -.Sy --repo -option is used, this command must be executed from within the repository -hierarchy; that is, +latest commit on trunk. This command must be executed from within or below the +top level directory of the repository; that is, .Nm assumes a local checkout is open in or above the current working directory. .Pp Tree nodes are lexicographically ordered and may be postfixed with an identifier corresponding to the mode of the file object on disk as returned by @@ -623,26 +501,10 @@ arguments this option accepts, see .Lk https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki \ "Fossil's Check-in Names". .It Fl h , -help Display tree command help and usage information then exit. -.It Fl R , -repo Ar path -Use the -.Xr fossil 1 -repository database at the specified -.Ar path -for the current -.Cm fnc tree -invocation. When this option is used, the checkout-related Fossil special -tags -.Qq current , -.Qq prev , -and -.Qq next -are invalid arguments to the -.Sy --commit -option. .El .Pp Key bindings for .Cm fnc tree are as follows: @@ -655,18 +517,14 @@ Move up a level to the parent directory. This is a no-op when in the root tree. .It Cm Arrow-down, j Move selection cursor one node down the tree. .It Cm Arrow-up, k Move selection cursor one node up the tree. -.It Cm C-f, Page-down -Scroll tree view one page downwards in the buffer. -.It Cm C-b, Page-up -Scroll tree view one page upwards in the buffer. -.It Cm C-d -Scroll tree view half a page downwards in the buffer. -.It Cm C-u -Scroll tree view half a page upwards in the buffer. +.It Cm Page-down, C-f +Move selection cursor one page down the tree. +.It Cm Page-up, C-b +Move selection cursor one page up the tree. .It Cm Home, gg Move selection cursor to the first node in the tree. .It Cm End, G Move selection cursor to the last node in the tree. .It Cm b @@ -673,20 +531,18 @@ Open and populate branch view with all repository branches. .It Cm c Toggle coloured output. On supported terminals, .Nm will default to displaying the tree in colour. -.It Cm d -Toggle ISO8601 modified timestamp display for each tree entry. -.It Cm i -Toggle SHA hash UUID display for all file nodes displayed in the tree. .It Cm t Open .Cm timeline view for the currently selected tree node. This will display the timeline of all commits that involve the versioned file(s) corresponding to the selected node. +.It Cm i +Show SHA hash UUID for all file nodes displayed in the tree. .It Cm / Prompt to enter a search term to begin searching the tree for nodes matching the entered pattern. The search term is an extended regular expression, as documented in .Xr re_format 7 , @@ -697,19 +553,17 @@ Find the previous tree node that matches the current search pattern. .El .Tg praise .It Cm blame Oo Fl C | -no-colour Oc \ Oo Fl c | -commit Ar commit Oo Fl r | -reverse Oc Oc Oo Fl h | -help Oc \ -Oo Fl n | -limit Ar n Oc Oo Fl R | -repo Ar path Oc Ar path +Oo Fl n | -limit Ar n Oc Ar path .Dl Pq aliases: Cm praise , Cm annotate , Cm bl , Cm pr , Cm an Show commit attribution history for each line of the file at the specified .Ar path , which may be absolute, relative to the current working directory, or relative to -the repository root. Unless the -.Sy --repo -option is used, this command must be executed from within the repository -hierarchy; that is, +the repository root. This command must be executed from within or below the top +level directory of the repository; that is, .Nm assumes a local checkout is open in or above the current working directory. .Pp Options for .Cm fnc blame @@ -749,30 +603,10 @@ specified time limit. By default, .Nm will traverse the entire historical record of the file, which can be expensive for large files that span many commits. Use this option for a faster, more targeted annotation. -.It Fl R , -repo Ar path -Use the -.Xr fossil 1 -repository database at the specified -.Ar path -for the current -.Cm fnc blame -invocation. When this option is used, the checkout-related Fossil special -tags -.Qq current , -.Qq prev , -and -.Qq next -are invalid arguments to the -.Sy --commit -option. When -.Sy --commit -is not specified, -.Nm -will default to blaming the version of the file found in the latest commit. .It Fl r , -reverse Reverse annotate the file starting from a historical commit and move forward in time. That is, rather than show the most recent change to each line, show the first time each line was modified by a subsequent commit after the specified .Ar commit . @@ -785,80 +619,62 @@ .Bl -tag -width Ds .It Cm Arrow-down, j Move selection cursor down one line. .It Cm Arrow-up, k Move selection cursor up one line. -.It Cm Arrow-right, l -Scroll the view two columns to the right in the buffer. File output moves -left on the screen. -.It Cm Arrow-left, h -Scroll the view two columns to the left in the buffer. File output moves -right on the screen. -.It Cm $ -Scroll the view right to the end of the longest line in the file. -.It Cm 0 -Scroll the view left to the beginning of the line. -.It Cm C-f, Page-down -Scroll blame view one page downwards in the buffer. -.It Cm C-b, Page-up -Scroll blame view one page upwards in the buffer. -.It Cm C-d -Scroll blame view half a page downwards in the buffer. -.It Cm C-u -Scroll blame view half a page upwards in the buffer. +.It Cm Page-down, C-f +Move selection cursor down one page. +.It Cm Page-up, C-b +Move selection cursor up one page. .It Cm Home, gg Move selection cursor to the first line in the file. .It Cm End, G Move selection cursor to the last line in the file. .It Cm Enter Display the .Cm diff of the commit corresponding to the currently selected line. -.It Cm # -Toggle display of file line numbers. -.It Cm B, Backspace -Reload the previous blamed version of the file. .It Cm b Blame the version of the file corresponding to the commit in the currently selected line. +.It Cm p +Blame the version of the file corresponding to the parent of the commit in +the currently selected line. +.It Cm B, Backspace +Reload the previous blamed version of the file. +.It Cm T +Open and populate branch view with all repository branches. .It Cm c Toggle coloured output. On supported terminals, .Nm will default to displaying the blamed file in colour. -.It Cm L -Open prompt to enter line number and navigate to line. -.It Cm p -Blame the version of the file corresponding to the parent of the commit in -the currently selected line. -.It Cm T -Open and populate branch view with all repository branches. .It Cm / Prompt to enter a search term to begin searching the file for tokens matching the entered pattern. The search term is an extended regular expression, as documented in .Xr re_format 7 . +.It Cm n +Find the next token that matches the current search pattern. .It Cm N Find the previous token that matches the current search pattern. -.It Cm n -Find the next token that matches the current search pattern. .El .Tg tag .It Cm branch Oo Fl C | -no-colour Oc Oo Fl -after Ar date | \ Fl -before Ar date Oc Oo Fl h | -help Oc Oo Fl -open | Fl -closed Oc \ -Oo Fl p | -no-private Oc Oo Fl R | -repo Ar path Oc Oo Fl r | -reverse Oc \ +Oo Fl p | -no-private Oc Oo Fl r | -reverse Oc \ Oo Fl s | -sort Ar order Oc Op Ar glob .Dl Pq aliases: Cm tag , Cm br Display navigable list of repository branches. If -.Ar glob -is specified, only display branches matching the pattern provided. Pattern -matching is case-insensitive unless -.Ar glob -contains at least one uppercase character, in which case the search will be -case-sensitive. Unless the -.Sy --repo -option is used, this command must be executed from within the repository -hierarchy; that is, +.Ar glob , +is specified, only display branches matching the pattern provided. Pattern +matching comparisons depend on the +.Xr sqlite3 1 +.B +LIKE +operator, which only folds case for the ASCII character set. This +command must be executed from within or below the top level directory of the +repository; that is, .Nm assumes a local checkout is open in or above the current working directory. .Pp Branches are lexicographically ordered by default, and are prefixed with an identifier corresponding to the branch state (i.e., open/closed). The @@ -878,32 +694,14 @@ .Cm fnc branch are as follows: .Bl -tag -width Ds .It Fl a , -after Ar date Display only those branches with activity after the specified -.Ar date , -which is expected to be either an ISO8601 -.Po e.g., -.Sy 2020-10-10 -.Pc -or unambiguous -.Sy DD/MM/YYYY -or -.Sy MM/DD/YYYY -formatted date. +.Ar date . .It Fl b , -before Ar date Display only those branches with activity before the specified -.Ar date , -which is expected to be either an ISO8601 -.Po e.g., -.Sy 2020-10-10 -.Pc -or unambiguous -.Sy DD/MM/YYYY -or -.Sy MM/DD/YYYY -formatted date. +.Ar date . .It Fl C , -no-colour Disable coloured output, which is enabled by default on supported terminals. If this option is not used, colour can be toggled with the .Sy c branch view key binding as documented below. @@ -917,18 +715,10 @@ .It Fl o , -open Display only opened branches. .It Fl p , -no-private Do not show private branches, which are included in the list of displayed branches by default. -.It Fl R , -repo Ar path -Use the -.Xr fossil 1 -repository database at the specified -.Ar path -for the current -.Cm fnc branch -invocation. .It Fl r , -reverse Reverse the order in which branches are displayed. .It Fl s , -sort Ar order Sort branches by .Ar order . @@ -949,18 +739,14 @@ .Bl -tag -width Ds .It Cm Arrow-down, j Move selection cursor down one branch. .It Cm Arrow-up, k Move selection cursor up one branch. -.It Cm C-f, Page-down -Scroll branch view one page downwards in the buffer. -.It Cm C-b, Page-up -Scroll branch view one page upwards in the buffer. -.It Cm C-d -Scroll branch view half a page downwards in the buffer. -.It Cm C-u -Scroll branch view half a page upwards in the buffer. +.It Cm Page-down, C-f +Move selection cursor down one page. +.It Cm Page-up, C-b +Move selection cursor up one page. .It Cm Home, gg Move selection cursor to the first branch in the list. .It Cm End, G Move selection cursor to the last branch in the list. .It Cm Enter, Space @@ -974,16 +760,10 @@ .It Cm d Toggle display of the date on which the branch last received changes. .It Cm i Toggle display of the SHA{1,3} hash that identifies branch, which is the hash of the commit on the tip of said branch. -.It Cm s -Toggle sort order of currently displayed branches. If branches are ordered -lexicographically, -.Nm -will sort branches in most recently used order, otherwise branches will be -sorted by their open/closed state. .It Cm t Open the .Cm tree view of the currently selected branch. .It Cm R, C-l @@ -1001,50 +781,10 @@ .It Cm N Find the previous branch that matches the current search pattern. .El .El .Sh ENVIRONMENT -Depending on the available screen estate determined by the LINES and COLUMNS -environment variables, -.Nm -will display child views in either a horizontal or vertical split. By default, -if COLUMNS is \(>= 120, a child view will open in a vertical split at least 80 -columns wide. Otherwise, the child view will open in a horizontal split that -is approximately 60% of the terminal height. This behaviour can be customised -by configuring the following options as either exported environment variables -or with -.Nm Cm config -as documented above. -.Bl -tag -width FNC_VIEW_SPLIT_HEIGHT -.It Ev FNC_VIEW_SPLIT_MODE -Open child views in a horizontal or vertical split. Value can be one of -.Sy auto , -.Sy horizontal , -or -.Sy vertical . -Default: -.Qq auto . -.It Ev FNC_VIEW_SPLIT_HEIGHT -Height of the child view when opening in a horizontal split. Valid numeric -values are 1 \(<= -.Sy n -< LINES. Percentage values denoted with a postfixed -.Sq % -.Po -e.g., -.Sy 55% -.Pc -are also valid. -Default: -.Qq 60% . -.It Ev FNC_VIEW_SPLIT_WIDTH -Minimum width of the child view when opening in a vertical split. Currently a -no-op. -Default: -.Qq 80 . -.El -.Pp .Nm displays coloured output by default in supported terminals. Each colour object identified below can be defined by either exporting environment variables .Po e.g., .Cm export FNC_COLOUR_COMMIT=red @@ -1060,17 +800,16 @@ .El .Pp If none are found, the default colour scheme will be displayed. This enables setting per-project colours to visually distinguish the current repository being viewed, and globally changing the colour scheme for all repositories with -no local settings configured. Except where documented below, colours supported -in +no local settings configured. Colours supported in .Nm are: .Bl -column "black" "yellow" "magenta" "default" -offset indent-two -.It Qo black Qc Ta Qo green Qc Ta Qo blue Qc Ta Qo cyan Qc -.It Qo red Qc Ta Qo yellow Qc Ta Qo magenta Qc Ta Qo default Qc +.It Qq black Ta Qq green Ta Qq blue Ta Qq cyan +.It Qq red Ta Qq yellow Ta Qq magenta Ta Qq default .El .Pp Where .Qq default is the current foreground (i.e., text) colour in the terminal. @@ -1097,11 +836,11 @@ Added lines displayed in the diff view. If not defined, the default value is .Qq cyan . .It Ev FNC_COLOUR_DIFF_CHUNK Chunk header lines .Po e.g., -.Li @@ -732,34 +747,40 @@ +.Ql @@ -732,34 +747,40 @@ .Pc displayed in the diff view. If not defined, the default value is .Qq yellow . .It Ev FNC_COLOUR_DIFF_META Metadata displayed in the diff view. If not defined, the default value is @@ -1134,22 +873,10 @@ If not defined, the default value is .Qq green . .It Ev FNC_COLOUR_BRANCH_PRIVATE Private branches displayed in the branch view. If not defined, the default value is -.Qq yellow . -.It Ev FNC_COLOUR_HL_LINE -Selected line highlight in the diff view. Value can be one of -.Sy auto -or -.Sy mono . -The former will invert the foreground colour of the selected line, while the -latter will use a monochromatic highlight. If not defined, the default value is -.Qq auto . -.It Ev FNC_COLOUR_HL_SEARCH -Search term highlight in blame and diff view. If not defined, the default -value is .Qq yellow . .El .Pp To clear environment variables, issue .Cm unset Ar ENVIRONMENT_VARIABLE Index: src/fnc.c ================================================================== --- src/fnc.c +++ src/fnc.c @@ -1,7 +1,7 @@ /* - * Copyright (c) 2021, 2022 Mark Jamsek + * Copyright (c) 2021 Mark Jamsek * Copyright (c) 2013-2021 Stephan Beal * Copyright (c) 2020 Stefan Sperling * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above @@ -33,13 +33,10 @@ # define _DEFAULT_SOURCE /* Needed for strsep() on glibc >= 2.19. */ # endif #endif -#ifdef FCLI_USE_SIGACTION -#define FCLI_USE_SIGACTION 0 /* We want C-c to exit. */ -#endif #include #include #include @@ -72,18 +69,16 @@ #include "settings.h" #define FNC_VERSION VERSION /* cf. Makefile */ /* Utility macros. */ -#define MIN(_a, _b) ((_a) < (_b) ? (_a) : (_b)) -#define MAX(_a, _b) ((_a) > (_b) ? (_a) : (_b)) -#define ABS(_n) ((_n) >= 0 ? (_n) : -(_n)) +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) #if !defined(CTRL) #define CTRL(key) ((key) & 037) /* CTRL+ input. */ #endif #define nitems(a) (sizeof((a)) / sizeof((a)[0])) -#define ndigits(_d, _n) do { _d++; } while (_n /= 10) #define STRINGIFYOUT(s) #s #define STRINGIFY(s) STRINGIFYOUT(s) #define CONCATOUT(a, b) a ## b #define CONCAT(a, b) CONCATOUT(a, b) #define FILE_POSITION __FILE__ ":" STRINGIFY(__LINE__) @@ -92,16 +87,13 @@ #define FLAG_TOG(f, b) ((f) ^= (b)) #define FLAG_CLR(f, b) ((f) &= ~(b)) /* Application macros. */ #define PRINT_VERSION STRINGIFY(FNC_VERSION) -#define DEF_DIFF_CTX 5 /* Default diff context lines. */ -#define MAX_DIFF_CTX 64 /* Max diff context lines. */ -#define HSPLIT_SCALE 0.4 /* Default horizontal split scale. */ +#define DIFF_DEF_CTXT 5 /* Default diff context lines. */ +#define DIFF_MAX_CTXT 64 /* Max diff context lines. */ #define SPIN_INTERVAL 200 /* Status line progress indicator. */ -#define LINENO_WIDTH 6 /* View lineno max column width. */ -#define MAX_PCT_LEN 7 /* Line position upto max len 99.99% */ #define SPINNER "\\|/-\0" #define NULL_DEVICE "/dev/null" #define NULL_DEVICELEN (sizeof(NULL_DEVICE) - 1) #define KEY_ESCAPE 27 #if DEBUG @@ -116,12 +108,12 @@ #ifndef HAVE_STRTONUM # define strtonum(s, min, max, o) strtol(s, (char **)o, 10) # endif /* HAVE_STRTONUM */ #endif -#ifndef __dead -#define __dead __attribute__((noreturn)) +#if !defined(__dead) +#define __dead #endif #ifndef TAILQ_FOREACH_SAFE /* Rewrite of OpenBSD 6.9 sys/queue.h for Linux builds. */ #define TAILQ_FOREACH_SAFE(var, head, field, tmp) \ @@ -182,11 +174,11 @@ const char **values; short nitems; } filter_types; /* Only load commits of . */ union { const char *zlimit; - long limit; + int limit; } nrecords; /* Number of commits to load. */ const char *filter_tag; /* Only load commits with . */ const char *filter_branch; /* Only load commits from . */ const char *filter_user; /* Only load commits from . */ const char *filter_type; /* Placeholder for repeatable types. */ @@ -214,16 +206,16 @@ /* Command line flags and help. */ fcli_help_info fnc_help; /* Global help. */ fcli_cliflag cliflags_global[3]; /* Global options. */ fcli_command cmd_args[7]; /* App commands. */ - fcli_cliflag cliflags_timeline[13]; /* Timeline options. */ - fcli_cliflag cliflags_diff[8]; /* Diff options. */ - fcli_cliflag cliflags_tree[5]; /* Tree options. */ - fcli_cliflag cliflags_blame[7]; /* Blame options. */ - fcli_cliflag cliflags_branch[11]; /* Branch options. */ - fcli_cliflag cliflags_config[5]; /* Config options. */ + fcli_cliflag cliflags_timeline[12]; /* Timeline options. */ + fcli_cliflag cliflags_diff[7]; /* Diff options. */ + fcli_cliflag cliflags_tree[4]; /* Tree options. */ + fcli_cliflag cliflags_blame[6]; /* Blame options. */ + fcli_cliflag cliflags_branch[10]; /* Branch options. */ + fcli_cliflag cliflags_config[4]; /* Config options. */ } fnc_init = { NULL, /* cmdarg copy of argv[1] to aid usage/error report. */ NULL, /* sym(bolic name) of commit to open defaults to tip. */ NULL, /* path for tree to open or timeline to find commits. */ 0, /* err fnc error state. */ @@ -286,16 +278,18 @@ cmd_config, usage_config, fnc_init.cliflags_config}, {NULL, NULL, NULL, NULL, NULL} /* Sentinel. */ }, { /* cliflags_timeline timeline command related options. */ - FCLI_FLAG("b", "branch", "", &fnc_init.filter_branch, - "Only display commits that reside on the given ."), FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour, "Disable colourised timeline, which is enabled by default on\n " "supported terminals. Colour can also be toggled with the 'c' " "\n key binding in timeline view when this option is not used."), + FCLI_FLAG("T", "tag", "", &fnc_init.filter_tag, + "Only display commits with T cards containing ."), + FCLI_FLAG("b", "branch", "", &fnc_init.filter_branch, + "Only display commits that reside on the given ."), FCLI_FLAG("c", "commit", "", &fnc_init.sym, "Open the timeline from . Common symbols are:\n" "\tSHA{1,3} hash\n" "\tSHA{1,3} unique prefix\n" "\tbranch\n" @@ -312,15 +306,10 @@ FCLI_FLAG_BOOL("h", "help", NULL, "Display timeline command help and usage."), FCLI_FLAG("n", "limit", "", &fnc_init.nrecords.zlimit, "Limit display to latest commits; defaults to entire history " "of\n current checkout. Negative values are a no-op."), - FCLI_FLAG_CSTR("R", "repo", "", NULL, - "Use the fossil(1) repository located at for this timeline\n" - " invocation."), - FCLI_FLAG("T", "tag", "", &fnc_init.filter_tag, - "Only display commits with T cards containing ."), FCLI_FLAG_X("t", "type", "", &fnc_init.filter_type, fcli_flag_type_arg_cb, "Only display commits. Valid types are:\n" "\tci - check-in\n" "\tw - wiki\n" @@ -348,13 +337,10 @@ "toggled\n with the 'i' key binding in diff view."), FCLI_FLAG_BOOL("q", "quiet", &fnc_init.quiet, "Disable verbose diff output; that is, do not output complete" " content\n of newly added or deleted files. Verbosity can also" " be toggled with\n the 'v' key binding in diff view."), - FCLI_FLAG_CSTR("R", "repo", "", NULL, - "Use the fossil(1) repository located at for this diff\n " - "invocation."), FCLI_FLAG_BOOL("w", "whitespace", &fnc_init.ws, "Ignore whitespace-only changes when displaying diff. This option " "can\n also be toggled with the 'w' key binding in diff view."), FCLI_FLAG("x", "context", "", &fnc_init.context, "Show context lines when displaying diff; is capped at 64." @@ -380,13 +366,10 @@ "\t{tip,current,prev,next}\n " "For a complete list of symbols see Fossil's Check-in Names:\n " "https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki"), FCLI_FLAG_BOOL("h", "help", NULL, "Display tree command help and usage."), - FCLI_FLAG_CSTR("R", "repo", "", NULL, - "Use the fossil(1) repository located at for this tree\n " - "invocation."), fcli_cliflag_empty_m }, /* End cliflags_tree. */ { /* cliflags_blame blame command related options. */ FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour, @@ -410,13 +393,10 @@ FCLI_FLAG("n", "limit", "", &fnc_init.nrecords.zlimit, "Limit depth of blame history to commits or seconds. Denote the" "\n latter by postfixing 's' (e.g., 30s). Useful for large files" " with\n extensive history. Persists for the duration of the " "session."), - FCLI_FLAG_CSTR("R", "repo", "", NULL, - "Use the fossil(1) repository located at for this blame\n" - " invocation."), FCLI_FLAG_BOOL("r", "reverse", &fnc_init.reverse, "Reverse annotate the file starting from a historical commit. " "Rather\n than show the most recent change of each line, show " "the first time\n each line was modified after the specified " "commit. Requires -c|--commit."), @@ -445,13 +425,10 @@ "Show open branches only. Open and closed branches are listed by " "\n default."), FCLI_FLAG_BOOL("p", "no-private", &fnc_init.noprivate, "Do not show private branches, which are otherwise included in the" "\n list of displayed branches by default."), - FCLI_FLAG_CSTR("R", "repo", "", NULL, - "Use the fossil(1) repository located at for this branch\n" - " invocation."), FCLI_FLAG_BOOL("r", "reverse", &fnc_init.reverse, "Reverse the order in which branches are displayed."), FCLI_FLAG("s", "sort", "", &fnc_init.sort, "Sort branches by . Available options are:\n" "\tmru - most recently used\n" @@ -463,23 +440,19 @@ { /* cliflags_config config command related options. */ FCLI_FLAG_BOOL("h", "help", NULL, "Display config command help and usage."), FCLI_FLAG_BOOL(NULL, "ls", &fnc_init.lsconf, "Display a list of all currently defined settings."), - FCLI_FLAG_CSTR("R", "repo", "", NULL, - "Use the fossil(1) repository located at for this config\n" - " invocation."), FCLI_FLAG_BOOL("u", "unset", &fnc_init.unset, "Unset (i.e., remove) the specified repository setting."), fcli_cliflag_empty_m }, /* End cliflags_tree. */ }; enum date_string { ISO8601_DATE_ONLY = 10, - ISO8601_DATE_HHMM = 16, ISO8601_TIMESTAMP = 20 }; enum fnc_view_id { FNC_VIEW_TIMELINE, @@ -500,27 +473,39 @@ SEARCH_CONTINUE, SEARCH_COMPLETE, SEARCH_NO_MATCH, SEARCH_FOR_END }; + +/* + * User-definable setting that must map to SETTINGS in "settings.h". + */ +enum fnc_colour_obj { + FNC_COLOUR_COMMIT = 1, + FNC_COLOUR_USER, + FNC_COLOUR_DATE, + FNC_COLOUR_DIFF_META, + FNC_COLOUR_DIFF_MINUS, + FNC_COLOUR_DIFF_PLUS, + FNC_COLOUR_DIFF_CHUNK, + FNC_COLOUR_DIFF_TAGS, + FNC_COLOUR_TREE_LINK, + FNC_COLOUR_TREE_DIR, + FNC_COLOUR_TREE_EXEC, + FNC_COLOUR_BRANCH_OPEN, + FNC_COLOUR_BRANCH_CLOSED, + FNC_COLOUR_BRANCH_CURRENT, + FNC_COLOUR_BRANCH_PRIVATE +}; enum fnc_diff_type { FNC_DIFF_CKOUT, FNC_DIFF_COMMIT, FNC_DIFF_BLOB, FNC_DIFF_WIKI }; -struct input { - void *data; - char *prompt; - enum input_type type; - bool clear; - char buf[BUFSIZ]; - long ret; -}; - struct fnc_colour { STAILQ_ENTRY(fnc_colour) entries; regex_t regex; uint8_t scheme; }; @@ -635,12 +620,12 @@ * XXX Is there a more elegant solution to retrieving return codes from * thread functions while pinging between, but before we join, threads? */ int rc; bool endjmp; - bool eotl; - bool reset; + bool timeline_end; + bool needs_reset; sig_atomic_t *quit; pthread_cond_t commit_consumer; pthread_cond_t commit_producer; }; @@ -652,14 +637,12 @@ struct commit_entry *selected_commit; struct commit_entry *matched_commit; struct commit_entry *search_commit; struct fnc_colours colours; const char *curr_ckout_uuid; - const char *glob; /* Match commits containing glob. */ - char *path; /* Match commits involving path. */ + char *path; /* Match commits involving path. */ int selected_idx; - int nscrolled; sig_atomic_t quit; pthread_t thread_id; bool colour; }; @@ -669,45 +652,32 @@ size_t pathlen; void *data; /* XXX May want to save id, mode, etc. */ }; TAILQ_HEAD(fnc_pathlist_head, fnc_pathlist_entry); -struct index { - size_t *lineno; - off_t *offset; - uint32_t n; - uint32_t idx; -}; - struct fnc_diff_view_state { struct fnc_view *timeline_view; struct fnc_commit_artifact *selected_commit; struct fnc_pathlist_head *paths; fsl_buffer buf; struct fnc_colours colours; - struct index index; FILE *f; fsl_uuid_str id1; fsl_uuid_str id2; int first_line_onscreen; int last_line_onscreen; int diff_flags; int context; int sbs; int matched_line; - int selected_line; - int maxx; - int lineno; - int gtl; + int current_line; size_t ncols; size_t nlines; - enum line_attr sline; off_t *line_offsets; bool eof; bool colour; bool showmeta; - bool showln; }; TAILQ_HEAD(fnc_parent_trees, fnc_parent_tree); struct fnc_tree_view_state { /* Parent trees of the- */ struct fnc_parent_trees parents; /* -current subtree. */ @@ -724,26 +694,23 @@ fsl_id_t rid; int ndisplayed; int selected_idx; bool colour; bool show_id; - bool show_date; }; struct fnc_blame_line { fsl_uuid_str id; - unsigned int lineno; bool annotated; }; struct fnc_blame_cb_cx { struct fnc_view *view; struct fnc_blame_line *lines; fsl_uuid_str commit_id; fsl_uuid_str root_commit; int nlines; - uint32_t maxlen; bool *quit; }; typedef int (*fnc_cancel_cb)(void *); @@ -786,17 +753,14 @@ int first_line_onscreen; int last_line_onscreen; int selected_line; int matched_line; int spin_idx; - int gtl; - uint32_t *maxx; bool done; bool blame_complete; bool eof; bool colour; - bool showln; }; struct fnc_branch { char *name; char *date; @@ -838,49 +802,33 @@ bool colour; bool show_date; bool show_id; }; -struct line { - char buf[BUFSIZ]; - int sz; - enum line_type type; - bool selected; -}; - -struct position { - int col; - int line; - int offset; -}; - TAILQ_HEAD(view_tailhead, fnc_view); struct fnc_view { TAILQ_ENTRY(fnc_view) entries; WINDOW *window; PANEL *panel; struct fnc_view *parent; struct fnc_view *child; - struct line line; - struct position pos; union { struct fnc_diff_view_state diff; struct fnc_tl_view_state timeline; struct fnc_tree_view_state tree; struct fnc_blame_view_state blame; struct fnc_branch_view_state branch; } state; enum fnc_view_id vid; - enum view_mode mode; enum fnc_search_state search_status; enum fnc_search_mvmnt searching; - int nlines; /* Dependent on split height. */ - int ncols; /* Dependent on split width. */ + int nlines; + int ncols; int start_ln; int start_col; - int lines; /* Always curses LINES macro */ - int cols; /* Always curses COLS macro. */ + int lines; /* Duplicate curses LINES macro. */ + int cols; /* Duplicate curses COLS macro. */ bool focus_child; bool active; /* Only 1 parent or child at a time. */ bool egress; bool started_search; regex_t regex; @@ -887,21 +835,20 @@ regmatch_t regmatch; int (*show)(struct fnc_view *); int (*input)(struct fnc_view **, struct fnc_view *, int); int (*close)(struct fnc_view *); - void (*grep_init)(struct fnc_view *); - int (*grep)(struct fnc_view *); + int (*search_init)(struct fnc_view *); + int (*search_next)(struct fnc_view *); }; static volatile sig_atomic_t rec_sigwinch; static volatile sig_atomic_t rec_sigpipe; static volatile sig_atomic_t rec_sigcont; static void fnc_show_version(void); static int init_curses(void); -static int fnc_set_signals(void); static struct fnc_view *view_open(int, int, int, int, enum fnc_view_id); static int open_timeline_view(struct fnc_view *, fsl_id_t, const char *, const char *); static int view_loop(struct fnc_view *); static int show_timeline_view(struct fnc_view *); @@ -911,50 +858,36 @@ static int commit_builder(struct fnc_commit_artifact **, fsl_id_t, fsl_stmt *); static int signal_tl_thread(struct fnc_view *, int); static int draw_commits(struct fnc_view *); static void parse_emailaddr_username(char **); -static int formatln(wchar_t **, int *, const char *, int, int, - size_t, bool); -static size_t expand_tab(char *, size_t, const char *, int); +static int formatln(wchar_t **, int *, const char *, int, int); static int multibyte_to_wchar(const char *, wchar_t **, size_t *); static int write_commit_line(struct fnc_view *, struct fnc_commit_artifact *, int); static int view_input(struct fnc_view **, int *, struct fnc_view *, struct view_tailhead *); -static int cycle_view(struct fnc_view *); -static int toggle_fullscreen(struct fnc_view **, - struct fnc_view *); static int help(struct fnc_view *); static int padpopup(struct fnc_view *, int, int, FILE *, const char *); static void centerprint(WINDOW *, int, int, int, const char *, chtype); static int tl_input_handler(struct fnc_view **, struct fnc_view *, int); -static int move_tl_cursor_down(struct fnc_view *, uint16_t); -static void move_tl_cursor_up(struct fnc_view *, uint16_t, bool); static int timeline_scroll_down(struct fnc_view *, int); static void timeline_scroll_up(struct fnc_tl_view_state *, int); static void select_commit(struct fnc_tl_view_state *); -static int request_view(struct fnc_view **, struct fnc_view *, - enum fnc_view_id); -static int init_view(struct fnc_view **, struct fnc_view *, - enum fnc_view_id, int, int); -static enum view_mode view_get_split(struct fnc_view *, int *, int *); -static int split_view(struct fnc_view *, int *); -static int offset_selected_line(struct fnc_view *); -static int view_split_start_col(int); -static int view_split_start_ln(int); +static int view_is_parent(struct fnc_view *); static int make_splitscreen(struct fnc_view *); static int make_fullscreen(struct fnc_view *); +static int view_split_start_col(int); static int view_search_start(struct fnc_view *); -static void tl_grep_init(struct fnc_view *); +static int tl_search_init(struct fnc_view *); static int tl_search_next(struct fnc_view *); static bool find_commit_match(struct fnc_commit_artifact *, regex_t *); -static int init_diff_view(struct fnc_view **, int, int, +static int init_diff_commit(struct fnc_view **, int, struct fnc_commit_artifact *, struct fnc_view *); static int open_diff_view(struct fnc_view *, struct fnc_commit_artifact *, int, bool, bool, bool, struct fnc_view *, bool, struct fnc_pathlist_head *); @@ -963,48 +896,41 @@ static int create_changeset(struct fnc_commit_artifact *); static int write_commit_meta(struct fnc_diff_view_state *); static int wrapline(char *, fsl_size_t ncols_avail, struct fnc_diff_view_state *, off_t *); static int add_line_offset(off_t **, size_t *, off_t); -static int diff_commit(struct fnc_diff_view_state *); -static int diff_checkout(struct fnc_diff_view_state *); +static int diff_commit(fsl_buffer *, struct fnc_commit_artifact *, + int, int, int, struct fnc_pathlist_head *); +static int diff_checkout(fsl_buffer *, fsl_id_t, int, int, int, + struct fnc_pathlist_head *); static int write_diff_meta(fsl_buffer *, const char *, fsl_uuid_str, const char *, fsl_uuid_str, int, enum fsl_ckout_change_e); -static int diff_file(struct fnc_diff_view_state *, fsl_buffer *, - const char *, fsl_uuid_str, const char *, - enum fsl_ckout_change_e); -static int fnc_diff_builder(fsl_dibu **, fsl_uuid_cstr, - fsl_uuid_cstr, const char *, const char *, int, - int, fsl_buffer *); -static void fnc_free_diff_builder(fsl_dibu *); +static int diff_file(fsl_buffer *, fsl_buffer *, const char *, + fsl_uuid_str, const char *, enum fsl_ckout_change_e, + int, int, bool); static int diff_non_checkin(fsl_buffer *, struct fnc_commit_artifact *, int, int, int); -static int diff_file_artifact(struct fnc_diff_view_state *, - fsl_id_t, const fsl_card_F *, const fsl_card_F *, - fsl_ckout_change_e); +static int diff_file_artifact(fsl_buffer *, fsl_id_t, + const fsl_card_F *, fsl_id_t, const fsl_card_F *, + fsl_ckout_change_e, int, int, int, + enum fnc_diff_type); static int show_diff(struct fnc_view *); static int write_diff(struct fnc_view *, char *); static int match_line(const char *, regex_t *, size_t, regmatch_t *); -static int draw_matched_line(struct fnc_view *, int *, - int, regmatch_t *, attr_t); -static void drawborder(struct fnc_view *); +static int write_matched_line(int *, const char *, int, int, + WINDOW *, regmatch_t *); +static void draw_vborder(struct fnc_view *); static int diff_input_handler(struct fnc_view **, struct fnc_view *, int); -static int request_tl_commits(struct fnc_view *); -static int reset_diff_view(struct fnc_view *, bool); static int set_selected_commit(struct fnc_diff_view_state *, struct commit_entry *); -static void diff_grep_init(struct fnc_view *); -static int find_next_match(struct fnc_view *); -static void grep_set_view(struct fnc_view *, FILE **, off_t **, - size_t *, int **, int **, int **, int **); +static int diff_search_init(struct fnc_view *); +static int diff_search_next(struct fnc_view *); static int view_close(struct fnc_view *); static int map_repo_path(char **); -static int init_timeline_view(struct fnc_view **, int, int, - fsl_id_t, const char *, const char *); static bool path_is_child(const char *, const char *, size_t); static int path_skip_common_ancestor(char **, const char *, size_t, const char *, size_t); static bool fnc_path_is_root_dir(const char *); /* static bool fnc_path_is_cwd(const char *); */ @@ -1011,11 +937,11 @@ static int fnc_pathlist_insert(struct fnc_pathlist_entry **, struct fnc_pathlist_head *, const char *, void *); static int fnc_path_cmp(const char *, const char *, size_t, size_t); static void fnc_pathlist_free(struct fnc_pathlist_head *); -static int browse_commit_tree(struct fnc_view **, int, int, +static int browse_commit_tree(struct fnc_view **, int, struct commit_entry *, const char *); static int open_tree_view(struct fnc_view *, const char *, fsl_id_t); static int walk_tree_path(struct fnc_tree_view_state *, struct fnc_repository_tree *, @@ -1025,28 +951,26 @@ static int tree_builder(struct fnc_repository_tree *, struct fnc_tree_object **, const char *); /* static void delete_tree_node(struct fnc_tree_entry **, */ /* struct fnc_tree_entry *); */ static int link_tree_node(struct fnc_repository_tree *, - const char *, const char *, double); + const char *, const char *, fsl_time_t); static int show_tree_view(struct fnc_view *); static int tree_input_handler(struct fnc_view **, struct fnc_view *, int); -static int blame_tree_entry(struct fnc_view **, int, int, +static int blame_tree_entry(struct fnc_view **, int, struct fnc_tree_entry *, struct fnc_parent_trees *, fsl_uuid_str); -static void tree_grep_init(struct fnc_view *); +static int tree_search_init(struct fnc_view *); static int tree_search_next(struct fnc_view *); static int tree_entry_path(char **, struct fnc_parent_trees *, struct fnc_tree_entry *); static int draw_tree(struct fnc_view *, const char *); -static int blame_selected_file(struct fnc_view **, - struct fnc_view *); static int timeline_tree_entry(struct fnc_view **, int, struct fnc_tree_view_state *); static void tree_scroll_up(struct fnc_tree_view_state *, int); -static int tree_scroll_down(struct fnc_view *, int); +static void tree_scroll_down(struct fnc_tree_view_state *, int); static int visit_subtree(struct fnc_tree_view_state *, struct fnc_tree_object *); static int tree_entry_get_symlink_target(char **, struct fnc_tree_entry *); static int match_tree_entry(struct fnc_tree_entry *, regex_t *); @@ -1062,11 +986,12 @@ static int blame_cb(void *, fsl_annotate_opt const * const, fsl_annotate_step const * const); static int draw_blame(struct fnc_view *); static int blame_input_handler(struct fnc_view **, struct fnc_view *, int); -static void blame_grep_init(struct fnc_view *); +static int blame_search_init(struct fnc_view *); +static int blame_search_next(struct fnc_view *); static fsl_uuid_cstr get_selected_commit_id(struct fnc_blame_line *, int, int, int); static int fnc_commit_qid_alloc(struct fnc_commit_qid **, fsl_uuid_cstr); static int close_blame_view(struct fnc_view *); @@ -1082,67 +1007,56 @@ static int open_branch_view(struct fnc_view *, int, const char *, double, int); static int show_branch_view(struct fnc_view *); static int branch_input_handler(struct fnc_view **, struct fnc_view *, int); +static int tl_branch_entry(struct fnc_view **, int, + struct fnc_branchlist_entry *); static int browse_branch_tree(struct fnc_view **, int, struct fnc_branchlist_entry *); static void branch_scroll_up(struct fnc_branch_view_state *, int); -static int branch_scroll_down(struct fnc_view *, int); +static void branch_scroll_down(struct fnc_branch_view_state *, + int); static int branch_search_next(struct fnc_view *); -static void branch_grep_init(struct fnc_view *); +static int branch_search_init(struct fnc_view *); static int match_branchlist_entry(struct fnc_branchlist_entry *, regex_t *); static int close_branch_view(struct fnc_view *); static void fnc_free_branches(struct fnc_branchlist_head *); static void fnc_branch_close(struct fnc_branch *); -static bool view_is_parent(struct fnc_view *); static void view_set_child(struct fnc_view *, struct fnc_view *); static int view_close_child(struct fnc_view *); static int close_tree_view(struct fnc_view *); static int close_timeline_view(struct fnc_view *); static int close_diff_view(struct fnc_view *); -static void free_index(struct index *); -static int view_resize(struct fnc_view *, enum view_mode); -static bool screen_is_split(struct fnc_view *); +static int view_resize(struct fnc_view *); +static int screen_is_split(struct fnc_view *); static bool screen_is_shared(struct fnc_view *); -static void updatescreen(WINDOW *, bool, bool); static void fnc_resizeterm(void); static int join_tl_thread(struct fnc_tl_view_state *); static void fnc_free_commits(struct commit_queue *); static void fnc_commit_artifact_close(struct fnc_commit_artifact*); static int fsl_file_artifact_free(void *, void *); static void sigwinch_handler(int); static void sigpipe_handler(int); static void sigcont_handler(int); -static int draw_lineno(struct fnc_view *, int, int, attr_t); -static bool gotoline(struct fnc_view *, int *, int *); -static int strtonumcheck(long *, const char *, const int, +static int strtonumcheck(int *, const char *, const int, const int); -static int fnc_prompt_input(struct fnc_view *, struct input *); static int fnc_date_to_mtime(double *, const char *, int); -static int cook_input(char *, int, WINDOW *); -static void fnc_print_msg(struct fnc_view *, const char *, bool, - bool, bool); static char *fnc_strsep (char **, const char *); -static bool fnc_str_has_upper(const char *); -static int fnc_make_sql_glob(char **, char **, const char *, bool); -#ifdef __OpenBSD__ -static int init_unveil(const char *, const char *, bool); -#endif static int set_colours(struct fnc_colours *, enum fnc_view_id); static int set_colour_scheme(struct fnc_colours *, const int (*)[2], const char **, int); -static int init_colour(enum fnc_opt_id); -static int default_colour(enum fnc_opt_id); +static int init_colour(enum fnc_colour_obj); +static char *fnc_conf_get(enum fnc_colour_obj, bool); +static int default_colour(enum fnc_colour_obj); +static int fnc_conf_set(enum fnc_colour_obj, const char *, bool); static void free_colours(struct fnc_colours *); static bool fnc_home(struct fnc_view *); -static char *fnc_conf_getopt(enum fnc_opt_id, bool); -static int fnc_conf_setopt(enum fnc_opt_id, const char *, bool); -static int fnc_conf_lsopt(bool); -static enum fnc_opt_id fnc_conf_str2enum(const char *); -static const char *fnc_conf_enum2str(enum fnc_opt_id); +static int fnc_conf_ls_settings(bool); +static int fnc_conf_str2enum(const char *); +static const char *fnc_conf_enum2str(int); static struct fnc_colour *get_colour(struct fnc_colours *, int); static struct fnc_colour *match_colour(struct fnc_colours *, const char *); static struct fnc_tree_entry *get_tree_entry(struct fnc_tree_object *, int); @@ -1161,12 +1075,13 @@ fnc_init.cmdarg = argv[1]; /* Which cmd to show usage if needed. */ #if DEBUG fcli.clientFlags.verbose = 2; /* Verbose error reporting. */ #endif - rc = fcli_setup_v2(argc, argv, fnc_init.cliflags_global, - &fnc_init.fnc_help); + fcli.cliFlags = fnc_init.cliflags_global; + fcli.appHelp = &fnc_init.fnc_help; + rc = fcli_setup(argc, argv); if (rc) goto end; if (fnc_init.vflag) { fnc_show_version(); @@ -1173,22 +1088,10 @@ goto end; } else if (fnc_init.hflag) usage(); /* NOT REACHED */ -#ifdef __OpenBSD__ - /* - * See pledge(2). This is the most restrictive set we can operate under. - * Look for any adverse impact & revise when implementing new features. - * stdio (close, sigaction); rpath (chdir getcwd lstat); wpath (getcwd); - * cpath (symlink); flock (open); tty (TIOCGWINSZ); unveil (unveil). - */ - if (pledge("stdio rpath wpath cpath flock tty unveil", NULL) == -1) { - rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), "%s", "pledge"); - goto end; - } -#endif rc = fcli_fingerprint_check(true); if (rc) goto end; if (argc == 1) @@ -1277,47 +1180,27 @@ if (fnc_init.glob) glob = fsl_strdup(fnc_init.glob); if (fnc_init.path) path = fsl_strdup(fnc_init.path); - else { + else rc = map_repo_path(&path); - if (rc) - goto end; - } - - rc = init_curses(); - if (rc) - goto end; -#ifdef __OpenBSD__ - rc = init_unveil(fsl_cx_db_file_repo(f, NULL), - fsl_cx_ckout_dir_name(f, NULL), false); - if (rc) - goto end; -#endif - - rc = init_timeline_view(&v, 0, 0, rid, path, glob); + if (!rc) + rc = init_curses(); + if (rc) + goto end; + v = view_open(0, 0, 0, 0, FNC_VIEW_TIMELINE); + if (v == NULL) { + rc = RC(FSL_RC_ERROR, "%s", "view_open"); + goto end; + } + rc = open_timeline_view(v, rid, path, glob); if (!rc) rc = view_loop(v); end: fsl_free(glob); fsl_free(path); - return rc; -} - -static int -init_timeline_view(struct fnc_view **view, int x, int y, fsl_id_t rid, - const char *path, const char *glob) -{ - int rc = FSL_RC_OK; - - *view = view_open(0, 0, y, x, FNC_VIEW_TIMELINE); - if (view == NULL) - rc = RC(FSL_RC_ERROR, "%s", "view_open"); - if (!rc) - rc = open_timeline_view(*view, rid, path, glob); - return rc; } /* * Look for an in-repository path in **argv. If found, canonicalise it as an @@ -1563,11 +1446,10 @@ cbreak(); noecho(); nonl(); intrflush(stdscr, FALSE); keypad(stdscr, TRUE); - raw(); /* Don't signal control characters, specifically C-y */ curs_set(0); set_escdelay(0); /* ESC should return immediately. */ #ifndef __linux__ typeahead(-1); /* Don't disrupt screen update operations. */ #endif @@ -1575,16 +1457,10 @@ if (!fnc_init.nocolour && has_colors()) { start_color(); use_default_colors(); } - return fnc_set_signals(); -} - -static int -fnc_set_signals(void) -{ if (sigaction(SIGPIPE, &(struct sigaction){{sigpipe_handler}}, NULL) == -1) return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "sigaction(SIGPIPE)"); if (sigaction(SIGWINCH, &(struct sigaction){{sigwinch_handler}}, NULL) @@ -1594,11 +1470,11 @@ if (sigaction(SIGCONT, &(struct sigaction){{sigcont_handler}}, NULL) == -1) return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "sigaction(SIGCONT)"); - return FSL_RC_OK; + return 0; } static struct fnc_view * view_open(int nlines, int ncols, int start_ln, int start_col, enum fnc_view_id vid) @@ -1637,13 +1513,14 @@ struct fnc_tl_view_state *s = &view->state.timeline; fsl_cx *const f = fcli_cx(); fsl_db *db = fsl_cx_db_repo(f); fsl_buffer sql = fsl_buffer_empty; char *startdate = NULL; - char *op = NULL, *str = NULL; fsl_id_t idtag = 0; - int idx, rc = FSL_RC_OK; + int idx, rc = 0; + + f->clientState.state = &s->thread_cx; if (path != s->path) { fsl_free(s->path); s->path = fsl_strdup(path); if (s->path == NULL) @@ -1737,87 +1614,67 @@ fnc_init.filter_types.values[idx], (idx + 1) < fnc_init.filter_types.nitems ? " OR " : ")"); } if (fnc_init.filter_branch) { - rc = fnc_make_sql_glob(&op, &str, fnc_init.filter_branch, - !fnc_str_has_upper(fnc_init.filter_branch)); - if (rc) - goto end; idtag = fsl_db_g_id(db, 0, - "SELECT tagid FROM tag WHERE tagname %q 'sym-%q'" - " ORDER BY tagid DESC", op, str); - if (idtag) { - rc = fsl_buffer_appendf(&sql, + "SELECT tagid FROM tag WHERE tagname='sym-%q'", + fnc_init.filter_branch); + if (idtag > 0) + fsl_buffer_appendf(&sql, " AND EXISTS(SELECT 1 FROM tagxref" " WHERE tagid=%"FSL_ID_T_PFMT " AND tagtype > 0 AND rid=blob.rid)", idtag); - if (rc) - goto end; - } else { - rc = RC(FSL_RC_NOT_FOUND, "branch not found: %s", + else { + rc = RC(FSL_RC_NOT_FOUND, "Invalid branch name [%s]", fnc_init.filter_branch); goto end; } } if (fnc_init.filter_tag) { - /* Lookup non-branch tag first; if not found, lookup branch. */ - rc = fnc_make_sql_glob(&op, &str, fnc_init.filter_tag, - !fnc_str_has_upper(fnc_init.filter_tag)); - if (rc) - goto end; idtag = fsl_db_g_id(db, 0, - "SELECT tagid FROM tag WHERE tagname %q '%q'" - " ORDER BY tagid DESC", op, str); + "SELECT tagid FROM tag WHERE tagname GLOB 'sym-%q'", + fnc_init.filter_tag); if (idtag == 0) idtag = fsl_db_g_id(db, 0, - "SELECT tagid FROM tag WHERE tagname %q 'sym-%q'" - " ORDER BY tagid DESC", op, str); - if (idtag) { - rc = fsl_buffer_appendf(&sql, + "SELECT tagid FROM tag WHERE tagname='%q'", + fnc_init.filter_tag); + if (idtag > 0) + fsl_buffer_appendf(&sql, " AND EXISTS(SELECT 1 FROM tagxref" " WHERE tagid=%"FSL_ID_T_PFMT " AND tagtype > 0 AND rid=blob.rid)", idtag); - if (rc) - goto end; - } else { - rc = RC(FSL_RC_NOT_FOUND, "tag not found: %s", + else { + rc = RC(FSL_RC_NOT_FOUND, "Invalid tag [%s]", fnc_init.filter_tag); goto end; } } - if (fnc_init.filter_user) { - rc = fnc_make_sql_glob(&op, &str, fnc_init.filter_user, - !fnc_str_has_upper(fnc_init.filter_user)); - if (rc) - goto end; - rc = fsl_buffer_appendf(&sql, - " AND coalesce(euser, user) %q '%q'", op, str); - if (rc) - goto end; - } + if (fnc_init.filter_user) + if ((rc = fsl_buffer_appendf(&sql, + " AND coalesce(euser, user) GLOB lower('*%q*')", + fnc_init.filter_user))) + goto end; if (glob) { /* Filter commits on comment, user, and branch name. */ - rc = fnc_make_sql_glob(&op, &str, glob, - !fnc_str_has_upper(glob)); - if (rc) - goto end; + char *like = fsl_mprintf("%%%%%s%%%%", glob); idtag = fsl_db_g_id(db, 0, - "SELECT tagid FROM tag WHERE tagname %q 'sym-%q'" - " ORDER BY tagid DESC", op, str); + "SELECT tagid FROM tag WHERE tagname LIKE 'sym-%q'", + like); rc = fsl_buffer_appendf(&sql, - " AND (coalesce(ecomment, comment) %q %Q" - " OR coalesce(euser, user) %q %Q%c", - op, str, op, str, idtag ? ' ' : ')'); + " AND (coalesce(ecomment, comment) LIKE %Q " + " OR coalesce(euser, user) LIKE %Q%c", + like, like, idtag ? ' ' : ')'); if (!rc && idtag > 0) rc = fsl_buffer_appendf(&sql, " OR EXISTS(SELECT 1 FROM tagxref" " WHERE tagid=%"FSL_ID_T_PFMT " AND tagtype > 0 AND rid=blob.rid))", idtag); + fsl_free(like); if (rc) goto end; } if (startdate) { @@ -1832,11 +1689,11 @@ if (path[1]) { fsl_buffer_appendf(&sql, " AND EXISTS(SELECT 1 FROM mlink" " WHERE mlink.mid = event.objid" " AND mlink.fnid IN "); - if (fsl_cx_is_case_sensitive(f,false)) { + if (fsl_cx_is_case_sensitive(f)) { fsl_buffer_appendf(&sql, "(SELECT fnid FROM filename" " WHERE name = %Q OR name GLOB '%q/*')", path + 1, path + 1); /* Skip prepended slash. */ } else { @@ -1855,12 +1712,12 @@ fsl_buffer_appendf(&sql, " LIMIT %d", fnc_init.nrecords.limit); view->show = show_timeline_view; view->input = tl_input_handler; view->close = close_timeline_view; - view->grep_init = tl_grep_init; - view->grep = tl_search_next; + view->search_init = tl_search_init; + view->search_next = tl_search_next; s->thread_cx.q = fsl_stmt_malloc(); rc = fsl_db_prepare(db, s->thread_cx.q, "%b", &sql); if (rc) { rc = RC(rc, "%s", "fsl_db_prepare"); @@ -1883,33 +1740,28 @@ s->thread_cx.rc = 0; s->thread_cx.db = db; s->thread_cx.spin_idx = 0; s->thread_cx.ncommits_needed = view->nlines - 1; s->thread_cx.commits = &s->commits; - s->thread_cx.eotl = false; + s->thread_cx.timeline_end = false; s->thread_cx.quit = &s->quit; s->thread_cx.first_commit_onscreen = &s->first_commit_onscreen; s->thread_cx.selected_commit = &s->selected_commit; s->thread_cx.searching = &view->searching; s->thread_cx.search_status = &view->search_status; s->thread_cx.regex = &view->regex; s->thread_cx.path = s->path; - s->thread_cx.reset = true; + s->thread_cx.needs_reset = false; if (s->colour) { STAILQ_INIT(&s->colours); rc = set_colours(&s->colours, FNC_VIEW_TIMELINE); } end: fsl_buffer_clear(&sql); - fsl_free(op); - fsl_free(str); if (rc) { - if (view->close) - view_close(view); - else - close_timeline_view(view); + view_close(view); if (db->error.code) rc = fsl_cx_uplift_db_error(f, db); } return rc; } @@ -1946,15 +1798,10 @@ prev = view->parent; if (view->parent) { view->parent->child = NULL; view->parent->focus_child = false; - /* Restore fullscreen line height. */ - view->parent->nlines = view->parent->lines; - rc = view_resize(view->parent, VIEW_SPLIT_NONE); - if (rc) - goto end; } else TAILQ_REMOVE(&views, view, entries); rc = view_close(view); if (rc) @@ -2015,15 +1862,22 @@ rc = view->show(view); if (rc) goto end; if (view->child) { rc = view->child->show(view->child); +#ifdef __linux__ + wnoutrefresh(view->child->window); +#endif if (rc) goto end; - updatescreen(view->child->window, false, false); } - updatescreen(view->window, true, true); +#ifdef __linux__ + wnoutrefresh(view->window); +#else + update_panels(); +#endif + doupdate(); } } end: while (!TAILQ_EMPTY(&views)) { view = TAILQ_FIRST(&views); @@ -2121,18 +1975,18 @@ if ((rc = pthread_mutex_unlock(&fnc_mutex))) rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS), "%s", "pthread_mutex_unlock"); } - cx->eotl = true; + cx->timeline_end = true; return (void *)(intptr_t)rc; } static int block_main_thread_signals(void) { - sigset_t set; + sigset_t set; if (sigemptyset(&set) == -1) return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s", "sigemptyset"); @@ -2151,27 +2005,28 @@ if (pthread_sigmask(SIG_BLOCK, &set, NULL)) return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s", "pthread_sigmask"); - return FSL_RC_OK; + return 0; } static int build_commits(struct fnc_tl_thread_cx *cx) { int rc = 0; - if (cx->reset && cx->commits->ncommits) { + if (cx->needs_reset) { /* - * If a child view was opened, there may be cached stmts that - * necessitate resetting the commit builder stmt. Otherwise one - * of the APIs down the fsl_stmt_step() call stack fails; - * irrespective of whether fsl_db_prepare_cached() was used. + * XXX If a {tree,branch} view has been opened with the '{t,b}' + * key binding, there may be cached statements that necessitate + * the commit builder statement being reset otherwise one of the + * SQLite3 APIs down the fsl_stmt_step() call stack fails. This + * is irrespective of whether fsl_db_prepare_cached() was used. */ fsl_size_t loaded = cx->commits->ncommits + 1; - cx->reset = false; + cx->needs_reset = false; rc = fsl_stmt_reset(cx->q); if (rc) return RC(rc, "%s", "fsl_stmt_reset"); while (loaded--) if ((rc = fsl_stmt_step(cx->q)) != FSL_RC_STEP_ROW) @@ -2357,11 +2212,11 @@ { struct fnc_tl_thread_cx *cx = &view->state.timeline.thread_cx; int rc = 0; while (cx->ncommits_needed > 0) { - if (cx->eotl) + if (cx->timeline_end) break; /* Wake timeline thread. */ if ((rc = pthread_cond_signal(&cx->commit_consumer))) return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE), @@ -2403,11 +2258,10 @@ const char *search_str = NULL; char *headln = NULL, *idxstr = NULL; char *branch = NULL, *type = NULL; char *uuid = NULL; wchar_t *wcstr; - attr_t rx = A_BOLD; int ncommits = 0, rc = 0, wstrlen = 0; int ncols_needed, max_usrlen = -1; if (s->selected_commit && !(view->searching != SEARCH_DONE && view->search_status == SEARCH_WAITING)) { @@ -2414,11 +2268,11 @@ uuid = fsl_strdup(s->selected_commit->commit->uuid); branch = fsl_strdup(s->selected_commit->commit->branch); type = fsl_strdup(s->selected_commit->commit->type); } - if (tcx->ncommits_needed > 0 && !tcx->eotl) { + if (s->thread_cx.ncommits_needed > 0) { if ((idxstr = fsl_mprintf(" [%d/%d] %s", entry ? entry->idx + 1 : 0, s->commits.ncommits, (view->searching && !view->search_status) ? "searching..." : "loading...")) == NULL) { rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf"); @@ -2474,29 +2328,31 @@ headln = NULL; goto end; } if (SPINNER[++tcx->spin_idx] == '\0') tcx->spin_idx = 0; - rc = formatln(&wcstr, &wstrlen, headln, view->ncols, 0, 0, false); + rc = formatln(&wcstr, &wstrlen, headln, view->ncols, 0); if (rc) goto end; werase(view->window); - if (screen_is_shared(view) || view->active) - rx |= A_REVERSE; + if (screen_is_shared(view)) + wattron(view->window, A_REVERSE); if (s->colour) c = get_colour(&s->colours, FNC_COLOUR_COMMIT); if (c) - rx |= COLOR_PAIR(c->scheme); - wattron(view->window, rx); + wattr_on(view->window, COLOR_PAIR(c->scheme), NULL); waddwstr(view->window, wcstr); while (wstrlen < view->ncols) { waddch(view->window, ' '); ++wstrlen; } - wattroff(view->window, rx); + if (c) + wattr_off(view->window, COLOR_PAIR(c->scheme), NULL); + if (screen_is_shared(view)) + wattroff(view->window, A_REVERSE); fsl_free(wcstr); if (view->nlines <= 1) goto end; /* Parse commits to be written on screen for the longest username. */ @@ -2512,12 +2368,11 @@ rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup"); goto end; } if (strpbrk(user, "<@>") != NULL) parse_emailaddr_username(&user); - rc = formatln(&usr_wcstr, &usrlen, user, view->ncols, 0, 0, - false); + rc = formatln(&usr_wcstr, &usrlen, user, view->ncols, 0); if (max_usrlen < usrlen) max_usrlen = usrlen; fsl_free(usr_wcstr); fsl_free(user); ++ncommits; @@ -2526,11 +2381,11 @@ ncommits = 0; entry = s->first_commit_onscreen; s->last_commit_onscreen = s->first_commit_onscreen; while (entry) { - if (ncommits >= MIN(view->nlines - 1, view->lines - 1)) + if (ncommits >= view->nlines - 1) break; if (ncommits == s->selected_idx) wattr_on(view->window, A_REVERSE, NULL); rc = write_commit_line(view, entry->commit, max_usrlen); if (ncommits == s->selected_idx) @@ -2537,11 +2392,11 @@ wattr_off(view->window, A_REVERSE, NULL); ++ncommits; s->last_commit_onscreen = entry; entry = TAILQ_NEXT(entry, entries); } - drawborder(view); + draw_vborder(view); end: free(branch); free(type); free(uuid); @@ -2566,29 +2421,20 @@ *username = usr; } static int formatln(wchar_t **ptr, int *wstrlen, const char *mbstr, int column_limit, - int start_column, size_t skip, bool expand) + int start_column) { wchar_t *wline = NULL; - static char exstr[BUFSIZ]; - size_t i, sz, wlen; - int cols = 0, rc = FSL_RC_OK; + size_t i, wlen; + int rc = 0, cols = 0; *ptr = NULL; *wstrlen = 0; - sz = fsl_strlen(mbstr); - - if (expand) { - sz = expand_tab(exstr, sizeof(exstr), mbstr, sz); - mbstr = exstr; - } - if (skip) - skip = MIN(skip, sz); - - rc = multibyte_to_wchar(mbstr + skip, &wline, &wlen); + + rc = multibyte_to_wchar(mbstr, &wline, &wlen); if (rc) return rc; if (wlen > 0 && wline[wlen - 1] == L'\n') { wline[wlen - 1] = L'\0'; @@ -2614,11 +2460,11 @@ cols += width; i++; } else if (width == -1) { if (wline[i] == L'\t') { width = TABSIZE - - ((cols + start_column) % TABSIZE); + ((cols + column_limit) % TABSIZE); } else { width = 1; wline[i] = L'.'; } if (cols + width > column_limit) @@ -2639,40 +2485,10 @@ else *ptr = wline; return rc; } -/* - * Copy the string src into the statically sized dst char array, and expand - * any tab ('\t') characters found into the equivalent number of space (' ') - * characters. Return number of bytes written to dst minus the terminating NUL. - */ -static size_t -expand_tab(char *dst, size_t dstlen, const char *src, int srclen) -{ - size_t sz = 0; - int idx = 0; - - while (sz < dstlen - 1 && idx < srclen && src[idx]) { - const char c = *(src + idx); - - if (c == '\t') { - size_t spaces = TABSIZE - (sz % TABSIZE); - if (spaces + sz >= dstlen - 1) - spaces = dstlen - sz - 1; - memcpy(dst + sz, " ", spaces); - sz += spaces; - } else { - dst[sz++] = src[idx]; - } - ++idx; - } - - dst[sz] = '\0'; - return sz; -} - static int multibyte_to_wchar(const char *src, wchar_t **dst, size_t *dstlen) { int rc = 0; @@ -2775,11 +2591,11 @@ if (user == NULL) goto end; if (strpbrk(user, "<@>") != NULL) parse_emailaddr_username(&user); rc = formatln(&usr_wcstr, &usrlen, user, view->ncols - col_pos, - col_pos, 0, false); + col_pos); if (rc) goto end; if (s->colour) c = get_colour(&s->colours, FNC_COLOUR_USER); if (c) @@ -2802,12 +2618,11 @@ ++comment; eol = strchr(comment, '\n'); if (eol) *eol = '\0'; ncols_avail = view->ncols - col_pos; - rc = formatln(&wcomment, &commentlen, comment, ncols_avail, col_pos, 0, - false); + rc = formatln(&wcomment, &commentlen, comment, ncols_avail, col_pos); if (rc) goto end; waddwstr(view->window, wcomment); col_pos += commentlen; while (col_pos < view->ncols) { @@ -2844,11 +2659,11 @@ "%s", "pthread_mutex_unlock"); sched_yield(); if ((rc = pthread_mutex_lock(&fnc_mutex))) return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS), "%s", "pthread_mutex_lock"); - rc = view->grep(view); + rc = view->search_next(view); return rc; } nodelay(stdscr, FALSE); /* Allow thread to make progress while waiting for input. */ @@ -2863,19 +2678,16 @@ if (rec_sigwinch || rec_sigcont) { fnc_resizeterm(); rec_sigwinch = 0; rec_sigcont = 0; TAILQ_FOREACH(v, views, entries) { - rc = view_resize(v, v->mode); - if (rc) + if ((rc = view_resize(v))) return rc; - rc = v->input(new, v, KEY_RESIZE); - if (rc) + if ((rc = v->input(new, v, KEY_RESIZE))) return rc; if (v->child) { - rc = view_resize(v->child, v->child->mode); - if (rc) + if ((rc = view_resize(v->child))) return rc; rc = v->child->input(new, v->child, KEY_RESIZE); if (rc) return rc; } @@ -2882,124 +2694,82 @@ } } switch (ch) { case '\t': - rc = cycle_view(view); + if (view->child) { + view->active = false; + view->child->active = true; + view->focus_child = true; + } else if (view->parent) { + view->active = false; + view->parent->active = true; + view->parent->focus_child = false; + } break; case KEY_F(1): case 'H': case '?': help(view); break; case 'q': - if (view->parent && view->parent->vid == FNC_VIEW_TIMELINE && - view->mode == VIEW_SPLIT_HRZN) { - /* May need more commits to fill fullscreen. */ - rc = request_tl_commits(view->parent); - view->parent->mode = VIEW_SPLIT_NONE; - } rc = view->input(new, view, ch); view->egress = true; break; case 'f': - rc = toggle_fullscreen(new, view); + if (view_is_parent(view)) { + if (view->child == NULL) + break; + if (screen_is_split(view->child)) { + view->active = false; + view->child->active = true; + rc = make_fullscreen(view->child); + } else + rc = make_splitscreen(view->child); + if (rc) + break; + rc = view->child->input(new, view->child, KEY_RESIZE); + } else { + if (screen_is_split(view)) { + view->parent->active = false; + view->active = true; + rc = make_fullscreen(view); + } else + rc = make_splitscreen(view); + if (rc) + break; + rc = view->input(new, view, KEY_RESIZE); + } break; case '/': - if (view->grep_init) + if (view->search_init) view_search_start(view); else rc = view->input(new, view, ch); break; case 'N': case 'n': - if (view->started_search && view->grep) { + if (view->started_search && view->search_next) { view->searching = (ch == 'n' ? SEARCH_FORWARD : SEARCH_REVERSE); view->search_status = SEARCH_WAITING; - rc = view->grep(view); + rc = view->search_next(view); } else rc = view->input(new, view, ch); break; case KEY_RESIZE: break; case ERR: break; - case CTRL('c'): case 'Q': *done = 1; break; - case CTRL('z'): - raise(SIGTSTP); default: rc = view->input(new, view, ch); break; } - return rc; -} - -static int -cycle_view(struct fnc_view *view) -{ - int rc = FSL_RC_OK; - - if (view->child) { - view->active = false; - view->child->active = true; - view->focus_child = true; - } else if (view->parent) { - view->active = false; - view->parent->active = true; - view->parent->focus_child = false; - if (view->mode == VIEW_SPLIT_HRZN && !screen_is_split(view)) { - if (view->parent->vid == FNC_VIEW_TIMELINE) { - rc = request_tl_commits(view->parent); - if (rc) - return rc; - } - rc = make_fullscreen(view->parent); - } - } - - return rc; -} - -static int -toggle_fullscreen(struct fnc_view **new, struct fnc_view *view) -{ - int rc = FSL_RC_OK; - - if (view_is_parent(view)) { - if (view->child == NULL) - return rc; - if (screen_is_split(view->child)) { - rc = make_fullscreen(view); - if (!rc) - rc = make_fullscreen(view->child); - } else - rc = make_splitscreen(view->child); - if (!rc) - rc = view->child->input(new, view->child, KEY_RESIZE); - } else { - if (screen_is_split(view)) - rc = make_fullscreen(view); - else - rc = make_splitscreen(view); - if (!rc) - rc = view->input(new, view, KEY_RESIZE); - } - - if (!rc && view->vid == FNC_VIEW_TIMELINE) - rc = request_tl_commits(view); - if (!rc) { - if (view->parent) - rc = offset_selected_line(view->parent); - if (!rc) - rc = offset_selected_line(view); - } - return rc; } static int help(struct fnc_view *view) @@ -3012,12 +2782,10 @@ {" H,?,F1 ", " ❬H❭❬?❭❬F1❭ "}, {" k, ", " ❬↑❭❬k❭ "}, {" j, ", " ❬↓❭❬j❭ "}, {" C-b,PgUp ", " ❬C-b❭❬PgUp❭ "}, {" C-f,PgDn ", " ❬C-f❭❬PgDn❭ "}, - {" C-u, ", " ❬C-u❭ "}, - {" C-d, ", " ❬C-d❭ "}, {" gg,Home ", " ❬gg❭❬Home❭ "}, {" G,End ", " ❬G❭❬End❭ "}, {" Tab ", " ❬TAB❭ "}, {" c ", " ❬c❭ "}, {" f ", " ❬f❭ "}, @@ -3035,23 +2803,12 @@ {" F ", " ❬F❭ "}, {" t ", " ❬t❭ "}, {""}, {""}, /* Diff */ {" Space ", " ❬Space❭ "}, - {" # ", " ❬#❭ "}, - {" $ ", " ❬$❭ "}, - {" 0 ", " ❬0❭ "}, - {" C-e ", " ❬C-e❭ "}, - {" C-y ", " ❬C-y❭ "}, - {" C-n ", " ❬C-n❭ "}, - {" C-p ", " ❬C-p❭ "}, - {" l ", " ❬l❭❬→❭ "}, - {" h ", " ❬h❭❬←❭ "}, {" b ", " ❬b❭ "}, - {" F ", " ❬F❭ "}, {" i ", " ❬i❭ "}, - {" L ", " ❬L❭ "}, {" v ", " ❬v❭ "}, {" w ", " ❬w❭ "}, {" -,_ ", " ❬-❭❬_❭ "}, {" +,= ", " ❬+❭❬=❭ "}, {" C-k,K,<,, ", " ❬C-k❭❬K❭❬<❭❬,❭ "}, @@ -3059,33 +2816,25 @@ {""}, {""}, /* Tree */ {" l,Enter, ", " ❬→❭❬l❭❬Enter❭ "}, {" h,, ", " ❬←❭❬h❭❬⌫❭ "}, {" b ", " ❬b❭ "}, - {" d ", " ❬d❭ "}, {" i ", " ❬i❭ "}, {" t ", " ❬t❭ "}, {""}, {""}, /* Blame */ {" Space ", " ❬Space❭ "}, {" Enter ", " ❬Enter❭ "}, - {" # ", " ❬#❭ "}, - {" $ ", " ❬$❭ "}, - {" 0 ", " ❬0❭ "}, - {" l ", " ❬l❭❬→❭ "}, - {" h ", " ❬h❭❬←❭ "}, - {" L ", " ❬L❭ "}, {" b ", " ❬b❭ "}, {" p ", " ❬p❭ "}, {" B ", " ❬B❭ "}, {" T ", " ❬T❭ "}, {""}, {""}, /* Branch */ {" Enter,Space ", " ❬Enter❭❬Space❭ "}, {" d ", " ❬d❭ "}, {" i ", " ❬i❭ "}, - {" s ", " ❬s❭ "}, {" t ", " ❬t❭ "}, {" R, ", " ❬R❭❬C-l❭ "}, {""}, {""}, {0} @@ -3094,14 +2843,12 @@ "", "Global", "Open in-app help", "Move selection cursor or page up one line", "Move selection cursor or page down one line", - "Scroll view up one page", - "Scroll view down one page", - "Scroll view up one half page", - "Scroll view down one half page", + "Scroll up one page", + "Scroll down one page", "Jump to first line or start of the view", "Jump to last line or end of the view", "Switch focus between open views", "Toggle coloured output", "Toggle fullscreen", @@ -3119,23 +2866,12 @@ "Open prompt to enter term with which to filter new timeline view", "Display a tree reflecting the state of the selected commit", "", "Diff", "Scroll down one page of diff output", - "Toggle display of diff view line numbers", - "Scroll the view right to the end of the longest line", - "Scroll the view left to the beginning of the line", - "Scroll the view down in the buffer", - "Scroll the view up in the buffer", - "Navigate to next file in the diff", - "Navigate to previous file in the diff", - "Scroll the view right", - "Scroll the view left", "Open and populate branch view with all repository branches", - "Open prompt to enter file number and navigate to file", "Toggle inversion of diff output", - "Open prompt to enter line number and navigate to line", "Toggle verbosity of diff output", "Toggle ignore whitespace-only changes in diff", "Decrease the number of context lines", "Increase the number of context lines", "Display diff of next (newer) commit in the timeline", @@ -3143,23 +2879,16 @@ "", "Tree", "Move into the selected directory", "Return to the parent directory", "Open and populate branch view with all repository branches", - "Toggle ISO8601 modified timestamp display for each tree entry", "Toggle display of file artifact SHA hash ID", "Display timeline of all commits modifying the selected entry", "", "Blame", "Scroll down one page", "Display the diff of the commit corresponding to the selected line", - "Toggle display of file line numbers", - "Scroll the view right to the end of the longest line", - "Scroll the view left to the beginning of the line", - "Scroll the view right", - "Scroll the view left", - "Open prompt to enter line number and navigate to line", "Blame the version of the file found in the selected line's commit", "Blame the version of the file found in the selected line's parent " "commit", "Reload the previous blamed version of the file", "Open and populate branch view with all repository branches", @@ -3166,11 +2895,10 @@ "", "Branch", "Display the timeline of the currently selected branch", "Toggle display of the date when the branch last received changes", "Toggle display of the SHA hash that identifies the branch", - "Toggle branch sort order (lexicographical -> mru -> state)", "Open a tree view of the currently selected branch", "Reload view with all repository branches and no filters applied", "", " See fnc(1) for complete list of options and key bindings." }; @@ -3262,20 +2990,20 @@ ++cury; break; case KEY_PPAGE: case CTRL('b'): if (cury > 0) { - cury -= wy - 3; + cury -= wy / 2; if (cury < 0) cury = 0; } break; case KEY_NPAGE: case CTRL('f'): case ' ': if (cury < end) { - cury += wy - 3; + cury += wy / 2; if (cury > end) cury = end; } break; case 'g': @@ -3339,26 +3067,41 @@ static int tl_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch) { struct fnc_tl_view_state *s = &view->state.timeline; - int rc = FSL_RC_OK; - uint16_t nscroll = view->nlines - 2; + struct fnc_view *branch_view = NULL, *diff_view = NULL; + struct fnc_view *tree_view = NULL; + int rc = 0, start_col = 0; switch (ch) { case KEY_DOWN: case 'j': case '.': case '>': - rc = move_tl_cursor_down(view, 0); + if (s->first_commit_onscreen == NULL) + break; + if (s->selected_idx < MIN(view->nlines - 2, + s->commits.ncommits - 1)) + ++s->selected_idx; + else if ((rc = timeline_scroll_down(view, 1))) + break; + select_commit(s); break; - case CTRL('d'): - nscroll >>= 1; - /* FALL THROUGH */ case KEY_NPAGE: case CTRL('f'): { - rc = move_tl_cursor_down(view, nscroll); + struct commit_entry *first; + if ((first = s->first_commit_onscreen) == NULL) + break; + if ((rc = timeline_scroll_down(view, view->nlines - 1))) + break; + if (first == s->first_commit_onscreen && s->selected_idx < + MIN(view->nlines - 2, s->commits.ncommits - 1)) + /* At bottom of timeline. */ + s->selected_idx = MIN(view->nlines - 2, + s->commits.ncommits - 1); + select_commit(s); break; } case KEY_END: case 'G': view->search_status = SEARCH_FOR_END; @@ -3366,75 +3109,189 @@ break; case 'k': case KEY_UP: case '<': case ',': - move_tl_cursor_up(view, false, false); + if (s->first_commit_onscreen == NULL) + break; + if (s->selected_idx > 0) + --s->selected_idx; + else + timeline_scroll_up(s, 1); + select_commit(s); break; - case CTRL('u'): - nscroll >>= 1; - /* FALL THROUGH */ case KEY_PPAGE: case CTRL('b'): - move_tl_cursor_up(view, nscroll, false); + if (s->first_commit_onscreen == NULL) + break; + if (TAILQ_FIRST(&s->commits.head) == s->first_commit_onscreen) + s->selected_idx = 0; + else + timeline_scroll_up(s, view->nlines - 1); + select_commit(s); break; case 'g': if (!fnc_home(view)) break; /* FALL THROUGH */ case KEY_HOME: - move_tl_cursor_up(view, false, true); + if (s->first_commit_onscreen == NULL) + break; + s->selected_idx = 0; + timeline_scroll_up(s, s->commits.ncommits); + select_commit(s); break; case KEY_RESIZE: if (s->selected_idx > view->nlines - 2) s->selected_idx = view->nlines - 2; if (s->selected_idx > s->commits.ncommits - 1) s->selected_idx = s->commits.ncommits - 1; select_commit(s); if (s->commits.ncommits < view->nlines - 1 && - !s->thread_cx.eotl) { + !s->thread_cx.timeline_end) { s->thread_cx.ncommits_needed += (view->nlines - 1) - s->commits.ncommits; rc = signal_tl_thread(view, 1); } break; case KEY_ENTER: case ' ': case '\r': - rc = request_view(new_view, view, FNC_VIEW_DIFF); + if (s->selected_commit == NULL) + break; + if (view_is_parent(view)) + start_col = view_split_start_col(view->start_col); + if ((rc = init_diff_commit(&diff_view, start_col, + s->selected_commit->commit, view))) + break; + view->active = false; + diff_view->active = true; + if (view_is_parent(view)) { + if (view->child != NULL) { + rc = view_close(view->child); + view->child = NULL; + } + if (rc) + return rc; + view->child = diff_view; + diff_view->parent = view; + view->focus_child = true; + } else + *new_view = diff_view; break; case 'b': - rc = request_view(new_view, view, FNC_VIEW_BRANCH); + if (view_is_parent(view)) + start_col = view_split_start_col(view->start_col); + branch_view = view_open(view->nlines, view->ncols, + view->start_ln, start_col, FNC_VIEW_BRANCH); + if (branch_view == NULL) + return RC(FSL_RC_ERROR, "%s", "view_open"); + rc = open_branch_view(branch_view, BRANCH_LS_OPEN_CLOSED, NULL, + 0, 0); + if (rc) { + view_close(branch_view); + return rc; + } + s->thread_cx.needs_reset = true; + view->active = false; + branch_view->active = true; + if (view_is_parent(view)) { + rc = view_close_child(view); + if (rc) + return rc; + view_set_child(view, branch_view); + view->focus_child = true; + } else + *new_view = branch_view; break; case 'c': s->colour = !s->colour; break; case 'F': { - struct input input = {NULL, "filter: ", INPUT_ALPHA, true}; - rc = fnc_prompt_input(view, &input); - if (rc) + struct fnc_view *new; + char glob[BUFSIZ]; + int retval; + mvwaddstr(view->window, view->start_ln + view->nlines - 1, 0, + "/"); + wclrtoeol(view->window); + nocbreak(); + echo(); + retval = wgetnstr(view->window, glob, sizeof(glob)); + cbreak(); + noecho(); + if (retval == ERR) return rc; - s->glob = input.buf; - rc = request_view(new_view, view, FNC_VIEW_TIMELINE); - if (rc == FSL_RC_BREAK) { - fnc_print_msg(view, "-- no matching commits --", - true, true, true); + if (view_is_parent(view)) + start_col = view_split_start_col(view->start_col); + new = view_open(view->nlines, view->ncols, view->start_ln, + start_col, FNC_VIEW_TIMELINE); + if (new == NULL) + return RC(FSL_RC_ERROR, "%s", "view_open"); + rc = open_timeline_view(new, 0, "/", glob); + if (rc) { + if (rc != FSL_RC_BREAK) + return rc; + wattr_on(view->window, A_BOLD, NULL); + mvwaddstr(view->window, + view->start_ln + view->nlines - 1, 0, + "-- no matching commits --"); + wclrtoeol(view->window); + wattr_off(view->window, A_BOLD, NULL); fcli_err_reset(); - rc = FSL_RC_OK; + rc = 0; + update_panels(); + doupdate(); + sleep(1); + break; } + view->active = false; + new->active = true; + if (view_is_parent(view)) { + rc = view_close_child(view); + if (rc) + return rc; + view_set_child(view, new); + view->focus_child = true; + } else + *new_view = new; break; } case 't': if (s->selected_commit == NULL) break; if (!fsl_rid_is_a_checkin(fcli_cx(), - s->selected_commit->commit->rid)) - fnc_print_msg(view, - "-- tree requires check-in artifact --", true, - true, true); - else - rc = request_view(new_view, view, FNC_VIEW_TREE); + s->selected_commit->commit->rid)) { + wattr_on(view->window, A_BOLD, NULL); + mvwaddstr(view->window, + view->start_ln + view->nlines - 1, 0, + "-- tree requires check-in artifact --"); + wclrtoeol(view->window); + wattr_off(view->window, A_BOLD, NULL); + fcli_err_reset(); + rc = 0; + update_panels(); + doupdate(); + sleep(1); + break; + } + if (view_is_parent(view)) + start_col = view_split_start_col(view->start_col); + rc = browse_commit_tree(&tree_view, start_col, + s->selected_commit, s->path); + if (rc) + break; + s->thread_cx.needs_reset = true; + view->active = false; + tree_view->active = true; + if (view_is_parent(view)) { + rc = view_close_child(view); + if (rc) + return rc; + view_set_child(view, tree_view); + view->focus_child = true; + } else + *new_view = tree_view; break; case 'q': s->quit = 1; break; default: @@ -3442,303 +3299,43 @@ } return rc; } -static int -move_tl_cursor_down(struct fnc_view *view, uint16_t page) -{ - struct fnc_tl_view_state *s = &view->state.timeline; - struct commit_entry *first; - int rc = FSL_RC_OK; - - first = s->first_commit_onscreen; - if (first == NULL) - return rc; - - if (s->thread_cx.eotl && - s->selected_commit->idx >= s->commits.ncommits - 1) - return rc; /* Last commit already selected. */ - - if (!page) { - /* Still more commits on this page to scroll down. */ - if (s->selected_idx < MIN(view->nlines - 2, - s->commits.ncommits - 1)) - ++s->selected_idx; - else /* Last commit on screen is selected, need to scroll. */ - rc = timeline_scroll_down(view, 1); - } else if (s->thread_cx.eotl) { - /* Last displayed commit is the end, jump to it. */ - if (s->last_commit_onscreen->idx == s->commits.ncommits - 1) - s->selected_idx += MIN(s->last_commit_onscreen->idx - - s->selected_commit->idx, page + 1); - else /* Scroll the page. */ - rc = timeline_scroll_down(view, MIN(page, - s->commits.ncommits - s->selected_commit->idx - 1)); - } else { - rc = timeline_scroll_down(view, page); - if (rc) - return rc; - if (first == s->first_commit_onscreen && s->selected_idx < - MIN(view->nlines - 2, s->commits.ncommits - 1)) { - /* End of timeline, no more commits; move cursor down */ - s->selected_idx = MIN(s->commits.ncommits - 1, page); - } - /* - * If we've overshot (necessarily possible with horizontal - * splits), select the final commit. - */ - s->selected_idx = MIN(s->selected_idx, - s->last_commit_onscreen->idx - - s->first_commit_onscreen->idx); - } - - if (!rc) - select_commit(s); - return rc; -} - -static void -move_tl_cursor_up(struct fnc_view *view, uint16_t page, bool home) -{ - struct fnc_tl_view_state *s = &view->state.timeline; - - if (s->first_commit_onscreen == NULL) - return; - - if ((page && TAILQ_FIRST(&s->commits.head) == s->first_commit_onscreen) - || home) - s->selected_idx = home ? 0 : MAX(0, s->selected_idx - page - 1); - - if (!page && !home && s->selected_idx > 0) - --s->selected_idx; - else - timeline_scroll_up(s, home ? - s->commits.ncommits : MAX(page, 1)); - - select_commit(s); - return; -} - -static int -request_view(struct fnc_view **new_view, struct fnc_view *view, - enum fnc_view_id request) -{ - struct fnc_view *requested = NULL; - enum view_mode split = VIEW_SPLIT_NONE; - int x = 0, y = 0, rc = FSL_RC_OK; - - /* - * Need to report to this view if request fails, so get dimensions - * for new view initialisation but don't split yet. - */ - if (view_is_parent(view)) - split = view_get_split(view, &x, &y); - - rc = init_view(&requested, view, request, x, y); - if (rc || !requested) - return rc; - - if (split == VIEW_SPLIT_HRZN) { /* Request success, safe to split. */ - rc = split_view(view, &y); - if (rc) - return rc; - } - - view->active = false; - requested->active = true; - requested->mode = view->mode; - requested->nlines = view->lines - y; - - if (view_is_parent(view)) { - rc = view_close_child(view); - if (rc) - return rc; - view_set_child(view, requested); - view->focus_child = true; - } else - *new_view = requested; - - return rc; -} - -static int -init_view(struct fnc_view **new_view, struct fnc_view *view, - enum fnc_view_id request, int x, int y) -{ - int rc = FSL_RC_OK; - - switch (request) { - case FNC_VIEW_DIFF: { - struct fnc_tl_view_state *s = &view->state.timeline; - if (s->selected_commit == NULL) - break; - rc = init_diff_view(new_view, x, y, s->selected_commit->commit, - view); - break; - } - case FNC_VIEW_BLAME: { - struct fnc_tree_view_state *s = &view->state.tree; - rc = blame_tree_entry(new_view, x, y, s->selected_entry, - &s->parents, s->commit_id); - break; - } - case FNC_VIEW_TIMELINE: { - const char *glob = NULL; - int rid = 0; - if (view->vid == FNC_VIEW_TIMELINE) - glob = view->state.timeline.glob; - else if (view->vid == FNC_VIEW_BRANCH) - rid = fsl_uuid_to_rid(fcli_cx(), - view->state.branch.selected_branch->branch->id); - rc = init_timeline_view(new_view, x, y, rid, "/", glob); - break; - } - case FNC_VIEW_TREE: { - struct fnc_tl_view_state *s = &view->state.timeline; - rc = browse_commit_tree(new_view, x, y, s->selected_commit, - s->path); - break; - } - case FNC_VIEW_BRANCH: { - *new_view = view_open(0, 0, y, x, FNC_VIEW_BRANCH); - if (*new_view == NULL) - return RC(FSL_RC_ERROR, "%s", "view_open"); - rc = open_branch_view(*new_view, BRANCH_LS_OPEN_CLOSED, NULL, - 0, 0); - /* FALL THROUGH */ - } - default: - break; - } - - return rc; -} - -/* - * Get dimensions for splitscreen view. If FNC_VIEW_SPLIT_MODE is either unset - * or set to auto, determine vertical or horizontal split depending on screen - * estate. If set to 'v' or 'h', assign start column or start line of the split - * view to *start_col and *start_ln, respectively, and return split mode. - */ -static enum view_mode -view_get_split(struct fnc_view *view, int *start_col, int *start_ln) -{ - char *mode = fnc_conf_getopt(FNC_VIEW_SPLIT_MODE, false); - - if (!mode || mode[0] != 'h') - *start_col = view_split_start_col(view->start_col); - - if (!*start_col && (!mode || mode[0] != 'v')) - *start_ln = view_split_start_ln(view->lines); - - return *start_col ? VIEW_SPLIT_VERT : VIEW_SPLIT_HRZN; -} - -/* Split view horizontally at *start_ln and offset view->state->selected line */ -static int -split_view(struct fnc_view *view, int *start_ln) -{ - int rc = FSL_RC_OK; - - view->mode = VIEW_SPLIT_HRZN; - view->nlines = *start_ln; - rc = view_resize(view, VIEW_SPLIT_NONE); - if (!rc) { - view->nlines = *start_ln - 1; - rc = offset_selected_line(view); - } - - return rc; -} - -/* - * If view->state->selected line is outside the now split view, scroll offset - * lines to move selected line into view and index its new position. - */ -static int -offset_selected_line(struct fnc_view *view) -{ - int (*scrolld)(struct fnc_view *, int); - int header, offset, rc = FSL_RC_OK; - int *selected; - - switch (view->vid) { - case FNC_VIEW_TIMELINE: { - struct fnc_tl_view_state *s = &view->state.timeline; - scrolld = &timeline_scroll_down; - header = 2; - selected = &s->selected_idx; - break; - } - case FNC_VIEW_TREE: { - struct fnc_tree_view_state *s = &view->state.tree; - scrolld = &tree_scroll_down; - header = 4; - selected = &s->selected_idx; - break; - } - case FNC_VIEW_BRANCH: { - struct fnc_branch_view_state *s = &view->state.branch; - scrolld = &branch_scroll_down; - header = 1; - selected = &s->selected; - break; - } - default: - selected = NULL; - scrolld = NULL; - header = 0; - break; - } - - - if (selected && *selected > view->nlines - header) { - offset = ABS(view->nlines - *selected - header); - rc = scrolld ? scrolld(view, offset) : rc; - view->pos.line = *selected; - *selected -= offset; - view->pos.offset = offset; - } - - return rc; -} - static int timeline_scroll_down(struct fnc_view *view, int maxscroll) { struct fnc_tl_view_state *s = &view->state.timeline; struct commit_entry *pentry; int rc = 0, nscrolled = 0, ncommits_needed; - if (s->last_commit_onscreen == NULL || !maxscroll) - return rc; + if (s->last_commit_onscreen == NULL) + return 0; ncommits_needed = s->last_commit_onscreen->idx + 1 + maxscroll; - if (s->commits.ncommits < ncommits_needed && !s->thread_cx.eotl) { + if (s->commits.ncommits < ncommits_needed && + !s->thread_cx.timeline_end) { /* Signal timeline thread for n commits needed. */ s->thread_cx.ncommits_needed += maxscroll; rc = signal_tl_thread(view, 1); if (rc) return rc; } do { pentry = TAILQ_NEXT(s->last_commit_onscreen, entries); - if (pentry == NULL && view->mode != VIEW_SPLIT_HRZN) + if (pentry == NULL) break; - s->last_commit_onscreen = pentry ? - pentry : s->last_commit_onscreen; + s->last_commit_onscreen = pentry; pentry = TAILQ_NEXT(s->first_commit_onscreen, entries); if (pentry == NULL) break; s->first_commit_onscreen = pentry; } while (++nscrolled < maxscroll); - s->nscrolled += view->mode == VIEW_SPLIT_HRZN ? nscrolled : 0; return rc; } static void timeline_scroll_up(struct fnc_tl_view_state *s, int maxscroll) @@ -3778,106 +3375,66 @@ } static int make_splitscreen(struct fnc_view *view) { - int rc = FSL_RC_OK; + int rc = 0; - view->start_ln = view->mode == VIEW_SPLIT_HRZN ? - view_split_start_ln(view->nlines) : 0; - view->start_col = view->mode != VIEW_SPLIT_HRZN ? - view_split_start_col(0) : 0; - view->nlines = LINES - view->start_ln; + view->start_ln = 0; + view->start_col = view_split_start_col(0); + view->nlines = LINES; view->ncols = COLS - view->start_col; view->lines = LINES; view->cols = COLS; - - rc = view_resize(view, view->mode); - if (rc) + if ((rc = view_resize(view))) return rc; - if (view->parent && view->mode == VIEW_SPLIT_HRZN) - view->parent->nlines = view->lines - view->nlines - 1; - if (mvwin(view->window, view->start_ln, view->start_col) == ERR) return RC(FSL_RC_ERROR, "%s", "mvwin"); return rc; } static int make_fullscreen(struct fnc_view *view) { - int rc = FSL_RC_OK; + int rc = 0; view->start_col = 0; view->start_ln = 0; view->nlines = LINES; view->ncols = COLS; view->lines = LINES; view->cols = COLS; - - rc = view_resize(view, VIEW_SPLIT_NONE); - if (rc) + if ((rc = view_resize(view))) return rc; if (mvwin(view->window, view->start_ln, view->start_col) == ERR) return RC(FSL_RC_ERROR, "%s", "mvwin"); return rc; } /* - * Find start column for vertical split. If terminal width is < 120 columns, - * return 0 (i.e., do not split; open new view in the existing one). If >= 120, - * return the largest of 80 columns or 50% of the current view width subtracted - * from COLS so that the child view will be no smaller than 80 columns wide. + * Only open a new view in a splitscreen if the console is >= 120 columns wide. + * Otherwise, open in the current view. If splitting the screen, make the new + * panel the largest of 80 columns or half the current column width. */ static int view_split_start_col(int start_col) { if (start_col > 0 || COLS < 120) return 0; return (COLS - MAX(COLS / 2, 80)); } -/* - * Find start line for horizontal split. If FNC_VIEW_SPLIT_HEIGHT is set as - * either an absolute line value or % equalling less than lines - 2, subtract - * from lines and return. If invalid or not set, return HSPLIT_SCALE(lines). - */ -static int -view_split_start_ln(int lines) -{ - char *height = NULL; - long n = 0; - int rc = FSL_RC_OK; - - height = fnc_conf_getopt(FNC_VIEW_SPLIT_HEIGHT, false); - - if (height && height[fsl_strlen(height) - 1] == '%') { - n = strtol(height, NULL, 10); - if (n > INT_MAX || (errno == ERANGE && n == LONG_MAX)) - rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE), - "%s", "strtol"); - if (n < INT_MIN || (errno == ERANGE && n == LONG_MIN)) - rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE), - "%s", "strtol"); - if (!rc) - n = lines * ((float)n / 100); - } else if (height) - rc = strtonumcheck(&n, height, 0, lines); - - fsl_free(height); - return !rc && n && n < (lines - 2) ? lines - n : lines * HSPLIT_SCALE; -} - static int view_search_start(struct fnc_view *view) { - struct input input = {NULL, "/", INPUT_ALPHA, true}; - int rc = FSL_RC_OK; + char pattern[BUFSIZ]; + int retval; + int rc = 0; if (view->started_search) { regfree(&view->regex); view->searching = SEARCH_DONE; memset(&view->regmatch, 0, sizeof(view->regmatch)); @@ -3886,42 +3443,53 @@ if (view->nlines < 1) return rc; if (view->search_status == SEARCH_FOR_END) { - view->grep_init(view); + view->search_init(view); view->started_search = true; view->searching = SEARCH_FORWARD; view->search_status = SEARCH_WAITING; view->state.timeline.thread_cx.endjmp = true; - rc = view->grep(view); + rc = view->search_next(view); return rc; } - rc = fnc_prompt_input(view, &input); - if (rc) + mvwaddstr(view->window, view->start_ln + view->nlines - 1, 0, "/"); + wclrtoeol(view->window); + + nocbreak(); + echo(); + retval = wgetnstr(view->window, pattern, sizeof(pattern)); + cbreak(); + noecho(); + if (retval == ERR) return rc; - if (regcomp(&view->regex, input.buf, REG_EXTENDED | REG_NEWLINE) == 0) { - view->grep_init(view); + if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) { + if ((rc = view->search_init(view))) { + regfree(&view->regex); + return rc; + } view->started_search = true; view->searching = SEARCH_FORWARD; view->search_status = SEARCH_WAITING; - rc = view->grep(view); + rc = view->search_next(view); } return rc; } -static void -tl_grep_init(struct fnc_view *view) +static int +tl_search_init(struct fnc_view *view) { - struct fnc_tl_view_state *s = &view->state.timeline; + struct fnc_tl_view_state *s = &view->state.timeline; s->matched_commit = NULL; s->search_commit = NULL; + return 0; } static int tl_search_next(struct fnc_view *view) { @@ -3968,19 +3536,19 @@ entry = TAILQ_LAST(&s->commits.head, commit_tailhead); } while (1) { if (entry == NULL) { - if (s->thread_cx.eotl && s->thread_cx.endjmp) { + if (s->thread_cx.timeline_end && s->thread_cx.endjmp) { s->matched_commit = TAILQ_LAST(&s->commits.head, commit_tailhead); view->search_status = SEARCH_COMPLETE; s->thread_cx.endjmp = false; break; } - if (s->thread_cx.eotl || - view->searching == SEARCH_REVERSE) { + if (s->thread_cx.timeline_end || view->searching == + SEARCH_REVERSE) { view->search_status = (s->matched_commit == NULL ? SEARCH_NO_MATCH : SEARCH_COMPLETE); s->search_commit = NULL; cbreak(); return rc; @@ -4044,11 +3612,11 @@ } static int view_close(struct fnc_view *view) { - int rc = FSL_RC_OK; + int rc = 0; if (view->child) { view_close(view->child); view->child = NULL; } @@ -4056,11 +3624,11 @@ rc = view->close(view); if (view->panel) del_panel(view->panel); if (view->window) delwin(view->window); - fsl_free(view); + free(view); return rc; } static int @@ -4177,21 +3745,21 @@ return 0; } static int -init_diff_view(struct fnc_view **new_view, int start_col, int start_ln, +init_diff_commit(struct fnc_view **new_view, int start_col, struct fnc_commit_artifact *commit, struct fnc_view *timeline_view) { - struct fnc_view *diff_view; - int rc = 0; + struct fnc_view *diff_view; + int rc = 0; - diff_view = view_open(0, 0, start_ln, start_col, FNC_VIEW_DIFF); + diff_view = view_open(0, 0, 0, start_col, FNC_VIEW_DIFF); if (diff_view == NULL) return RC(FSL_RC_ERROR, "%s", "view_open"); - rc = open_diff_view(diff_view, commit, DEF_DIFF_CTX, fnc_init.ws, + rc = open_diff_view(diff_view, commit, DIFF_DEF_CTXT, fnc_init.ws, fnc_init.invert, !fnc_init.quiet, timeline_view, true, NULL); if (!rc) *new_view = diff_view; return rc; @@ -4202,32 +3770,23 @@ int context, bool ignore_ws, bool invert, bool verbosity, struct fnc_view *timeline_view, bool showmeta, struct fnc_pathlist_head *paths) { struct fnc_diff_view_state *s = &view->state.diff; - char *opt; int rc = 0; - opt = fnc_conf_getopt(FNC_COLOUR_HL_LINE, false); - if (!fsl_stricmp(opt, "mono")) - s->sline = SLINE_MONO; - fsl_free(opt); - - s->index.n = 0; - s->index.idx = 0; - s->maxx = 0; s->paths = paths; s->selected_commit = commit; s->first_line_onscreen = 1; s->last_line_onscreen = view->nlines; - s->selected_line = 1; + s->current_line = 1; s->f = NULL; s->context = context; s->sbs = 0; - verbosity ? FLAG_SET(s->diff_flags, FSL_DIFF_VERBOSE) : 0; - ignore_ws ? FLAG_SET(s->diff_flags, FSL_DIFF2_IGNORE_ALLWS) : 0; - invert ? FLAG_SET(s->diff_flags, FSL_DIFF2_INVERT) : 0; + verbosity ? s->diff_flags |= FSL_DIFF_VERBOSE : 0; + ignore_ws ? s->diff_flags |= FSL_DIFF_IGNORE_ALLWS : 0; + invert ? s->diff_flags |= FSL_DIFF_INVERT : 0; s->timeline_view = timeline_view; s->colour = !fnc_init.nocolour && has_colors(); s->showmeta = showmeta; if (s->colour) { @@ -4252,31 +3811,35 @@ } view->show = show_diff; view->input = diff_input_handler; view->close = close_diff_view; - view->grep_init = diff_grep_init; - view->grep = find_next_match; + view->search_init = diff_search_init; + view->search_next = diff_search_next; return rc; } static void show_diff_status(struct fnc_view *view) { mvwaddstr(view->window, 0, 0, "generating diff..."); - updatescreen(view->window, true, true); +#ifdef __linux__ + wnoutrefresh(view->window); +#else + update_panels(); +#endif + doupdate(); } static int create_diff(struct fnc_diff_view_state *s) { FILE *fout = NULL; char *line, *st0 = NULL, *st = NULL; off_t lnoff = 0; - uint32_t idx = 0; - int rc = 0; + int n, rc = 0; free(s->line_offsets); s->line_offsets = fsl_malloc(sizeof(off_t)); if (s->line_offsets == NULL) return RC(FSL_RC_ERROR, "%s", "fsl_malloc"); @@ -4298,12 +3861,14 @@ * it's a different process to diff the others (wiki, technote, etc.). */ if (s->selected_commit->diff_type == FNC_DIFF_COMMIT) rc = create_changeset(s->selected_commit); else if (s->selected_commit->diff_type == FNC_DIFF_BLOB) - rc = diff_file_artifact(s, s->selected_commit->prid, NULL, - NULL, FSL_CKOUT_CHANGE_MOD); + rc = diff_file_artifact(&s->buf, s->selected_commit->prid, NULL, + s->selected_commit->rid, NULL, FSL_CKOUT_CHANGE_MOD, + s->diff_flags, s->context, s->sbs, + s->selected_commit->diff_type); else if (s->selected_commit->diff_type == FNC_DIFF_WIKI) rc = diff_non_checkin(&s->buf, s->selected_commit, s->diff_flags, s->context, s->sbs); if (rc) goto end; @@ -4311,20 +3876,18 @@ /* * Delay assigning diff headline labels (i.e., diff id1 id2) till now * because wiki parent commits are obtained in diff_non_checkin(). */ if (s->selected_commit->puuid) { - fsl_free(s->id1); s->id1 = fsl_strdup(s->selected_commit->puuid); if (s->id1 == NULL) { rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup"); goto end; } } else s->id1 = NULL; /* Initial commit, tag, technote, etc. */ if (s->selected_commit->uuid) { - fsl_free(s->id2); s->id2 = fsl_strdup(s->selected_commit->uuid); if (s->id2 == NULL) { rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup"); goto end; } @@ -4342,38 +3905,39 @@ * Diff local changes on disk in the current checkout differently to * checked-in versions: the former compares on disk file content with * file artifacts; the latter compares file artifact blobs only. */ if (s->selected_commit->diff_type == FNC_DIFF_COMMIT) - diff_commit(s); + diff_commit(&s->buf, s->selected_commit, s->diff_flags, + s->context, s->sbs, s->paths); else if (s->selected_commit->diff_type == FNC_DIFF_CKOUT) - diff_checkout(s); + diff_checkout(&s->buf, s->selected_commit->prid, s->diff_flags, + s->context, s->sbs, s->paths); /* * Parse the diff buffer line-by-line to record byte offsets of each * line for scrolling and searching in diff view. */ st0 = fsl_strdup(fsl_buffer_str(&s->buf)); st = st0; lnoff = (s->line_offsets)[s->nlines - 1]; - s->index.lineno = fsl_malloc(s->index.n * sizeof(size_t)); while ((line = fnc_strsep(&st, "\n")) != NULL) { - int lineno, n = fprintf(s->f, "%s\n", line); - s->maxx = MAX((int)s->maxx, n); - if (s->index.offset && idx < s->index.n && - lnoff == s->index.offset[idx]) { - lineno = s->nlines + (idx ? 1 : 0); - s->index.lineno[idx++] = lineno; - } + n = fprintf(s->f, "%s\n", line); lnoff += n; rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff); if (rc) goto end; } - --s->nlines; /* Don't count EOF '\n' */ + + fputc('\n', s->f); + ++lnoff; + rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff); + if (rc) + goto end; + end: - fsl_free(st0); + free(st0); fsl_buffer_clear(&s->buf); if (s->f && fflush(s->f) != 0 && rc == 0) rc = RC(FSL_RC_IO, "%s", "fflush"); return rc; } @@ -4489,11 +4053,11 @@ goto end; } while ((line = fnc_strsep(&st, "\n")) != NULL) { linelen = fsl_strlen(line); if (linelen >= s->ncols) { - rc = wrapline(line, s->ncols - LINENO_WIDTH, s, &lnoff); + rc = wrapline(line, s->ncols, s, &lnoff); if (rc) goto end; } else { if ((n = fprintf(s->f, "%s\n", line)) < 0) @@ -4509,13 +4073,10 @@ fputc('\n', s->f); ++lnoff; if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff))) goto end; - if (s->selected_commit->diff_type == FNC_DIFF_WIKI) - goto end; /* No changeset for wiki commits. */ - for (idx = 0; idx < s->selected_commit->changeset.used; ++idx) { char *changeline; struct fsl_file_artifact *file_change; file_change = s->selected_commit->changeset.list[idx]; @@ -4544,17 +4105,10 @@ lnoff += n; if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff))) goto end; } - /* Add blank line between end of changeset and diff. */ - fputc('\n', s->f); - ++lnoff; - rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff); - s->index.offset = fsl_realloc(s->index.offset, - (s->index.n + 1) * sizeof(size_t)); - s->index.offset[s->index.n++] = lnoff; end: free(st0); free(line); if (rc) { free(*&s->line_offsets); @@ -4631,22 +4185,22 @@ * set, otherwise only diff metatadata will be output. In case (3), if the * hash (UUID) of each F card is the same, there are no changes; if different, * both artifacts will be passed to diff_file_artifact() to be diffed. */ static int -diff_commit(struct fnc_diff_view_state *s) +diff_commit(fsl_buffer *buf, struct fnc_commit_artifact *commit, int diff_flags, + int context, int sbs, struct fnc_pathlist_head *paths) { fsl_cx *const f = fcli_cx(); const fsl_card_F *fc1 = NULL; const fsl_card_F *fc2 = NULL; fsl_deck d1 = fsl_deck_empty; fsl_deck d2 = fsl_deck_empty; fsl_id_t id1; int different = 0, rc = 0; - rc = fsl_deck_load_rid(f, &d2, s->selected_commit->rid, - FSL_SATYPE_CHECKIN); + rc = fsl_deck_load_rid(f, &d2, commit->rid, FSL_SATYPE_CHECKIN); if (rc) goto end; rc = fsl_deck_F_rewind(&d2); if (rc) goto end; @@ -4654,13 +4208,12 @@ /* * For the one-and-only special case of repositories, such as the * canonical fnc, that do not have an "initial empty check-in", we * proceed with no parent version to diff against. */ - if (s->selected_commit->puuid) { - rc = fsl_sym_to_rid(f, s->selected_commit->puuid, - FSL_SATYPE_CHECKIN, &id1); + if (commit->puuid) { + rc = fsl_sym_to_rid(f, commit->puuid, FSL_SATYPE_CHECKIN, &id1); if (rc) goto end; rc = fsl_deck_load_rid(f, &d1, id1, FSL_SATYPE_CHECKIN); if (rc) goto end; @@ -4674,14 +4227,14 @@ while (fc1 || fc2) { const fsl_card_F *a = NULL, *b = NULL; fsl_ckout_change_e change = FSL_CKOUT_CHANGE_NONE; bool diff = true; - if (s->paths != NULL && !TAILQ_EMPTY(s->paths)) { + if (paths != NULL && !TAILQ_EMPTY(paths)) { struct fnc_pathlist_entry *pe; diff = false; - TAILQ_FOREACH(pe, s->paths, entry) + TAILQ_FOREACH(pe, paths, entry) if (!fsl_strcmp(pe->path, fc1->name) || !fsl_strcmp(pe->path, fc2->name) || !fsl_strncmp(pe->path, fc1->name, pe->pathlen) || !fsl_strncmp(pe->path, fc2->name, pe->pathlen)) { @@ -4706,29 +4259,32 @@ a = fc1; change = FSL_CKOUT_CHANGE_REMOVED; fsl_deck_F_next(&d1, &fc1); } if (diff) - rc = diff_file_artifact(s, id1, a, b, change); + rc = diff_file_artifact(buf, id1, a, + commit->rid, b, change, diff_flags, + context, sbs, commit->diff_type); } else if (!fsl_uuidcmp(fc1->uuid, fc2->uuid)) { /* No change */ fsl_deck_F_next(&d1, &fc1); fsl_deck_F_next(&d2, &fc2); } else { change = FSL_CKOUT_CHANGE_MOD; if (diff) - rc = diff_file_artifact(s, id1, fc1, fc2, - change); + rc = diff_file_artifact(buf, id1, fc1, + commit->rid, fc2, change, diff_flags, + context, sbs, commit->diff_type); fsl_deck_F_next(&d1, &fc1); fsl_deck_F_next(&d2, &fc2); } if (rc == FSL_RC_RANGE) { - fsl_buffer_append(&s->buf, + fsl_buffer_append(buf, "\nDiff has too many changes\n", -1); rc = 0; fsl_cx_err_reset(f); } else if (rc == FSL_RC_DIFF_BINARY) { - fsl_buffer_append(&s->buf, + fsl_buffer_append(buf, "\nBinary files cannot be diffed\n", -1); rc = 0; fsl_cx_err_reset(f); } else if (rc) goto end; @@ -4747,22 +4303,22 @@ * diff_flags, context, and sbs are the same parameters as diff_file_artifact() * nb. This routine is only called with 'fnc diff [hash]'; that is, one or * zero args—not two—supplied to fnc's diff command line interface. */ static int -diff_checkout(struct fnc_diff_view_state *s) +diff_checkout(fsl_buffer *buf, fsl_id_t vid, int diff_flags, int context, + int sbs, struct fnc_pathlist_head *paths) { fsl_cx *const f = fcli_cx(); fsl_stmt *st = NULL; fsl_buffer sql, abspath, bminus; fsl_uuid_str xminus = NULL; - fsl_id_t cid, vid; + fsl_id_t cid; int rc = 0; bool allow_symlinks; abspath = bminus = sql = fsl_buffer_empty; - vid = s->selected_commit->prid; fsl_ckout_version_info(f, &cid, NULL); /* cid = fsl_config_get_id(f, FSL_CONFDB_CKOUT, 0, "checkout"); */ /* XXX Already done in cmd_diff(): Load vfile table with local state. */ /* rc = fsl_vfile_changes_scan(f, cid, */ /* FSL_VFILE_CKSIG_ENOTFILE & FSL_VFILE_CKSIG_KEEP_OTHERS); */ @@ -4883,14 +4439,14 @@ xminus = fsl_strdup(NULL_DEVICE); allow_symlinks = fsl_config_get_bool(f, FSL_CONFDB_REPO, false, "allow-symlinks"); if (!symlink != !(fsl_is_symlink(fsl_buffer_cstr(&abspath)) && allow_symlinks)) { - rc = write_diff_meta(&s->buf, path, xminus, path, - NULL_DEVICE, s->diff_flags, change); - fsl_buffer_append(&s->buf, - "\nSymbolic links cannot be diffed\n", -1); + rc = write_diff_meta(buf, path, xminus, path, + NULL_DEVICE, diff_flags, change); + fsl_buffer_append(buf, "\nSymbolic links and regular " + "files cannot be diffed\n", -1); if (rc) goto yield; continue; } if (fid > 0 && change != FSL_CKOUT_CHANGE_ADDED) { @@ -4897,34 +4453,35 @@ rc = fsl_content_get(f, fid, &bminus); if (rc) goto yield; } else fsl_buffer_clear(&bminus); - if (s->paths != NULL && !TAILQ_EMPTY(s->paths)) { + if (paths != NULL && !TAILQ_EMPTY(paths)) { struct fnc_pathlist_entry *pe; diff = false; - TAILQ_FOREACH(pe, s->paths, entry) + TAILQ_FOREACH(pe, paths, entry) if (!fsl_strncmp(pe->path, path, pe->pathlen) || !fsl_strcmp(pe->path, path)) { diff = true; break; } } if (diff) - rc = diff_file(s, &bminus, path, xminus, - fsl_buffer_cstr(&abspath), change); + rc = diff_file(buf, &bminus, path, xminus, + fsl_buffer_cstr(&abspath), change, diff_flags, + context, sbs); fsl_buffer_reuse(&bminus); fsl_buffer_reuse(&abspath); fsl_free(xminus); xminus = NULL; if (rc == FSL_RC_RANGE) { - fsl_buffer_append(&s->buf, + fsl_buffer_append(buf, "\nDiff has too many changes\n", -1); rc = 0; fsl_cx_err_reset(f); } else if (rc == FSL_RC_DIFF_BINARY) { - fsl_buffer_append(&s->buf, + fsl_buffer_append(buf, "\nBinary files cannot be diffed\n", -1); rc = 0; fsl_cx_err_reset(f); } else if (rc) goto yield; @@ -4987,27 +4544,26 @@ minus = xminus; plus = xplus; break; } - if FLAG_CHK(diff_flags, FSL_DIFF2_INVERT) { + if (diff_flags & FSL_DIFF_INVERT) { const char *tmp = minus; minus = plus; plus = tmp; tmp = zminus; zminus = zplus; zplus = tmp; } - if (!FLAG_CHK(diff_flags, (FSL_DIFF_SIDEBYSIDE | FSL_DIFF_BRIEF))) { - rc = fsl_buffer_appendf(buf, "%sIndex: %s\n%.71c\n", - buf->used ? "\n" : "", index, '='); + if ((diff_flags & (FSL_DIFF_SIDEBYSIDE | FSL_DIFF_BRIEF)) == 0) { + rc = fsl_buffer_appendf(buf, "\nIndex: %s\n%.71c\n", index, '='); if (!rc) rc = fsl_buffer_appendf(buf, "hash - %s\nhash + %s\n", minus, plus); } - if (!rc && !FLAG_CHK(diff_flags, FSL_DIFF_BRIEF)) + if (!rc && (diff_flags & FSL_DIFF_BRIEF) == 0) rc = fsl_buffer_appendf(buf, "--- %s\n+++ %s\n", zminus, zplus); return rc; } @@ -5021,19 +4577,20 @@ * abspath absolute path to the file on disk being diffed * change enum denoting the versioning change of the file * diff_flags, context, and sbs are the same parameters as diff_file_artifact() */ static int -diff_file(struct fnc_diff_view_state *s, fsl_buffer *bminus, const char *zminus, - fsl_uuid_str xminus, const char *abspath, enum fsl_ckout_change_e change) +diff_file(fsl_buffer *buf, fsl_buffer *bminus, const char *zminus, + fsl_uuid_str xminus, const char *abspath, enum fsl_ckout_change_e change, + int diff_flags, int context, bool sbs) { fsl_cx *const f = fcli_cx(); - fsl_dibu *diffbld = NULL; fsl_buffer bplus = fsl_buffer_empty; fsl_buffer xplus = fsl_buffer_empty; const char *zplus = NULL; int rc = 0; + bool verbose; /* * If it exists, read content of abspath to diff EXCEPT for the content * of 'fossil rm FILE' files because they will either: (1) have the same * content as the versioned file's blob in bminus or (2) have changes. @@ -5089,86 +4646,30 @@ goto end; } if (rc) goto end; - s->index.offset = fsl_realloc(s->index.offset, - (s->index.n + 1) * sizeof(size_t)); - s->index.offset[s->index.n++] = s->buf.used; - rc = write_diff_meta(&s->buf, zminus, xminus, zplus, - fsl_buffer_str(&xplus), s->diff_flags, change); + rc = write_diff_meta(buf, zminus, xminus, zplus, fsl_buffer_str(&xplus), + diff_flags, change); if (rc) goto end; - rc = fnc_diff_builder(&diffbld, xminus, fsl_buffer_str(&xplus), zminus, - zplus, s->context, s->diff_flags, &s->buf); - if (rc) - goto end; - - if FLAG_CHK(s->diff_flags, FSL_DIFF_BRIEF) { + verbose = (diff_flags & FSL_DIFF_VERBOSE) != 0 ? true : false; + if (diff_flags & FSL_DIFF_BRIEF) { rc = fsl_buffer_compare(bminus, &bplus); if (!rc) - rc = fsl_buffer_appendf(&s->buf, "CHANGED -> %s\n", - zminus); - } else if (FLAG_CHK(s->diff_flags, FSL_DIFF_VERBOSE) || - (bminus->used && bplus.used)) - rc = fsl_diff_v2(bminus, &bplus, diffbld); + rc = fsl_buffer_appendf(buf, "CHANGED -> %s\n", zminus); + } else if (verbose || (bminus->used && bplus.used)) { + rc = fsl_diff_text_to_buffer(bminus, &bplus, buf, context, + sbs, diff_flags); + } end: fsl_buffer_clear(&bplus); fsl_buffer_clear(&xplus); - fnc_free_diff_builder(diffbld); - return rc; -} - -static int -fnc_diff_builder(fsl_dibu **ptr, fsl_uuid_cstr xminus, fsl_uuid_cstr xplus, - const char *zminus, const char *zplus, int context, int diff_flags, - fsl_buffer *buf) -{ - fsl_dibu *diffbld = NULL; - fsl_dibu_opt *diffopt = NULL; - struct fsl_dibu_opt_ansi ansiopt = {"", "", "", ""}; - int rc = FSL_RC_OK; - - *ptr = NULL; - - diffopt = fsl_malloc(sizeof(fsl_dibu_opt)); - if (diffopt == NULL) - return RC(FSL_RC_ERROR, "%s", "fsl_malloc"); - - - FLAG_SET(diff_flags, FSL_DIFF2_CONTEXT_ZERO); - diffopt->ansiColor = ansiopt; - diffopt->hashLHS = xminus; - diffopt->hashRHS = xplus; - diffopt->nameLHS = zminus; - diffopt->nameRHS = zplus; - diffopt->diffFlags = diff_flags; - diffopt->contextLines = context; - diffopt->out = fsl_output_f_buffer; - diffopt->outState = buf; - - rc = fsl_dibu_factory(FSL_DIBU_UNIFIED_TEXT, &diffbld); - if (!rc) { - diffbld->opt = diffopt; - diffbld->start = NULL; - *ptr = diffbld; - } else - fsl_free(diffopt); - - return rc; -} - -static void -fnc_free_diff_builder(fsl_dibu *diffbld) -{ - if (diffbld) { - if (diffbld->opt) - fsl_free(diffbld->opt); - diffbld->finalize(diffbld); - } + + return rc; } /* * Parse the deck of non-checkin commits to present a 'fossil ui' equivalent * of the corresponding artifact when selected from the timeline. @@ -5177,11 +4678,10 @@ static int diff_non_checkin(fsl_buffer *buf, struct fnc_commit_artifact *commit, int diff_flags, int context, int sbs) { fsl_cx *const f = fcli_cx(); - fsl_dibu *diffbld = NULL; fsl_buffer wiki = fsl_buffer_empty; fsl_buffer pwiki = fsl_buffer_empty; fsl_id_t prid = 0; fsl_size_t idx; int rc = 0; @@ -5253,35 +4753,27 @@ goto end; } } /* Diff the artifacts if a parent is found. */ - rc = fsl_sym_to_rid(f, commit->puuid, FSL_SATYPE_ANY, &prid); - if (rc) + if ((rc = fsl_sym_to_rid(f, commit->puuid, FSL_SATYPE_ANY, &prid))) goto end; - rc = fsl_deck_load_rid(f, d, prid, FSL_SATYPE_ANY); - if (rc) + if ((rc = fsl_deck_load_rid(f, d, prid, FSL_SATYPE_ANY))) goto end; fsl_buffer_append(&pwiki, d->W.mem, d->W.used); - rc = fnc_diff_builder(&diffbld, NULL, NULL, NULL, NULL, context, - diff_flags, buf); - if (rc) - goto end; - rc = fsl_diff_v2(&pwiki, &wiki, diffbld); - if (rc) - goto end; + rc = fsl_diff_text_to_buffer(&pwiki, &wiki, buf, context, sbs, + diff_flags); /* If a technote, provide the full content after its diff. */ if (d->type == FSL_SATYPE_TECHNOTE) fsl_buffer_appendf(buf, "\n---\n\n%s", wiki.mem); end: fsl_buffer_clear(&wiki); fsl_buffer_clear(&pwiki); fsl_deck_finalize(d); - fnc_free_diff_builder(diffbld); return rc; } /* * Compute the differences between two repository file artifacts to produce the @@ -5295,24 +4787,24 @@ * diff_flags bitwise flags to control the diff * context the number of context lines to surround changes * sbs number of columns in which to display each side-by-side diff */ static int -diff_file_artifact(struct fnc_diff_view_state *s, fsl_id_t vid1, - const fsl_card_F *a, const fsl_card_F *b, enum fsl_ckout_change_e change) +diff_file_artifact(fsl_buffer *buf, fsl_id_t vid1, const fsl_card_F *a, + fsl_id_t vid2, const fsl_card_F *b, enum fsl_ckout_change_e change, + int diff_flags, int context, int sbs, enum fnc_diff_type diff_type) { fsl_cx *const f = fcli_cx(); - fsl_dibu *diffbld = NULL; fsl_stmt stmt = fsl_stmt_empty; fsl_buffer fbuf1 = fsl_buffer_empty; fsl_buffer fbuf2 = fsl_buffer_empty; char *zminus0 = NULL, *zplus0 = NULL; const char *zplus = NULL, *zminus = NULL; fsl_uuid_str xplus0 = NULL, xminus0 = NULL; fsl_uuid_str xplus = NULL, xminus = NULL; - fsl_id_t vid2 = s->selected_commit->rid; int rc = 0; + bool verbose; assert(vid1 != vid2); assert(vid2 > 0 && "local checkout should be diffed with diff_checkout()"); @@ -5322,11 +4814,11 @@ rc = fsl_card_F_content(f, a, &fbuf1); if (rc) goto end; zminus = a->name; xminus = a->uuid; - } else if (s->selected_commit->diff_type == FNC_DIFF_BLOB) { + } else if (diff_type == FNC_DIFF_BLOB) { rc = fsl_cx_prepare(f, &stmt, "SELECT name FROM filename, mlink " "WHERE filename.fnid=mlink.fnid AND mlink.fid = %d", vid1); if (rc) { rc = RC(FSL_RC_DB, "%s %d", "fsl_cx_prepare", vid1); @@ -5352,11 +4844,11 @@ rc = fsl_card_F_content(f, b, &fbuf2); if (rc) goto end; zplus = b->name; xplus = b->uuid; - } else if (s->selected_commit->diff_type == FNC_DIFF_BLOB) { + } else if (diff_type == FNC_DIFF_BLOB) { rc = fsl_cx_prepare(f, &stmt, "SELECT name FROM filename, mlink " "WHERE filename.fnid=mlink.fnid AND mlink.fid = %d", vid2); if (rc) { rc = RC(FSL_RC_DB, "%s %d", "fsl_cx_prepare", vid2); @@ -5377,26 +4869,16 @@ xplus = xplus0; fsl_stmt_finalize(&stmt); fsl_content_get(f, vid2, &fbuf2); } - if (s->buf.used) { - s->index.offset = fsl_realloc(s->index.offset, - (s->index.n + 1) * sizeof(size_t)); - s->index.offset[s->index.n++] = s->buf.used + s->index.offset[0]; - } - rc = write_diff_meta(&s->buf, zminus, xminus, zplus, xplus, - s->diff_flags, change); - if (rc) - goto end; - - rc = fnc_diff_builder(&diffbld, xminus, xplus, zminus, zplus, - s->context, s->diff_flags, &s->buf); - if (rc) - goto end; - if (FLAG_CHK(s->diff_flags, FSL_DIFF_VERBOSE) || (a && b)) - rc = fsl_diff_v2(&fbuf1, &fbuf2, diffbld); + rc = write_diff_meta(buf, zminus, xminus, zplus, xplus, diff_flags, + change); + verbose = (diff_flags & FSL_DIFF_VERBOSE) != 0 ? true : false; + if (verbose || (a && b)) + rc = fsl_diff_text_to_buffer(&fbuf1, &fbuf2, buf, context, sbs, + diff_flags); if (rc) RC(rc, "%s: fsl_diff_text_to_buffer\n" " -> %s [%s]\n -> %s [%s]", fsl_rc_cstr(rc), a ? a->name : NULL_DEVICE, a ? a->uuid : NULL_DEVICE, b ? b->name : NULL_DEVICE, b ? b->uuid : NULL_DEVICE); @@ -5405,11 +4887,10 @@ fsl_free(zplus0); fsl_free(xminus0); fsl_free(xplus0); fsl_buffer_clear(&fbuf1); fsl_buffer_clear(&fbuf2); - fnc_free_diff_builder(diffbld); return rc; } static int show_diff(struct fnc_view *view) @@ -5452,62 +4933,51 @@ wchar_t *wcstr; char *line; size_t linesz = 0; ssize_t linelen; off_t line_offset; - attr_t rx = A_BOLD; - int col, wstrlen, max_lines = view->nlines; + int wstrlen; + int max_lines = view->nlines; int nlines = s->nlines; - int npad = 0, nprinted = 0, rc = FSL_RC_OK; - bool selected; + int rc = 0, nprintln = 0; - s->lineno = s->first_line_onscreen - 1; line_offset = s->line_offsets[s->first_line_onscreen - 1]; if (fseeko(s->f, line_offset, SEEK_SET)) return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "fseeko"); werase(view->window); if (headln) { - static char pct[MAX_PCT_LEN]; - double percent; - int ln, pctlen; - ln = s->gtl ? s->gtl : s->lineno + s->selected_line; - percent = 100.00 * ln / nlines; - pctlen = snprintf(pct, MAX_PCT_LEN, "%.*lf%%", - percent > 99.99 ? 0 : 2, percent); - if (pctlen < 0) - return RC(FSL_RC_RANGE, "%s", "snprintf"); - line = fsl_mprintf("[%d/%d] %s", ln, nlines, headln); - if (line == NULL) + if ((line = fsl_mprintf("[%d/%d] %s", (s->first_line_onscreen - + 1 + s->current_line), nlines, headln)) == NULL) return RC(FSL_RC_RANGE, "%s", "fsl_mprintf"); - rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0, 0, false); + rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0); fsl_free(line); fsl_free(headln); if (rc) return rc; - if (screen_is_shared(view) || view->active) - rx |= A_REVERSE; - wattron(view->window, rx); + if (screen_is_shared(view)) + wattron(view->window, A_REVERSE); waddwstr(view->window, wcstr); fsl_free(wcstr); wcstr = NULL; - col = wstrlen; - while (col++ < view->ncols) + while (wstrlen < view->ncols) { waddch(view->window, ' '); - if (wstrlen < view->ncols - pctlen) - mvwaddstr(view->window, 0, view->ncols - pctlen, pct); - wattroff(view->window, rx); + ++wstrlen; + } + if (screen_is_shared(view)) + wattroff(view->window, A_REVERSE); - if (--max_lines < 1) + if (max_lines <= 1) return rc; + --max_lines; } s->eof = false; line = NULL; - while (max_lines > 0 && nprinted < max_lines) { + while (max_lines > 0 && nprintln < max_lines) { linelen = getline(&line, &linesz, s->f); if (linelen == -1) { if (feof(s->f)) { s->eof = true; break; @@ -5516,68 +4986,51 @@ RC(ferror(s->f) ? fsl_errno_to_rc(errno, FSL_RC_IO) : FSL_RC_IO, "%s", "getline"); return rc; } - if (++s->lineno < s->first_line_onscreen) - continue; - if (s->gtl) - if (!gotoline(view, &s->lineno, &nprinted)) - continue; - - rx = 0; - if ((selected = nprinted == s->selected_line - 1)) - rx = A_BOLD | A_REVERSE; - if (s->showln) - npad = draw_lineno(view, nlines, s->lineno, rx); - if (s->colour) c = match_colour(&s->colours, line); - if (c && !(selected && s->sline == SLINE_MONO)) - rx |= COLOR_PAIR(c->scheme); - if (c || selected) - wattron(view->window, rx); - - if (s->first_line_onscreen + nprinted == s->matched_line && + if (c) + wattr_on(view->window, COLOR_PAIR(c->scheme), NULL); + if (s->first_line_onscreen + nprintln == s->matched_line && regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) { - rc = draw_matched_line(view, &wstrlen, npad, regmatch, - rx); + rc = write_matched_line(&wstrlen, line, view->ncols, 0, + view->window, regmatch); if (rc) { fsl_free(line); return rc; } } else { - rc = formatln(&wcstr, &wstrlen, line, - view->ncols - npad, npad, view->pos.col, true); + rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0); if (rc) { fsl_free(line); return rc; } waddwstr(view->window, wcstr); fsl_free(wcstr); wcstr = NULL; } - col = wstrlen + npad; - while (col++ < view->ncols) - waddch(view->window, ' '); - - if (c || selected) - wattroff(view->window, rx); - if (++nprinted == 1) - s->first_line_onscreen = s->lineno; + if (c) + wattr_off(view->window, COLOR_PAIR(c->scheme), NULL); + if (wstrlen <= view->ncols - 1) + waddch(view->window, '\n'); + ++nprintln; } fsl_free(line); - if (nprinted >= 1) - s->last_line_onscreen = s->first_line_onscreen + (nprinted - 1); + if (nprintln >= 1) + s->last_line_onscreen = s->first_line_onscreen + (nprintln - 1); else s->last_line_onscreen = s->first_line_onscreen; - drawborder(view); + draw_vborder(view); if (s->eof) { - while (nprinted++ < view->nlines) + while (nprintln < view->nlines) { waddch(view->window, '\n'); + ++nprintln; + } wstandout(view->window); waddstr(view->window, "(END)"); wstandend(view->window); } @@ -5596,151 +5049,106 @@ return false; return view->active; } -static bool +static int view_is_parent(struct fnc_view *view) { return view->parent == NULL; } -static bool +static int screen_is_split(struct fnc_view *view) { - return view->start_col > 0 || view->start_ln > 0; -} - -static void -updatescreen(WINDOW *win, bool panel, bool update) -{ -#ifdef __linux__ - wnoutrefresh(win); -#else - if (panel) - update_panels(); -#endif - if (update) - doupdate(); + return view->start_col > 0; } static int -draw_matched_line(struct fnc_view *view, int *col, int offset, - regmatch_t *regmatch, attr_t rx) +write_matched_line(int *col_pos, const char *line, int ncols_avail, + int start_column, WINDOW *window, regmatch_t *regmatch) { wchar_t *wcstr; char *s; - int rme, rms, skip = view->pos.col, wstrlen; - int n = 0, ncols_avail = view->ncols - offset, rc = 0; - attr_t hl = A_BOLD | A_REVERSE; - - *col = 0; - rms = regmatch->rm_so; - rme = regmatch->rm_eo; - - /* - * Copy line up to string match and draw to screen. Trim preceding skip - * chars if scrolled right. Don't copy if skip consumes substring. - */ - s = fsl_strndup(view->line.buf + skip, MAX(rms - skip, 0)); + int wstrlen; + int rc = 0; + + *col_pos = 0; + + /* Copy the line up to the matching substring & write it to screen. */ + s = fsl_strndup(line, regmatch->rm_so); if (s == NULL) return RC(FSL_RC_ERROR, "%s", "fsl_strndup"); - rc = formatln(&wcstr, &wstrlen, s, ncols_avail, offset, 0, false); + rc = formatln(&wcstr, &wstrlen, s, ncols_avail, start_column); if (rc) { free(s); return rc; } - waddwstr(view->window, wcstr); + waddwstr(window, wcstr); free(wcstr); free(s); ncols_avail -= wstrlen; - *col += wstrlen; + *col_pos += wstrlen; - /* - * Copy string match and draw with highlight. If skip traverses string - * match, trim n chars off the front. Don't copy if skip consumed match. - */ + /* If not EOL, copy matching string & write to screen with highlight. */ if (ncols_avail > 0) { - int len = rme - rms; - if (skip > rms) { - n = skip - rms; - len = MAX(len - n, 0); - } - s = fsl_strndup(view->line.buf + rms + n, len); + s = fsl_strndup(line + regmatch->rm_so, + regmatch->rm_eo - regmatch->rm_so); if (s == NULL) { rc = RC(FSL_RC_ERROR, "%s", "fsl_strndup"); free(s); return rc; } - rc = formatln(&wcstr, &wstrlen, s, ncols_avail, offset, - 0, false); - if (rc) { - free(s); - return rc; - } - wattron(view->window, COLOR_PAIR(FNC_COLOUR_HL_SEARCH) | hl); - waddwstr(view->window, wcstr); - wattroff(view->window, COLOR_PAIR(FNC_COLOUR_HL_SEARCH) | hl); - free(wcstr); - free(s); - ncols_avail -= wstrlen; - *col += wstrlen; - } - - /* - * Write rest of line if not yet at EOL. If skip passes the end of - * string match, trim n chars off the front of substring. - */ - if (ncols_avail > 0 && view->line.sz > rme) { - n = 0; - if (skip > rme) - n = MIN(skip - rme, view->line.sz - rme); - rc = formatln(&wcstr, &wstrlen, view->line.buf + rme + n, - ncols_avail, offset, 0, false); - if (rc) - return rc; - wattron(view->window, rx); - waddwstr(view->window, wcstr); - free(wcstr); - ncols_avail -= wstrlen; - *col += wstrlen; - while (--ncols_avail >= 0) { - ++(*col); - waddch(view->window, ' '); - } - wattroff(view->window, rx); - } - - return rc; -} - -static void -drawborder(struct fnc_view *view) + rc = formatln(&wcstr, &wstrlen, s, ncols_avail, start_column); + if (rc) { + free(s); + return rc; + } + wattr_on(window, A_REVERSE, NULL); + waddwstr(window, wcstr); + wattr_off(window, A_REVERSE, NULL); + free(wcstr); + free(s); + ncols_avail -= wstrlen; + *col_pos += wstrlen; + } + + /* Write the rest of the line if not yet at EOL. */ + if (ncols_avail > 0 && fsl_strlen(line) > (fsl_size_t)regmatch->rm_eo) { + rc = formatln(&wcstr, &wstrlen, line + regmatch->rm_eo, + ncols_avail, start_column); + if (rc) + return rc; + waddwstr(window, wcstr); + free(wcstr); + *col_pos += wstrlen; + } + + return rc; +} + +static void +draw_vborder(struct fnc_view *view) { const struct fnc_view *view_above; char *codeset = nl_langinfo(CODESET); PANEL *panel; if (view->parent) - drawborder(view->parent); + draw_vborder(view->parent); panel = panel_above(view->panel); if (panel == NULL) return; view_above = panel_userptr(panel); - if (view->mode == VIEW_SPLIT_HRZN) - mvwhline(view->window, view_above->start_ln - 1, - view->start_col, (strcmp(codeset, "UTF-8") == 0) ? - ACS_HLINE : '-', view->ncols); - else - mvwvline(view->window, view->start_ln, - view_above->start_col - 1, (strcmp(codeset, "UTF-8") == 0) ? - ACS_VLINE : '|', view->nlines); - - updatescreen(view->window, false, false); + mvwvline(view->window, view->start_ln, view_above->start_col - 1, + (strcmp(codeset, "UTF-8") == 0) ? ACS_VLINE : '|', view->nlines); +#ifdef __linux__ + wnoutrefresh(view->window); +#endif } static int diff_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch) { @@ -5749,194 +5157,66 @@ struct fnc_tl_view_state *tlstate; struct commit_entry *previous_selection; char *line = NULL; ssize_t linelen; size_t linesz = 0; - int nlines, i = 0, rc = FSL_RC_OK; - uint16_t nscroll = view->nlines - 2; + int i, rc = 0; bool tl_down = false; - nlines = s->nlines; - s->lineno = s->first_line_onscreen - 1 + s->selected_line; - switch (ch) { - case '0': - view->pos.col = 0; - break; - case '$': - view->pos.col = s->maxx - view->ncols / 2; - break; - case KEY_RIGHT: - case 'l': - if (view->pos.col + view->ncols / 2 < s->maxx) - view->pos.col += 2; - break; - case KEY_LEFT: - case 'h': - view->pos.col -= MIN(view->pos.col, 2); - break; - case CTRL('p'): - if (s->selected_commit->diff_type == FNC_DIFF_WIKI) - break; - if (!((size_t)s->lineno > s->index.lineno[s->index.n - 1])) { - if (s->index.idx == 0) - s->index.idx = s->index.n - 1; - else - --s->index.idx; - } else - s->index.idx = s->index.n - 1; - s->first_line_onscreen = s->index.lineno[s->index.idx]; - s->selected_line = 1; - break; - case CTRL('n'): - if (s->selected_commit->diff_type == FNC_DIFF_WIKI) - break; - if (!((size_t)s->lineno < s->index.lineno[0])) { - if (++s->index.idx == s->index.n) - s->index.idx = 0; - } else - s->index.idx = 0; - s->first_line_onscreen = s->index.lineno[s->index.idx]; - s->selected_line = 1; - break; - case CTRL('e'): - if (!s->eof) { + case KEY_DOWN: + case 'j': + if (!s->eof) + ++s->first_line_onscreen; + break; + case KEY_NPAGE: + case CTRL('f'): + case ' ': + if (s->eof) + break; + i = 0; + while (!s->eof && i++ < view->nlines - 1) { + linelen = getline(&line, &linesz, s->f); ++s->first_line_onscreen; - if (s->lineno == nlines) - --s->selected_line; + if (linelen == -1) { + if (feof(s->f)) + s->eof = true; + else + RC(ferror(s->f) ? + fsl_errno_to_rc(errno, FSL_RC_IO) : + FSL_RC_IO, "%s", "getline"); + break; + } } + free(line); + break; + case KEY_END: + case 'G': + if (s->eof) + break; + s->first_line_onscreen = (s->nlines - view->nlines) + 2; + s->eof = true; break; - case CTRL('y'): + case KEY_UP: + case 'k': if (s->first_line_onscreen > 1) --s->first_line_onscreen; break; - case KEY_DOWN: - case 'j': - if (s->first_line_onscreen + s->selected_line == nlines + 2) - break; - if (s->selected_line < view->nlines - 1 && s->lineno != nlines) - ++s->selected_line; - else if (s->last_line_onscreen <= nlines && !s->eof) { - ++s->first_line_onscreen; - if (s->lineno == nlines) - --s->selected_line; - } - break; - case KEY_UP: - case 'k': - if (s->selected_line > 1) - --s->selected_line; - else if (s->selected_line == 1 && s->first_line_onscreen > 1) - --s->first_line_onscreen; - break; - case CTRL('d'): - nscroll >>= 1; - /* FALL THROUGH */ - case KEY_NPAGE: - case CTRL('f'): - case ' ': - if (s->eof && s->last_line_onscreen == nlines) { - uint16_t move = nlines - s->lineno; - s->selected_line += MIN(nscroll, move); - break; - } - while (!s->eof && i++ < nscroll) { - linelen = getline(&line, &linesz, s->f); - ++s->first_line_onscreen; - if (linelen == -1) { - if (!feof(s->f)) - return RC(ferror(s->f) ? - fsl_errno_to_rc(errno, FSL_RC_IO) : - FSL_RC_IO, "%s", "getline"); - if (s->selected_line > nscroll) - s->selected_line = view->nlines - 2; - else - s->selected_line = nscroll; - s->eof = true; - break; - } - } - fsl_free(line); - break; - case CTRL('u'): - nscroll >>= 1; - /* FALL THROUGH */ case KEY_PPAGE: case CTRL('b'): - if (s->first_line_onscreen == 1) { - uint16_t move = s->selected_line - 1; - s->selected_line -= MIN(nscroll, move); - break; - } - while (i++ < nscroll && s->first_line_onscreen > 1) - --s->first_line_onscreen; - break; - case KEY_END: - case 'G': - if (nlines < view->nlines - 1) { - s->selected_line = nlines; - s->first_line_onscreen = 1; - } else { - s->selected_line = nscroll; - s->first_line_onscreen = nlines - view->nlines + 3; - } - /* - * XXX Assume user would expect file navigation (C-n/p) to - * follow a jump to the end of the diff. - */ - s->index.idx = s->index.n - 1; - s->eof = true; + if (s->first_line_onscreen == 1) + break; + i = 0; + while (i++ < view->nlines - 1 && s->first_line_onscreen > 1) + --s->first_line_onscreen; break; case 'g': if (!fnc_home(view)) break; /* FALL THROUGH */ case KEY_HOME: - s->selected_line = 1; s->first_line_onscreen = 1; - /* - * XXX Assume user would expect file navigation (C-n/p) to - * reset after jumping home. - */ - s->index.idx = 0; - break; - case 'F': - if (s->selected_commit->diff_type == FNC_DIFF_WIKI) - break; - fsl_buffer buf = fsl_buffer_empty; - struct input input; - char *end = fsl_mprintf(", ..., %d: ", s->index.n); - size_t maxwidth = view->ncols - 12; - uint32_t idx = 0; - - fsl_buffer_append(&buf, "File ", -1); - while (++idx <= s->index.n && buf.used < maxwidth) - fsl_buffer_appendf(&buf, - "%d%s", idx, (idx + 1 < s->index.n ? - buf.used + 6 < maxwidth ? - ", " : end : (idx < s->index.n ? - " or " : ": "))); - input = (struct input){(int []){1, s->index.n}, - fsl_buffer_str(&buf), INPUT_NUMERIC, true}; - rc = fnc_prompt_input(view, &input); - if (input.ret) { - s->index.idx = input.ret - 1; - s->first_line_onscreen = s->index.lineno[s->index.idx]; - s->selected_line = 1; - } - fsl_buffer_clear(&buf); - fsl_free(end); - break; - case 'L': { - struct input input = {(int []){1, nlines}, "line: ", - INPUT_NUMERIC, true}; - rc = fnc_prompt_input(view, &input); - s->gtl = input.ret; - break; - } - case '#': - s->showln = !s->showln; break; case 'b': { int start_col = 0; if (view_is_parent(view)) start_col = view_split_start_col(view->start_col); @@ -5967,29 +5247,40 @@ case 'v': case 'w': if (ch == 'c') s->colour = !s->colour; if (ch == 'i') - FLAG_TOG(s->diff_flags, FSL_DIFF2_INVERT); + s->diff_flags ^= FSL_DIFF_INVERT; if (ch == 'v') - FLAG_TOG(s->diff_flags, FSL_DIFF_VERBOSE); + s->diff_flags ^= FSL_DIFF_VERBOSE; if (ch == 'w') - FLAG_TOG(s->diff_flags, FSL_DIFF2_IGNORE_ALLWS); - rc = reset_diff_view(view, true); + s->diff_flags ^= FSL_DIFF_IGNORE_ALLWS; + wclear(view->window); + s->first_line_onscreen = 1; + s->last_line_onscreen = view->nlines; + show_diff_status(view); + rc = create_diff(s); break; case '-': case '_': if (s->context > 0) { --s->context; - rc = reset_diff_view(view, true); + show_diff_status(view); + rc = create_diff(s); + if (s->first_line_onscreen + view->nlines - 1 > + (int)s->nlines) { + s->first_line_onscreen = 1; + s->last_line_onscreen = view->nlines; + } } break; case '+': case '=': - if (s->context < MAX_DIFF_CTX) { + if (s->context < DIFF_MAX_CTXT) { ++s->context; - rc = reset_diff_view(view, true); + show_diff_status(view); + rc = create_diff(s); } break; case CTRL('j'): case '>': case '.': @@ -6013,57 +5304,20 @@ break; if ((rc = set_selected_commit(s, tlstate->selected_commit))) break; - s->selected_line = 1; - reset_diff_view(view, false); + s->first_line_onscreen = 1; + s->last_line_onscreen = view->nlines; + + show_diff_status(view); + rc = create_diff(s); break; default: break; } - return rc; -} - -static int -reset_diff_view(struct fnc_view *view, bool stay) -{ - struct fnc_diff_view_state *s = &view->state.diff; - int n, rc = FSL_RC_OK; - - n = s->nlines; - free_index(&s->index); - show_diff_status(view); - rc = create_diff(s); - if (rc) - return rc; - - if (stay) { - float scale = (float)s->first_line_onscreen / n; - s->first_line_onscreen = MAX(1, (int)(s->nlines * scale)); - } else { - s->first_line_onscreen = 1; - view->pos.col = 0; - } - - s->last_line_onscreen = s->first_line_onscreen + view->nlines; - s->matched_line = 0; - - return rc; -} - -static int -request_tl_commits(struct fnc_view *view) -{ - struct fnc_tl_view_state *state = &view->state.timeline; - int rc = FSL_RC_OK; - - state->thread_cx.ncommits_needed = state->nscrolled; - rc = signal_tl_thread(view, 1); - state->nscrolled = 0; - return rc; } static int set_selected_commit(struct fnc_diff_view_state *s, struct commit_entry *entry) @@ -6077,132 +5331,86 @@ s->selected_commit = entry->commit; return 0; } -static void -diff_grep_init(struct fnc_view *view) +static int +diff_search_init(struct fnc_view *view) { struct fnc_diff_view_state *s = &view->state.diff; s->matched_line = 0; + return 0; } static int -find_next_match(struct fnc_view *view) -{ - FILE *f = NULL; - off_t *line_offsets = NULL; - ssize_t linelen; - size_t nlines = 0, linesz = 0; - int *first, *last, *match, *selected; - int lineno; - char *line = NULL; - - first = last = match = selected = NULL; - grep_set_view(view, &f, &line_offsets, &nlines, &first, &last, - &match, &selected); +diff_search_next(struct fnc_view *view) +{ + struct fnc_diff_view_state *s = &view->state.diff; + char *line = NULL; + ssize_t linelen; + size_t linesz = 0; + int start_ln; if (view->searching == SEARCH_DONE) { view->search_status = SEARCH_CONTINUE; return 0; } - if (*match) { - if (view->searching == SEARCH_FORWARD) - lineno = *match + 1; - else - lineno = *match - 1; - } else { - if (view->searching == SEARCH_FORWARD) - lineno = 1; - else - lineno = nlines; - } - - while (1) { - off_t offset; - - if (lineno <= 0 || (size_t)lineno > nlines) { - if (*match == 0) { - view->search_status = SEARCH_CONTINUE; - break; - } - - if (view->searching == SEARCH_FORWARD) - lineno = 1; - else - lineno = nlines; - } - - offset = line_offsets[lineno - 1]; - if (fseeko(f, offset, SEEK_SET) != 0) { - fsl_free(line); - return RC(fsl_errno_to_rc(errno, FSL_RC_IO), - "%s", "fseeko"); - } - /* - * Expand tabs for accurate rm_so/rm_eo offsets, and save to - * view->line so we don't have to expand when drawing matches. - */ - linelen = getline(&line, &linesz, f); - view->line.sz = expand_tab(view->line.buf, - sizeof(view->line.buf), line, linelen); - if (linelen != -1 && regexec(&view->regex, view->line.buf, 1, - &view->regmatch, 0) == 0) { - view->search_status = SEARCH_CONTINUE; - *match = lineno; - while (view->pos.col > view->regmatch.rm_so) - --view->pos.col; /* Scroll till on-screen. */ - break; - } - if (view->searching == SEARCH_FORWARD) - ++lineno; - else - --lineno; - } - fsl_free(line); - - /* - * If match is on current screen, move to it and highlight; else, - * scroll view till matching line is ~1/3rd from the top and highlight. - */ - if (*match) { - if (*match >= *first && *match <= *last) - *selected = *match - *first + 1; - else { - *first = MAX(*match - view->nlines / 3, 1); - *selected = *match - *first + 1; - } - } - - return FSL_RC_OK; -} - -static void -grep_set_view(struct fnc_view *view, FILE **f, off_t **line_offsets, - size_t *nlines, int **first, int **last, int **match, int **selected) -{ - if (view->vid == FNC_VIEW_DIFF) { - struct fnc_diff_view_state *s = &view->state.diff; - *f = s->f; - *nlines = s->nlines; - *line_offsets = s->line_offsets; - *match = &s->matched_line; - *first = &s->first_line_onscreen; - *last = &s->last_line_onscreen; - *selected = &s->selected_line; - } else if (view->vid == FNC_VIEW_BLAME) { - struct fnc_blame_view_state *s = &view->state.blame; - *f = s->blame.f; - *nlines = s->blame.nlines; - *line_offsets = s->blame.line_offsets; - *match = &s->matched_line; - *first = &s->first_line_onscreen; - *last = &s->last_line_onscreen; - *selected = &s->selected_line; - } + if (s->matched_line) { + if (view->searching == SEARCH_FORWARD) + start_ln = s->matched_line + 1; + else + start_ln = s->matched_line - 1; + } else { + if (view->searching == SEARCH_FORWARD) + start_ln = 1; + else + start_ln = s->nlines; + } + + while (1) { + off_t offset; + + if (start_ln <= 0 || start_ln > (int)s->nlines) { + if (s->matched_line == 0) { + view->search_status = SEARCH_CONTINUE; + break; + } + + if (view->searching == SEARCH_FORWARD) + start_ln = 1; + else + start_ln = s->nlines; + } + + offset = s->line_offsets[start_ln - 1]; + if (fseeko(s->f, offset, SEEK_SET) != 0) { + free(line); + return RC(fsl_errno_to_rc(errno, FSL_RC_IO), + "%s", "fseeko"); + } + linelen = getline(&line, &linesz, s->f); + if (linelen != -1 && regexec(&view->regex, line, 1, + &view->regmatch, 0) == 0) { + view->search_status = SEARCH_CONTINUE; + s->matched_line = start_ln; + break; + } + if (view->searching == SEARCH_FORWARD) + ++start_ln; + else + --start_ln; + } + free(line); + + if (s->matched_line) { + s->first_line_onscreen = s->matched_line; + s->current_line = 1; + } + + return 0; } static int close_diff_view(struct fnc_view *view) { @@ -6217,25 +5425,13 @@ s->id2 = NULL; fsl_free(s->line_offsets); free_colours(&s->colours); s->line_offsets = NULL; s->nlines = 0; - free_index(&s->index); return rc; } -static void -free_index(struct index *index) -{ - index->idx = 0; - index->n = 0; - fsl_free(index->lineno); - index->lineno = NULL; - fsl_free(index->offset); - index->offset = NULL; -} - static void fnc_resizeterm(void) { struct winsize size; int cols, lines; @@ -6249,13 +5445,13 @@ } resize_term(lines, cols); } static int -view_resize(struct fnc_view *view, enum view_mode mode) +view_resize(struct fnc_view *view) { - int nlines, ncols, rc = FSL_RC_OK; + int nlines, ncols; if (view->lines > LINES) nlines = view->nlines - (view->lines - LINES); else nlines = view->nlines + (LINES - view->lines); @@ -6274,25 +5470,25 @@ view->nlines = nlines; view->ncols = ncols; view->lines = LINES; view->cols = COLS; - if (view->child && mode != VIEW_SPLIT_NONE) { + if (view->child) { view->child->start_col = view_split_start_col(view->start_col); - if (view->mode == VIEW_SPLIT_HRZN || !view->child->start_col) { - rc = make_fullscreen(view->child); + if (view->child->start_col == 0) { + make_fullscreen(view->child); if (view->child->active) show_panel(view->child->panel); else show_panel(view->panel); } else { - rc = make_splitscreen(view->child); + make_splitscreen(view->child); show_panel(view->child->panel); } } - return rc; + return 0; } /* * Consume repeatable arguments containing artifact type values used in * constructing the SQL query to generate commit records of the specified type @@ -6304,13 +5500,12 @@ fcli_flag_type_arg_cb(fcli_cliflag const *v) { struct artifact_types *ft = &fnc_init.filter_types; const char *t = *((const char **)v->flagValue); - /* Valid types: ci, e, f, g, t, w */ - if (t[2] || (t[1] && (*t != 'c' || t[1] != 'i')) || (!t[1] && - (*t != 'e' && *t != 'f' && *t != 'g' && *t != 't' && *t != 'w'))) { + if (*t != 'e' && *t != 'f' && *t != 'g' && + *t != 't' && *t != 'w' && fsl_strcmp(t, "ci")) { fnc_init.err = RC(FSL_RC_TYPE, "invalid type: %s", t); usage(); /* NOT REACHED */ } @@ -6392,53 +5587,52 @@ static void usage_timeline(void) { fsl_fprintf(fnc_init.err ? stderr : stdout, - " usage: %s timeline [-C|--no-colour] [-R path] [-T tag] " - "[-b branch] [-c commit] [-f glob] [-h|--help] [-n n] [-t type] " - "[-u user] [-z|--utc] [path]\n" + " usage: %s timeline [-C|--no-colour] [-T tag] [-b branch] " + "[-c commit] [-f glob] [-h|--help] [-n n] [-t type] [-u user] " + "[-z|--utc] [path]\n" " e.g.: %s timeline --type ci -u jimmy src/frobnitz.c\n\n", fcli_progname(), fcli_progname()); } static void usage_diff(void) { fsl_fprintf(fnc_init.err ? stderr : stdout, - " usage: %s diff [-C|--no-colour] [-R path] [-h|--help] " - "[-i|--invert] [-q|--quiet] [-w|--whitespace] [-x|--context n] " + " usage: %s diff [-C|--no-colour] [-h|--help] [-i|--invert]" + " [-q|--quiet] [-w|--whitespace] [-x|--context n] " "[artifact1 [artifact2]] [path ...]\n " "e.g.: %s diff --context 3 d34db33f c0ff33 src/*.c\n\n", fcli_progname(), fcli_progname()); } static void usage_tree(void) { fsl_fprintf(fnc_init.err ? stderr : stdout, - " usage: %s tree [-C|--no-colour] [-R path] [-c commit] [-h|--help]" - " [path]\n" + " usage: %s tree [-C|--no-colour] [-c commit] [-h|--help] [path]\n" " e.g.: %s tree -c d34dc0d3\n\n" , fcli_progname(), fcli_progname()); } static void usage_blame(void) { fsl_fprintf(fnc_init.err ? stderr : stdout, - " usage: %s blame [-C|--no-colour] [-R path] [-c commit [-r]] " - "[-h|--help] [-n n] path\n" + " usage: %s blame [-C|--no-colour] [-c commit [-r]] [-h|--help] " + "[-n n] path\n" " e.g.: %s blame -c d34db33f src/foo.c\n\n" , fcli_progname(), fcli_progname()); } static void usage_branch(void) { fsl_fprintf(fnc_init.err ? stderr : stdout, - " usage: %s branch [-C|--no-colour] [-R path] [-a|--after date] " + " usage: %s branch [-C|--no-colour] [-a|--after date] " "[-b|--before date] [-c|--closed] [-h|--help] [-o|--open] " "[-p|--no-private] [-r|--reverse] [-s|--sort order] [glob]\n" " e.g.: %s branch -b 2020-10-10\n\n" , fcli_progname(), fcli_progname()); } @@ -6445,12 +5639,11 @@ static void usage_config(void) { fsl_fprintf(fnc_init.err ? stderr : stdout, - " usage: %s config [-R path] [-h|--help] [--ls] " - "[setting [value|--unset]]\n" + " usage: %s config [-h|--help] [--ls] [setting [value|--unset]]\n" " e.g.: %s config FNC_DIFF_COMMIT blue\n\n" , fcli_progname(), fcli_progname()); } static int @@ -6464,12 +5657,11 @@ fsl_deck d = fsl_deck_empty; fsl_stmt *q = NULL; const char *artifact1 = NULL, *artifact2 = NULL; char *path0 = NULL; fsl_id_t prid = -1, rid = -1; - long context = DEF_DIFF_CTX; - int rc = FSL_RC_OK; + int context = DIFF_DEF_CTXT, rc = 0; unsigned short blob = 0; enum fnc_diff_type diff_type = FNC_DIFF_CKOUT; bool showmeta = false; rc = fcli_process_flags(argv->flags); @@ -6609,22 +5801,16 @@ } rc = init_curses(); if (rc) goto end; -#ifdef __OpenBSD__ - rc = init_unveil(fsl_cx_db_file_repo(f, NULL), - fsl_cx_ckout_dir_name(f, NULL), false); - if (rc) - goto end; -#endif if (fnc_init.context) { if ((rc = strtonumcheck(&context, fnc_init.context, INT_MIN, INT_MAX))) goto end; - context = MIN(MAX_DIFF_CTX, context); + context = MIN(DIFF_MAX_CTXT, context); } view = view_open(0, 0, 0, 0, FNC_VIEW_DIFF); if (view == NULL) { rc = RC(FSL_RC_ERROR, "%s", "view_open"); @@ -6646,17 +5832,17 @@ fnc_pathlist_free(&paths); return rc; } static int -browse_commit_tree(struct fnc_view **new_view, int start_col, int start_ln, +browse_commit_tree(struct fnc_view **new_view, int start_col, struct commit_entry *entry, const char *path) { struct fnc_view *tree_view; int rc = 0; - tree_view = view_open(0, 0, start_ln, start_col, FNC_VIEW_TREE); + tree_view = view_open(0, 0, 0, start_col, FNC_VIEW_TREE); if (tree_view == NULL) return RC(FSL_RC_ERROR, "%s", "view_open"); rc = open_tree_view(tree_view, path, entry->commit->rid); if (rc) @@ -6721,16 +5907,10 @@ } rc = init_curses(); if (rc) goto end; -#ifdef __OpenBSD__ - rc = init_unveil(fsl_cx_db_file_repo(f, NULL), - fsl_cx_ckout_dir_name(f, NULL), false); - if (rc) - goto end; -#endif view = view_open(0, 0, 0, 0, FNC_VIEW_TREE); if (view == NULL) { RC(FSL_RC_ERROR, "%s", "view_open"); goto end; @@ -6803,12 +5983,12 @@ } view->show = show_tree_view; view->input = tree_input_handler; view->close = close_tree_view; - view->grep_init = tree_grep_init; - view->grep = tree_search_next; + view->search_init = tree_search_init; + view->search_next = tree_search_next; end: if (rc) close_tree_view(view); return rc; } @@ -6911,14 +6091,14 @@ rc = fsl_deck_load_rid(f, &d, rid, FSL_SATYPE_CHECKIN); if (rc) return RC(rc, "fsl_deck_load_rid(%d) [%s]", rid, id); rc = fsl_deck_F_rewind(&d); if (rc) - goto end; + goto end;; rc = fsl_deck_F_next(&d, &cf); if (rc) - goto end; + goto end;; while (cf) { char *filename = NULL, *uuid = NULL; fsl_time_t mtime; @@ -6932,21 +6112,21 @@ rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup"); goto end; } rc = fsl_mtime_of_F_card(f, rid, cf, &mtime); if (!rc) - rc = link_tree_node(ptr, filename, uuid, - fsl_unix_to_julian(mtime)); + rc = link_tree_node(ptr, filename, uuid, mtime); fsl_free(filename); fsl_free(uuid); if (!rc) rc = fsl_deck_F_next(&d, &cf); if (rc) goto end; } end: fsl_deck_finalize(&d); + *repo = ptr; return rc; } /* @@ -7044,11 +6224,11 @@ * mtime Modification time of the file * Returns 0 on success, non-zero on error. */ static int link_tree_node(struct fnc_repository_tree *tree, const char *path, - const char *uuid, double mtime) + const char *uuid, fsl_time_t mtime) { struct fnc_repo_tree_node *parent_dir; fsl_buffer buf = fsl_buffer_empty; struct stat s; int i, rc = 0; @@ -7160,11 +6340,11 @@ if (rc) return rc; rc = draw_tree(view, treepath); fsl_free(treepath); - drawborder(view); + draw_vborder(view); return rc; } /* @@ -7243,11 +6423,11 @@ { struct fnc_tree_view_state *s = &view->state.tree; struct fnc_tree_entry *te; struct fnc_colour *c = NULL; wchar_t *wcstr; - int rc = FSL_RC_OK; + int rc = 0; int wstrlen, n, idx, nentries; int limit = view->nlines; uint_fast8_t hashlen = FSL_UUID_STRLEN_MIN; s->ndisplayed = 0; @@ -7254,12 +6434,11 @@ werase(view->window); if (limit == 0) return rc; /* Write (highlighted) headline (if view is active in splitscreen). */ - rc = formatln(&wcstr, &wstrlen, s->tree_label, view->ncols, 0, 0, - false); + rc = formatln(&wcstr, &wstrlen, s->tree_label, view->ncols, 0); if (rc) return rc; if (screen_is_shared(view)) wattron(view->window, A_REVERSE); if (s->colour) @@ -7279,11 +6458,11 @@ wcstr = NULL; if (--limit <= 0) return rc; /* Write this (sub)tree's absolute repository path subheader. */ - rc = formatln(&wcstr, &wstrlen, treepath, view->ncols, 0, 0, false); + rc = formatln(&wcstr, &wstrlen, treepath, view->ncols, 0); if (rc) return rc; waddwstr(view->window, wcstr); fsl_free(wcstr); wcstr = NULL; @@ -7297,15 +6476,16 @@ /* Write parent dir entry (i.e., "..") if top of the tree is in view. */ if (s->first_entry_onscreen == NULL) { te = &s->tree->entries[0]; if (s->selected_idx == 0) { - wattr_on(view->window, A_REVERSE, NULL); + if (view->active) + wattr_on(view->window, A_REVERSE, NULL); s->selected_entry = NULL; } waddstr(view->window, " ..\n"); - if (s->selected_idx == 0) + if (s->selected_idx == 0 && view->active) wattr_off(view->window, A_REVERSE, NULL); ++s->ndisplayed; if (--limit <= 0) return rc; n = 1; @@ -7314,20 +6494,20 @@ te = s->first_entry_onscreen; } nentries = s->tree->nentries; for (idx = 0; idx < nentries; ++idx) /* Find max hash length. */ - hashlen = MAX(fsl_strlen(s->tree->entries[idx].uuid), hashlen); + if (hashlen < fsl_strlen(s->tree->entries[idx].uuid)) + hashlen = fsl_strlen(s->tree->entries[idx].uuid); /* Iterate and write tree nodes postfixed with path type identifier. */ for (idx = te->idx; idx < nentries; ++idx) { char *line = NULL, *idstr = NULL, *targetlnk = NULL; - char iso8601[ISO8601_TIMESTAMP] = {0}; const char *modestr = ""; mode_t mode; if (idx < 0 || idx >= s->tree->nentries) - return rc; + return 0; te = &s->tree->entries[idx]; mode = te->mode; if (s->show_id) { idstr = fsl_strdup(te->uuid); @@ -7335,11 +6515,10 @@ if (idstr == NULL && !S_ISDIR(mode)) return RC(FSL_RC_ERROR, "%s", "fsl_strdup"); /* If needed, pad SHA1 hash to align w/ SHA3 hashes. */ if (idstr == NULL || fsl_strlen(idstr) < hashlen) { char buf[hashlen], pad = '.'; - buf[hashlen] = '\0'; idstr = fsl_mprintf("%s%s", idstr ? idstr : "", (char *)memset(buf, pad, hashlen - fsl_strlen(idstr))); if (idstr == NULL) return RC(FSL_RC_RANGE, @@ -7364,45 +6543,39 @@ } else if (S_ISDIR(mode)) modestr = "/"; else if (mode & S_IXUSR) modestr = "*"; - if (s->show_date) { - char *t; - if (fsl_julian_to_iso8601(te->mtime, iso8601, false)) - *(t = strchr(iso8601, 'T')) = ' '; - else - rc = FSL_RC_ERROR; - } - line = fsl_mprintf("%s%s%.*s %s%s%s%s", idstr ? idstr : "", - (*iso8601 && idstr) ? " " : "", ISO8601_DATE_HHMM, - *iso8601 ? iso8601 : "", te->basename, modestr, - targetlnk ? " -> ": "", targetlnk ? targetlnk : ""); + if ((line = fsl_mprintf("%s %s%s%s%s", idstr ? idstr : "", + te->basename, modestr, targetlnk ? " -> ": "", + targetlnk ? targetlnk : "")) == NULL) { + fsl_free(idstr); + fsl_free(targetlnk); + return RC(FSL_RC_RANGE, "%s", "fsl_mprintf"); + } fsl_free(idstr); fsl_free(targetlnk); - if (rc || line == NULL) - return RC(rc ? rc : FSL_RC_RANGE, "%s", - rc ? "fsl_julian_to_iso8601" : "fsl_mprintf"); - rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0, 0, false); + rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0); if (rc) { fsl_free(line); break; } if (n == s->selected_idx) { - wattr_on(view->window, A_REVERSE, NULL); + if (view->active) + wattr_on(view->window, A_REVERSE, NULL); s->selected_entry = te; } if (s->colour) c = match_colour(&s->colours, line); if (c) wattr_on(view->window, COLOR_PAIR(c->scheme), NULL); waddwstr(view->window, wcstr); if (c) wattr_off(view->window, COLOR_PAIR(c->scheme), NULL); - if (wstrlen < view->ncols) + if (wstrlen < view->ncols - 1) waddch(view->window, '\n'); - if (n == s->selected_idx) + if (n == s->selected_idx && view->active) wattr_off(view->window, A_REVERSE, NULL); fsl_free(line); fsl_free(wcstr); wcstr = NULL; ++n; @@ -7476,13 +6649,13 @@ static int tree_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch) { struct fnc_view *branch_view, *timeline_view; struct fnc_tree_view_state *s = &view->state.tree; + struct fnc_tl_thread_cx *tcx = NULL; struct fnc_tree_entry *te; - int n, start_col = 0, rc = FSL_RC_OK; - uint16_t nscroll = view->nlines - 3; + int n, start_col = 0, rc = 0; switch (ch) { case 'b': if (view_is_parent(view)) start_col = view_split_start_col(view->start_col); @@ -7494,10 +6667,12 @@ 0, 0); if (rc) { view_close(branch_view); return rc; } + tcx = fcli_cx()->clientState.state; + tcx->needs_reset = true; view->active = false; branch_view->active = true; if (view_is_parent(view)) { rc = view_close_child(view); if (rc) @@ -7508,13 +6683,10 @@ *new_view = branch_view; break; case 'c': s->colour = !s->colour; break; - case 'd': - s->show_date = !s->show_date; - break; case 'i': s->show_id = !s->show_id; break; case 't': if (!s->selected_entry) @@ -7562,60 +6734,53 @@ te = get_tree_entry(s->tree, te->idx - 1); } if (n > 0) s->selected_idx = n - 1; break; + case KEY_UP: + case 'k': + if (s->selected_idx > 0) { + --s->selected_idx; + break; + } + tree_scroll_up(s, 1); + break; + case KEY_PPAGE: + case CTRL('b'): + if (s->tree == s->root) { + if (&s->tree->entries[0] == s->first_entry_onscreen) + s->selected_idx = 0; + } else { + if (s->first_entry_onscreen == NULL) + s->selected_idx = 0; + } + tree_scroll_up(s, MAX(0, view->nlines - 3)); + break; case KEY_DOWN: case 'j': if (s->selected_idx < s->ndisplayed - 1) { ++s->selected_idx; break; } if (get_tree_entry(s->tree, s->last_entry_onscreen->idx + 1) == NULL) break; /* Reached last entry. */ - tree_scroll_down(view, 1); - break; - case KEY_UP: - case 'k': - if (s->selected_idx > 0) { - --s->selected_idx; - break; - } - tree_scroll_up(s, 1); - break; - case CTRL('d'): - nscroll >>= 1; - /* FALL THROUGH */ + tree_scroll_down(s, 1); + break; case KEY_NPAGE: case CTRL('f'): if (get_tree_entry(s->tree, s->last_entry_onscreen->idx + 1) == NULL) { /* * When the last entry on screen is the last node in the * tree move cursor to it instead of scrolling the view. */ if (s->selected_idx < s->ndisplayed - 1) - s->selected_idx += MIN(nscroll, - s->ndisplayed - s->selected_idx - 1); - break; - } - tree_scroll_down(view, nscroll); - break; - case CTRL('u'): - nscroll >>= 1; - /* FALL THROUGH */ - case KEY_PPAGE: - case CTRL('b'): - if (s->tree == s->root) { - if (&s->tree->entries[0] == s->first_entry_onscreen) - s->selected_idx -= MIN(s->selected_idx, nscroll); - } else { - if (s->first_entry_onscreen == NULL) - s->selected_idx -= MIN(s->selected_idx, nscroll); - } - tree_scroll_up(s, nscroll); + s->selected_idx = s->ndisplayed - 1; + break; + } + tree_scroll_down(s, view->nlines - 3); break; case KEY_BACKSPACE: case KEY_ENTER: case KEY_LEFT: case KEY_RIGHT: @@ -7639,12 +6804,10 @@ fnc_object_tree_close(s->tree); s->tree = parent->tree; s->first_entry_onscreen = parent->first_entry_onscreen; s->selected_entry = parent->selected_entry; s->selected_idx = parent->selected_idx; - if (s->selected_idx > view->nlines - 3) - offset_selected_line(view); fsl_free(parent); } else if (s->selected_entry != NULL && S_ISDIR(s->selected_entry->mode)) { struct fnc_tree_object *subtree = NULL; rc = tree_builder(s->repo, &subtree, @@ -7654,13 +6817,30 @@ rc = visit_subtree(s, subtree); if (rc) { fnc_object_tree_close(subtree); break; } - } else if (s->selected_entry != NULL && - S_ISREG(s->selected_entry->mode)) - rc = blame_selected_file(new_view, view); + } else if (S_ISREG(s->selected_entry->mode)) { + struct fnc_view *blame_view; + int start_col = view_is_parent(view) ? + view_split_start_col(view->start_col) : 0; + + rc = blame_tree_entry(&blame_view, start_col, + s->selected_entry, &s->parents, s->commit_id); + if (rc) + break; + view->active = false; + blame_view->active = true; + if (view_is_parent(view)) { + rc = view_close_child(view); + if (rc) + return rc; + view_set_child(view, blame_view); + view->focus_child = true; + } else + *new_view = blame_view; + } break; case KEY_RESIZE: if (view->nlines >= 4 && s->selected_idx >= view->nlines - 3) s->selected_idx = view->nlines - 4; break; @@ -7669,34 +6849,10 @@ } return rc; } -static int -blame_selected_file(struct fnc_view **new_view, struct fnc_view *view) -{ - fsl_cx *const f = fcli_cx(); - struct fnc_tree_view_state *s = &view->state.tree; - fsl_buffer buf = fsl_buffer_empty; - fsl_id_t fid; - int rc = FSL_RC_OK; - - fid = fsl_uuid_to_rid(f, s->selected_entry->uuid); - rc = fsl_content_get(f, fid, &buf); - if (rc) - goto end; - - if (fsl_looks_like_binary(&buf)) - fnc_print_msg(view, "-- cannot blame binary file --", false, - true, true); - else - rc = request_view(new_view, view, FNC_VIEW_BLAME); -end: - fsl_buffer_clear(&buf); - return rc; -} - static int timeline_tree_entry(struct fnc_view **new_view, int start_col, struct fnc_tree_view_state *s) { struct fnc_view *timeline_view; @@ -7743,34 +6899,30 @@ s->first_entry_onscreen = te; te = get_tree_entry(s->tree, te->idx - 1); } } -static int -tree_scroll_down(struct fnc_view *view, int maxscroll) +static void +tree_scroll_down(struct fnc_tree_view_state *s, int maxscroll) { - struct fnc_tree_view_state *s = &view->state.tree; - struct fnc_tree_entry *next, *last; - int n = 0; + struct fnc_tree_entry *next, *last; + int n = 0; if (s->first_entry_onscreen) next = get_tree_entry(s->tree, s->first_entry_onscreen->idx + 1); else next = &s->tree->entries[0]; last = s->last_entry_onscreen; - while (next && n++ < maxscroll) { - if (last) - last = get_tree_entry(s->tree, last->idx + 1); - if (last || (view->mode == VIEW_SPLIT_HRZN && next)) { + while (next && last && n++ < maxscroll) { + last = get_tree_entry(s->tree, last->idx + 1); + if (last) { s->first_entry_onscreen = next; next = get_tree_entry(s->tree, next->idx + 1); } } - - return FSL_RC_OK; } static int visit_subtree(struct fnc_tree_view_state *s, struct fnc_tree_object *subtree) { @@ -7791,11 +6943,11 @@ return 0; } static int -blame_tree_entry(struct fnc_view **new_view, int start_col, int start_ln, +blame_tree_entry(struct fnc_view **new_view, int start_col, struct fnc_tree_entry *te, struct fnc_parent_trees *parents, fsl_uuid_str commit_id) { struct fnc_view *blame_view; char *path; @@ -7805,11 +6957,11 @@ rc = tree_entry_path(&path, parents, te); if (rc) return rc; - blame_view = view_open(0, 0, start_ln, start_col, FNC_VIEW_BLAME); + blame_view = view_open(0, 0, 0, start_col, FNC_VIEW_BLAME); if (blame_view == NULL) { rc = RC(FSL_RC_ERROR, "%s", "view_open"); goto end; } @@ -7821,47 +6973,46 @@ end: fsl_free(path); return rc; } -static void -tree_grep_init(struct fnc_view *view) +static int +tree_search_init(struct fnc_view *view) { struct fnc_tree_view_state *s = &view->state.tree; s->matched_entry = NULL; + return 0; } static int tree_search_next(struct fnc_view *view) { struct fnc_tree_view_state *s = &view->state.tree; struct fnc_tree_entry *te = NULL; - int rc = FSL_RC_OK; + int rc = 0; if (view->searching == SEARCH_DONE) { view->search_status = SEARCH_CONTINUE; return rc; } if (s->matched_entry) { if (view->searching == SEARCH_FORWARD) { if (s->selected_entry) - te = get_tree_entry(s->tree, - s->selected_entry->idx + 1); + te = &s->tree->entries[s->selected_entry->idx + + 1]; else te = &s->tree->entries[0]; } else { if (s->selected_entry == NULL) te = &s->tree->entries[s->tree->nentries - 1]; else - te = get_tree_entry(s->tree, - s->selected_entry->idx - 1); + te = &s->tree->entries[s->selected_entry->idx + - 1]; } } else { - if (s->selected_entry) - te = s->selected_entry; if (view->searching == SEARCH_FORWARD) te = &s->tree->entries[0]; else te = &s->tree->entries[s->tree->nentries - 1]; } @@ -7883,27 +7034,18 @@ s->matched_entry = te; break; } if (view->searching == SEARCH_FORWARD) - te = get_tree_entry(s->tree, te->idx + 1); + te = &s->tree->entries[te->idx + 1]; else - te = get_tree_entry(s->tree, te->idx - 1); + te = &s->tree->entries[te->idx - 1]; } if (s->matched_entry) { - int idx = s->matched_entry->idx; - bool parent = !s->first_entry_onscreen; - - if (idx >= (parent ? 0 : s->first_entry_onscreen->idx) && - idx <= s->last_entry_onscreen->idx) - s->selected_idx = idx - (parent ? - 1 : - s->first_entry_onscreen->idx); - else { - s->first_entry_onscreen = s->matched_entry; - s->selected_idx = 0; - } + s->first_entry_onscreen = s->matched_entry; + s->selected_idx = 0; } return rc; } @@ -8006,74 +7148,68 @@ } static int cmd_config(const fcli_command *argv) { - const char *opt = NULL, *value = NULL; - char *prev, *v; - enum fnc_opt_id setid; - int rc = FSL_RC_OK; -#ifdef __OpenBSD__ - const fsl_cx *const f = fcli_cx(); - fsl_buffer buf = fsl_buffer_empty; - - fsl_file_dirpart(fsl_cx_db_file_repo(f, NULL), -1, &buf, false); - rc = init_unveil(fsl_buffer_cstr(&buf), fsl_cx_ckout_dir_name(f, NULL), - true); - if (rc) - return rc; -#endif + const char *set = NULL, *value = NULL; + int setid, rc = 0; rc = fcli_process_flags(argv->flags); if (rc || (rc = fcli_has_unused_flags(false))) return rc; - opt = fcli_next_arg(true); - if (opt == NULL || fnc_init.lsconf) { + set = fcli_next_arg(true); + if (set == NULL || fnc_init.lsconf) { if (fnc_init.unset) { fnc_init.err = RC(FSL_RC_MISSING_INFO, "%s", "-u|--unset requires "); usage(); /* NOT REACHED */ } - return fnc_conf_lsopt(fnc_init.lsconf ? false : true); + return fnc_conf_ls_settings(fnc_init.lsconf ? false : true); } - setid = fnc_conf_str2enum(opt); - if (!setid) - return RC(FSL_RC_NOT_FOUND, "invalid setting: %s", opt); + setid = fnc_conf_str2enum(set); + if (!setid) /* Presently, the only valid settings are colours. */ + return RC(FSL_RC_NOT_FOUND, "invalid setting: %s", set); value = fcli_next_arg(true); if (value || fnc_init.unset) { if (value && fnc_init.unset) return RC(FSL_RC_MISUSE, "\n--unset or set %s to %s?", - opt, value); - prev = fnc_conf_getopt(setid, true); - rc = fnc_conf_setopt(setid, value, fnc_init.unset); + set, value); + char *prev = fnc_conf_get(setid, true); + rc = fnc_conf_set(setid, value, fnc_init.unset); if (!rc) f_out("%s: %s -> %s (local)", fnc_conf_enum2str(setid), prev ? prev : "default", value ? value : "default"); fsl_free(prev); } else { - v = fnc_conf_getopt(setid, true); + char *v = fnc_conf_get(setid, true); f_out("%s = %s", fnc_conf_enum2str(setid), v ? v : "default"); fsl_free(v); } return rc; } static int -fnc_conf_lsopt(bool all) +fnc_conf_ls_settings(bool all) { + static const char *fnc_settings[] = { + SETTINGS(GEN_STR) + }; + enum settings { + SETTINGS(GEN_ENUM) + }; char *value = NULL; int idx, last = 0; size_t maxlen = 0; for (idx = FNC_START_SETTINGS + 1; idx < FNC_EOF_SETTINGS; ++idx) { - last = (value = fnc_conf_getopt(idx, true)) ? idx : last; - maxlen = MAX(fsl_strlen(fnc_opt_name[idx]), maxlen); + last = (value = fnc_conf_get(idx, true)) ? idx : last; + maxlen = MAX(fsl_strlen(fnc_settings[idx]), maxlen); fsl_free(value); } if (!last && !all) { f_out("No user-defined settings: " @@ -8081,13 +7217,13 @@ fcli_progname()); return 0; } for (idx = FNC_START_SETTINGS + 1; idx < FNC_EOF_SETTINGS; ++idx) { - value = fnc_conf_getopt(idx, true); + value = fnc_conf_get(idx, true); if (value || all) - f_out("%-*s%s%s%c", maxlen + 2, fnc_opt_name[idx], + f_out("%-*s%s%s%c", maxlen + 2, fnc_settings[idx], value ? " = " : "", value ? value : "", all ? (idx + 1 < FNC_EOF_SETTINGS ? '\n' : '\0') : idx < last ? '\n' : '\0'); fsl_free(value); value = NULL; @@ -8094,29 +7230,42 @@ } return 0; } -static enum fnc_opt_id +static int fnc_conf_str2enum(const char *str) { - enum fnc_opt_id idx; + static const char *fnc_settings[] = { + SETTINGS(GEN_STR) + }; + enum settings { + SETTINGS(GEN_ENUM) + }; + int idx; for (idx = FNC_START_SETTINGS + 1; idx < FNC_EOF_SETTINGS; ++idx) - if (!fsl_stricmp(str, fnc_opt_name[idx])) + if (!fsl_stricmp(str, fnc_settings[idx])) return idx; return FNC_START_SETTINGS; } static const char * -fnc_conf_enum2str(enum fnc_opt_id id) +fnc_conf_enum2str(int id) { + static const char *fnc_settings[] = { + SETTINGS(GEN_STR) + }; + enum settings { + SETTINGS(GEN_ENUM) + }; + if (id <= FNC_START_SETTINGS || id >= FNC_EOF_SETTINGS) return NULL; - return fnc_opt_name[id]; + return fnc_settings[id]; } static int view_close_child(struct fnc_view *view) { @@ -8134,26 +7283,16 @@ static void view_set_child(struct fnc_view *view, struct fnc_view *child) { view->child = child; child->parent = view; - - /* - * If the timeline is open and has not yet loaded /all/ commits, cached - * stmts require resetting the commit builder stmt before restepping. - */ - if (view->vid == FNC_VIEW_TIMELINE) { - struct fnc_tl_thread_cx *tcx = &view->state.timeline.thread_cx; - if (tcx && !tcx->eotl) - tcx->reset = true; - } } static int set_colours(struct fnc_colours *s, enum fnc_view_id vid) { - int rc = FSL_RC_OK; + int rc = 0; switch (vid) { case FNC_VIEW_DIFF: { static const char *regexp_diff[] = { "^((checkin|wiki|ticket|technote) " @@ -8225,12 +7364,10 @@ } default: rc = RC(FSL_RC_TYPE, "invalid fnc_view_id: %s", vid); } - init_pair(FNC_COLOUR_HL_SEARCH, init_colour(FNC_COLOUR_HL_SEARCH), -1); - return rc; } static int set_colour_scheme(struct fnc_colours *colours, const int (*pairs)[2], @@ -8262,16 +7399,16 @@ return rc; } static int -init_colour(enum fnc_opt_id id) +init_colour(enum fnc_colour_obj id) { char *val = NULL; int rc = 0; - val = fnc_conf_getopt(id, false); + val = fnc_conf_get(id, false); if (val == NULL) return default_colour(id); if (!fsl_stricmp(val, "black")) @@ -8304,75 +7441,82 @@ * set, search local settings and envvars for id. If found, dynamically allocate * and return a formatted string for pretty printing the current state of id, * which the caller must free. In either case, if not found, return NULL. */ static char * -fnc_conf_getopt(enum fnc_opt_id id, bool ls) +fnc_conf_get(enum fnc_colour_obj id, bool ls) { fsl_cx *const f = fcli_cx(); fsl_db *db = NULL; - char *optval = NULL, *envvar = NULL; + char *colour = NULL, *colour_g = NULL; db = fsl_needs_repo(f); if (!db) { /* Theoretically, this shouldn't happen. */ RC(FSL_RC_DB, "%s", "fsl_needs_repo"); return NULL; } - optval = fsl_db_g_text(db, NULL, + colour = fsl_db_g_text(db, NULL, "SELECT value FROM config WHERE name=%Q", fnc_conf_enum2str(id)); - if (optval == NULL || ls) - envvar = fsl_strdup(getenv(fnc_conf_enum2str(id))); - - if (ls && (optval || envvar)) { - char *showopt = fsl_mprintf("%s%s%s%s%s", - optval ? optval : "", optval ? " (local)" : "", - optval && envvar ? ", " : "", - envvar ? envvar : "", envvar ? " (envvar)" : ""); - fsl_free(optval); - fsl_free(envvar); - optval = showopt; + if (colour == NULL || ls) + colour_g = fsl_strdup(getenv(fnc_conf_enum2str(id))); + + if (ls && (colour || colour_g)) { + char *colour_ls = fsl_mprintf("%s%s%s%s%s", + colour ? colour : "", colour ? " (local)" : "", + colour && colour_g ? ", " : "", + colour_g ? colour_g : "", colour_g ? " (envvar)" : ""); + fsl_free(colour); + fsl_free(colour_g); + colour = colour_ls; } - return ls ? optval : (optval ? optval : envvar); + return ls ? colour : (colour ? colour : colour_g); } static int -default_colour(enum fnc_opt_id id) +default_colour(enum fnc_colour_obj obj) { - switch (id) { - case FNC_COLOUR_COMMIT: - case FNC_COLOUR_DIFF_META: - case FNC_COLOUR_TREE_EXEC: - case FNC_COLOUR_BRANCH_CURRENT: + if (obj == FNC_COLOUR_COMMIT) + return COLOR_GREEN; + if (obj == FNC_COLOUR_USER) + return COLOR_CYAN; + if (obj == FNC_COLOUR_DATE) + return COLOR_YELLOW; + if (obj == FNC_COLOUR_DIFF_META) + return COLOR_GREEN; + if (obj == FNC_COLOUR_DIFF_MINUS) + return COLOR_MAGENTA; + if (obj == FNC_COLOUR_DIFF_PLUS) + return COLOR_CYAN; + if (obj == FNC_COLOUR_DIFF_CHUNK) + return COLOR_YELLOW; + if (obj == FNC_COLOUR_DIFF_TAGS) + return COLOR_MAGENTA; + if (obj == FNC_COLOUR_TREE_LINK) + return COLOR_MAGENTA; + if (obj == FNC_COLOUR_TREE_DIR) + return COLOR_CYAN; + if (obj == FNC_COLOUR_TREE_EXEC) return COLOR_GREEN; - case FNC_COLOUR_USER: - case FNC_COLOUR_DIFF_PLUS: - case FNC_COLOUR_TREE_DIR: - case FNC_COLOUR_BRANCH_OPEN: + if (obj == FNC_COLOUR_BRANCH_OPEN) return COLOR_CYAN; - case FNC_COLOUR_DATE: - case FNC_COLOUR_DIFF_CHUNK: - case FNC_COLOUR_BRANCH_PRIVATE: - return COLOR_YELLOW; - case FNC_COLOUR_DIFF_MINUS: - case FNC_COLOUR_DIFF_TAGS: - case FNC_COLOUR_TREE_LINK: - case FNC_COLOUR_BRANCH_CLOSED: - return COLOR_MAGENTA; - case FNC_COLOUR_HL_SEARCH: - return COLOR_YELLOW; - default: - return -1; /* Terminal default foreground colour. */ - } -} - -static int -fnc_conf_setopt(enum fnc_opt_id id, const char *val, bool unset) + if (obj == FNC_COLOUR_BRANCH_CLOSED) + return COLOR_MAGENTA; + if (obj == FNC_COLOUR_BRANCH_CURRENT) + return COLOR_GREEN; + if (obj == FNC_COLOUR_BRANCH_PRIVATE) + return COLOR_YELLOW; + + return -1; /* Terminal default foreground colour. */ +} + +static int +fnc_conf_set(enum fnc_colour_obj id, const char *val, bool unset) { fsl_cx *const f = fcli_cx(); fsl_db *db = NULL; db = fsl_needs_repo(f); @@ -8457,12 +7601,11 @@ fsl_cx *const f = fcli_cx(); struct fnc_view *view; char *path = NULL; fsl_uuid_str commit_id = NULL; fsl_id_t tip = 0, rid = 0; - long nlimit = 0; - int rc = 0; + int nlimit = 0, rc = 0; rc = fcli_process_flags(argv->flags); if (rc || (rc = fcli_has_unused_flags(false))) goto end; if (!fcli_next_arg(false)) { @@ -8497,15 +7640,12 @@ goto end; } rc = fsl_sym_to_rid(f, fnc_init.sym, FSL_SATYPE_CHECKIN, &rid); if (rc) goto end; - } else if (!fnc_init.sym) { + } else if (!fnc_init.sym) fsl_ckout_version_info(f, &rid, NULL); - if (!rid) /* -R|--repo option used */ - fsl_sym_to_rid(f, "tip", FSL_SATYPE_CHECKIN, &rid); - } rc = map_repo_path(&path); if (rc) { if (rc != FSL_RC_NOT_FOUND || !fnc_init.sym) goto end; @@ -8519,19 +7659,11 @@ rc = rc ? rc : RC(FSL_RC_MISSING_INFO, "%s blame requires versioned file path", fcli_progname()); goto end; } - rc = init_curses(); - if (rc) - goto end; -#ifdef __OpenBSD__ - rc = init_unveil(fsl_cx_db_file_repo(f, NULL), - fsl_cx_ckout_dir_name(f, NULL), false); - if (rc) - goto end; -#endif + init_curses(); view = view_open(0, 0, 0, 0, FNC_VIEW_BLAME); if (view == NULL) { rc = RC(FSL_RC_ERROR, "%s", view_open); goto end; @@ -8587,12 +7719,12 @@ } view->show = show_blame_view; view->input = blame_input_handler; view->close = close_blame_view; - view->grep_init = blame_grep_init; - view->grep = find_next_match; + view->search_init = blame_search_init; + view->search_next = blame_search_next; return run_blame(view); } static int @@ -8629,14 +7761,10 @@ goto end; } rc = fsl_card_F_content(f, cf, &buf); if (rc) goto end; - if (fsl_looks_like_binary(&buf)) { - rc = RC(FSL_RC_DIFF_BINARY, "%s", "cannot blame binary file"); - goto end; - } /* * We load f with the actual file content to map line offsets so we * accurately find tokens when running a search. */ @@ -8716,12 +7844,11 @@ if (s->first_line_onscreen + view->nlines - 1 > blame->nlines) { s->first_line_onscreen = 1; s->last_line_onscreen = view->nlines; s->selected_line = 1; } - s->matched_line = 0; - s->maxx = &blame->thread_cx.cb_cx->maxlen; + end: fsl_free(master); fsl_free(root); fsl_deck_finalize(&d); fsl_buffer_clear(&buf); @@ -8752,12 +7879,12 @@ if (nlines) *nlines = 0; len = buf->used; if (len == 0) - return rc; /* empty file */ - + return RC(FSL_RC_SIZE_MISMATCH, "%s", + "fnc_dump_buffer_to_file"); if (nlines) { if (line_offsets && *line_offsets == NULL) { *nlines = 1; nalloc = alloc_chunksz; *line_offsets = calloc(nalloc, sizeof(**line_offsets)); @@ -8847,11 +7974,11 @@ if (s->blame_complete) cbreak(); /* Return to blocking mode. */ rc = draw_blame(view); - drawborder(view); + draw_vborder(view); return rc; } static void * @@ -8922,12 +8049,10 @@ if (opt->originRid && !line->id) { line->id = fsl_strdup(cx->root_commit); line->annotated = true; } - line->lineno = step->lineNumber; - cx->maxlen = MAX(step->lineLength, cx->maxlen); ++cx->nlines; end: rc = pthread_mutex_unlock(&fnc_mutex); if (rc) rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS), @@ -8943,29 +8068,32 @@ struct fnc_blame_line *blame_line; regmatch_t *regmatch = &view->regmatch; struct fnc_colour *c = NULL; wchar_t *wcstr; char *line = NULL; - fsl_uuid_str prev_id = NULL; + fsl_uuid_str prev_id = NULL, id_str = NULL; ssize_t linelen; size_t linesz = 0; int width, lineno = 0, nprinted = 0; - int rc = FSL_RC_OK; - int npad = 0; + int rc = 0; const int idfield = 11; /* Prefix + space. */ - bool selected; + + id_str = fsl_strdup(s->blamed_commit->id); + if (id_str == NULL) + return RC(FSL_RC_ERROR, "%s", "fsl_strdup"); rewind(blame->f); werase(view->window); - if ((line = fsl_mprintf("checkin %s", s->blamed_commit->id)) == NULL) { + if ((line = fsl_mprintf("checkin %s", id_str)) == NULL) { rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "fsl_mprintf"); + fsl_free(id_str); return rc; } - rc = formatln(&wcstr, &width, line, view->ncols, 0, 0, false); + rc = formatln(&wcstr, &width, line, view->ncols, 0); fsl_free(line); line = NULL; if (rc) return rc; if (screen_is_shared(view)) @@ -8986,18 +8114,19 @@ fsl_free(wcstr); wcstr = NULL; if (width < view->ncols - 1) waddch(view->window, '\n'); - line = fsl_mprintf("[%d/%d] %s%s%s %c", s->gtl ? s->gtl : - MIN(blame->nlines, s->first_line_onscreen - 1 + s->selected_line), - blame->nlines, s->blame_complete ? "" : "annotating... ", + line = fsl_mprintf("[%d/%d] %s%s%s %c", + s->first_line_onscreen - 1 + s->selected_line, blame->nlines, + s->blame_complete ? "" : "annotating... ", fnc_init.sym ? "/" : "", s->path, s->blame_complete ? ' ' : SPINNER[s->spin_idx]); if (SPINNER[++s->spin_idx] == '\0') s->spin_idx = 0; - rc = formatln(&wcstr, &width, line, view->ncols, 0, 0, false); + fsl_free(id_str); + rc = formatln(&wcstr, &width, line, view->ncols, 0); fsl_free(line); line = NULL; if (rc) return rc; waddwstr(view->window, wcstr); @@ -9006,11 +8135,10 @@ if (width < view->ncols - 1) waddch(view->window, '\n'); s->eof = false; while (nprinted < view->nlines - 2) { - attr_t rx = 0; linelen = getline(&line, &linesz, blame->f); if (linelen == -1) { if (feof(blame->f)) { s->eof = true; break; @@ -9019,24 +8147,20 @@ return RC(ferror(blame->f) ? fsl_errno_to_rc(errno, FSL_RC_IO) : FSL_RC_IO, "%s", "getline"); } if (++lineno < s->first_line_onscreen) continue; - if (s->gtl) - if (!gotoline(view, &lineno, &nprinted)) - continue; - - if ((selected = nprinted == s->selected_line - 1)) { - rx = A_BOLD | A_REVERSE; - wattron(view->window, rx); - } + + if (view->active && nprinted == s->selected_line - 1) + wattr_on(view->window, A_REVERSE, NULL); if (blame->nlines > 0) { blame_line = &blame->lines[lineno - 1]; if (blame_line->annotated && prev_id && - !fsl_uuidcmp(prev_id, blame_line->id) && - !selected) { + fsl_uuidcmp(prev_id, blame_line->id) == 0 && + !(view->active && + nprinted == s->selected_line - 1)) { waddstr(view->window, " "); } else if (blame_line->annotated) { char *id_str; id_str = fsl_strndup(blame_line->id, idfield - 1); @@ -9060,21 +8184,18 @@ prev_id = blame_line->id; } else { waddstr(view->window, ".........."); prev_id = NULL; } - if (s->showln) - npad = draw_lineno(view, blame->nlines, - blame_line->lineno, rx); } else { waddstr(view->window, ".........."); prev_id = NULL; } - if (selected) - wattroff(view->window, rx); - waddch(view->window, ' '); + if (view->active && nprinted == s->selected_line - 1) + wattr_off(view->window, A_REVERSE, NULL); + waddstr(view->window, " "); if (view->ncols <= idfield) { width = idfield; wcstr = wcsdup(L""); if (wcstr == NULL) { @@ -9084,129 +8205,48 @@ return rc; } } else if (s->first_line_onscreen + nprinted == s->matched_line && regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) { - rc = draw_matched_line(view, &width, idfield + npad, - regmatch, 0); + rc = write_matched_line(&width, line, + view->ncols - idfield, idfield, + view->window, regmatch); if (rc) { fsl_free(line); return rc; } width += idfield; } else { rc = formatln(&wcstr, &width, line, - view->ncols - idfield - npad, idfield + npad, - view->pos.col, true); + view->ncols - idfield, idfield); waddwstr(view->window, wcstr); fsl_free(wcstr); wcstr = NULL; width += idfield; } - if (width + npad <= view->ncols - 1) + if (width <= view->ncols - 1) waddch(view->window, '\n'); if (++nprinted == 1) s->first_line_onscreen = lineno; } fsl_free(line); s->last_line_onscreen = lineno; - drawborder(view); + draw_vborder(view); return rc; } -/* - * Draw column of line numbers up to nlines for the given view. - */ -static int -draw_lineno(struct fnc_view *view, int nlines, int lineno, attr_t rx) -{ - int npad = 0; - - ndigits(npad, nlines); /* Number of digits to pad. */ - - wattron(view->window, rx | A_BOLD); - wprintw(view->window, " %*d ", npad, lineno); - if (view->vid == FNC_VIEW_BLAME) /* Don't highlight separator. */ - wattroff(view->window, A_REVERSE); - waddch(view->window, (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) ? - ACS_VLINE : '|'); - wattroff(view->window, rx | A_BOLD); - - npad += 3; /* {ap,pre}pended ' ' + line separator */ - - return npad; -} - -static bool -gotoline(struct fnc_view *view, int *lineno, int *nprinted) -{ - FILE *f = NULL; - int *first, *selected, *gtl; - bool *eof; - - if (view->vid == FNC_VIEW_BLAME) { - struct fnc_blame_view_state *s = &view->state.blame; - first = &s->first_line_onscreen; - selected = &s->selected_line; - gtl = &s->gtl; - eof = &s->eof; - f = s->blame.f; - } else if (view->vid == FNC_VIEW_DIFF) { - struct fnc_diff_view_state *s = &view->state.diff; - first = &s->first_line_onscreen; - selected = &s->selected_line; - gtl = &s->gtl; - eof = &s->eof; - f = s->f; - } else - return false; - - if (*first != 1 && (*lineno >= *gtl - (view->nlines - 3) / 2)) { - rewind(f); - *nprinted = 0; - *eof = false; - *first = 1; - *lineno = 0; - return false; - } - if (*lineno < *gtl - (view->nlines - 3) / 2) - return false; - - *selected = *gtl <= (view->nlines - 3) / 2 ? - *gtl : (view->nlines - 3) / 2 + 1; - *gtl = 0; - - return true; -} - static int blame_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch) { struct fnc_view *branch_view, *diff_view; struct fnc_blame_view_state *s = &view->state.blame; - int start_col = 0, rc = FSL_RC_OK; - uint16_t nscroll = view->nlines - 2; + int start_col = 0, rc = 0; switch (ch) { - case '0': - view->pos.col = 0; - break; - case '$': - view->pos.col = *s->maxx - view->ncols / 2; - break; - case KEY_RIGHT: - case 'l': - if ((size_t)view->pos.col + view->ncols / 2 < *s->maxx) - view->pos.col += 2; - break; - case KEY_LEFT: - case 'h': - view->pos.col -= MIN(view->pos.col, 2); - break; case 'q': s->done = true; if (s->selected_commit) fnc_commit_artifact_close(s->selected_commit); break; @@ -9229,70 +8269,37 @@ s->selected_line = view->nlines - 2; s->first_line_onscreen = s->blame.nlines - (view->nlines - 3); } break; + case KEY_UP: + case 'k': + if (s->selected_line > 1) + --s->selected_line; + else if (s->selected_line == 1 && s->first_line_onscreen > 1) + --s->first_line_onscreen; + break; + case KEY_PPAGE: + case CTRL('b'): + if (s->first_line_onscreen == 1) { + s->selected_line = 1; + break; + } + if (s->first_line_onscreen > view->nlines - 2) + s->first_line_onscreen -= (view->nlines - 2); + else + s->first_line_onscreen = 1; + break; case KEY_DOWN: case 'j': if (s->selected_line < view->nlines - 2 && s->first_line_onscreen + s->selected_line <= s->blame.nlines) ++s->selected_line; else if (s->last_line_onscreen < s->blame.nlines) ++s->first_line_onscreen; break; - case KEY_UP: - case 'k': - if (s->selected_line > 1) - --s->selected_line; - else if (s->selected_line == 1 && s->first_line_onscreen > 1) - --s->first_line_onscreen; - break; - case CTRL('d'): - nscroll >>= 1; - /* FALL THROUGH */ - case KEY_NPAGE: - case CTRL('f'): - case ' ': - if (s->last_line_onscreen >= s->blame.nlines) { - if (s->selected_line >= MIN(s->blame.nlines, - view->nlines - 2)) - break; - s->selected_line += MIN(nscroll, s->last_line_onscreen - - s->first_line_onscreen - s->selected_line + 1); - break; - } - if (s->last_line_onscreen + nscroll <= s->blame.nlines) - s->first_line_onscreen += nscroll; - else - s->first_line_onscreen = - s->blame.nlines - (view->nlines - 3); - break; - case CTRL('u'): - nscroll >>= 1; - /* FALL THROUGH */ - case KEY_PPAGE: - case CTRL('b'): - if (s->first_line_onscreen == 1) { - s->selected_line = MAX(1, s->selected_line - nscroll); - break; - } - if (s->first_line_onscreen > nscroll) - s->first_line_onscreen -= nscroll; - else - s->first_line_onscreen = 1; - break; - case 'L': { - struct input input = {(int []){1, s->blame.nlines}, "line: ", - INPUT_NUMERIC, true}; - rc = fnc_prompt_input(view, &input); - s->gtl = input.ret; - break; - } - case '#': - s->showln = !s->showln; - break; case 'b': case 'p': { fsl_uuid_cstr id = NULL; id = get_selected_commit_id(s->blame.lines, s->blame.nlines, s->first_line_onscreen, s->selected_line); @@ -9326,11 +8333,18 @@ char *m = fsl_mprintf("-- %s not in [%.12s] --", s->path + (fnc_init.sym ? 0 : 1), pid); if (m == NULL) rc = RC(FSL_RC_ERROR, "%s", "fsl_mprintf"); - fnc_print_msg(view, m, true, true, true); + wattr_on(view->window, A_BOLD, NULL); + mvwaddstr(view->window, + view->start_ln + view->nlines - 1, 0, m); + wclrtoeol(view->window); + wattr_off(view->window, A_BOLD, NULL); + update_panels(); + doupdate(); + sleep(1); fsl_deck_finalize(&d); fsl_free(pid); fsl_free(m); break; } @@ -9427,11 +8441,11 @@ if (diff_view == NULL) { fnc_commit_artifact_close(commit); rc = RC(FSL_RC_ERROR, "%s", "view_open"); break; } - rc = open_diff_view(diff_view, commit, DEF_DIFF_CTX, + rc = open_diff_view(diff_view, commit, DIFF_DEF_CTXT, fnc_init.ws, fnc_init.invert, !fnc_init.quiet, NULL, true, NULL); s->selected_commit = commit; if (rc) { fnc_commit_artifact_close(commit); @@ -9450,10 +8464,28 @@ *new_view = diff_view; if (rc) break; break; } + case KEY_NPAGE: + case CTRL('f'): + case ' ': + if (s->last_line_onscreen >= s->blame.nlines && s->selected_line + >= MIN(s->blame.nlines, view->nlines - 2)) + break; + if (s->last_line_onscreen >= s->blame.nlines && + s->selected_line < view->nlines - 2) { + s->selected_line = MIN(s->blame.nlines, + view->nlines - 2); + break; + } + if (s->last_line_onscreen + view->nlines - 2 <= s->blame.nlines) + s->first_line_onscreen += view->nlines - 2; + else + s->first_line_onscreen = + s->blame.nlines - (view->nlines - 3); + break; case KEY_RESIZE: if (s->selected_line > view->nlines - 2) { s->selected_line = MIN(s->blame.nlines, view->nlines - 2); } @@ -9462,16 +8494,86 @@ break; } return rc; } -static void -blame_grep_init(struct fnc_view *view) +static int +blame_search_init(struct fnc_view *view) { struct fnc_blame_view_state *s = &view->state.blame; s->matched_line = 0; + return 0; +} + +static int +blame_search_next(struct fnc_view *view) +{ + struct fnc_blame_view_state *s = &view->state.blame; + char *line = NULL; + ssize_t linelen; + size_t linesz = 0; + int lineno; + + if (view->searching == SEARCH_DONE) { + view->search_status = SEARCH_CONTINUE; + return 0; + } + + if (s->matched_line) { + if (view->searching == SEARCH_FORWARD) + lineno = s->matched_line + 1; + else + lineno = s->matched_line - 1; + } else { + if (view->searching == SEARCH_FORWARD) + lineno = 1; + else + lineno = s->blame.nlines; + } + + while (1) { + off_t offset; + + if (lineno <= 0 || lineno > s->blame.nlines) { + if (s->matched_line == 0) { + view->search_status = SEARCH_CONTINUE; + break; + } + + if (view->searching == SEARCH_FORWARD) + lineno = 1; + else + lineno = s->blame.nlines; + } + + offset = s->blame.line_offsets[lineno - 1]; + if (fseeko(s->blame.f, offset, SEEK_SET) != 0) { + fsl_free(line); + return RC(fsl_errno_to_rc(errno, FSL_RC_IO), + "%s", "fseeko"); + } + linelen = getline(&line, &linesz, s->blame.f); + if (linelen != -1 && regexec(&view->regex, line, 1, + &view->regmatch, 0) == 0) { + view->search_status = SEARCH_CONTINUE; + s->matched_line = lineno; + break; + } + if (view->searching == SEARCH_FORWARD) + ++lineno; + else + --lineno; + } + fsl_free(line); + + if (s->matched_line) { + s->first_line_onscreen = s->matched_line; + s->selected_line = 1; + } + + return 0; } static fsl_uuid_cstr get_selected_commit_id(struct fnc_blame_line *lines, int nlines, int first_line_onscreen, int selected_line) @@ -9530,11 +8632,11 @@ stop_blame(struct fnc_blame *blame) { int idx, rc = 0; if (blame->thread_id) { - intptr_t retval; + int retval; rc = pthread_mutex_unlock(&fnc_mutex); if (rc) return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS), "%s", "pthread_mutex_unlock"); rc = pthread_join(blame->thread_id, (void **)&retval); @@ -9648,31 +8750,26 @@ if (rc) return rc; } glob = fsl_strdup(fcli_next_arg(true)); - rc = init_curses(); - if (rc) - goto end; -#ifdef __OpenBSD__ - const fsl_cx *const f = fcli_cx(); - rc = init_unveil(fsl_cx_db_file_repo(f, NULL), - fsl_cx_ckout_dir_name(f, NULL), false); - if (rc) - goto end; -#endif + init_curses(); view = view_open(0, 0, 0, 0, FNC_VIEW_BRANCH); if (view == NULL) { rc = RC(FSL_RC_ERROR, "%s", "view_open"); goto end; } rc = open_branch_view(view, branch_flags, glob, dateline, when); - if (!rc) - rc = view_loop(view); + if (rc) + goto end; + + rc = view_loop(view); end: + if (rc) + fnc_free_branches(&view->state.branch.branches); fsl_free(glob); return rc; } static int @@ -9689,25 +8786,23 @@ s->dateline = dateline; s->when = when; rc = fnc_load_branches(s); if (rc) - goto end; + return rc; if (s->colour) { STAILQ_INIT(&s->colours); rc = set_colours(&s->colours, FNC_VIEW_BRANCH); } view->show = show_branch_view; view->input = branch_input_handler; view->close = close_branch_view; - view->grep_init = branch_grep_init; - view->grep = branch_search_next; -end: - if (rc) - fnc_free_branches(&s->branches); + view->search_init = branch_search_init; + view->search_next = branch_search_next; + return rc; } static int fnc_load_branches(struct fnc_branch_view_state *s) @@ -9745,17 +8840,13 @@ } if (rc) goto end; if (s->branch_glob) { - char *op = NULL, *str = NULL; - rc = fnc_make_sql_glob(&op, &str, s->branch_glob, - !fnc_str_has_upper(s->branch_glob)); - if (!rc) - fsl_buffer_appendf(&sql, " AND name %q %Q", op, str); - fsl_free(op); - fsl_free(str); + char *like = fsl_mprintf("%%%%%s%%%%", s->branch_glob); + rc = fsl_buffer_appendf(&sql, " AND name LIKE %Q", like); + fsl_free(like); if (rc) goto end; } if (FLAG_CHK(s->branch_flags, BRANCH_LS_NO_PRIVATE)) { @@ -9824,11 +8915,11 @@ static int create_tmp_branchlist_table(void) { fsl_cx *const f = fcli_cx(); - fsl_db *db = fsl_needs_repo(f); /* -R|--repo option */ + fsl_db *db = fsl_needs_ckout(f); static const char tmp_branchlist_table[] = "CREATE TEMP TABLE IF NOT EXISTS tmp_brlist AS " "SELECT tagxref.value AS name," " max(event.mtime) AS mtime," " EXISTS(SELECT 1 FROM tagxref AS tx WHERE tx.rid=tagxref.rid" @@ -9850,11 +8941,11 @@ " AND event.objid=tagxref.rid " "GROUP BY 1;"; int rc = 0; if (!db) - return RC(FSL_RC_NOT_A_CKOUT, "%s", "fsl_needs_repo"); + return RC(FSL_RC_NOT_A_CKOUT, "%s", "fsl_needs_ckout"); rc = fsl_db_exec(db, tmp_branchlist_table); return rc ? RC(fsl_cx_uplift_db_error2(f, db, rc), "%s", "fsl_db_exec") : rc; } @@ -9960,11 +9051,11 @@ if ((line = fsl_mprintf("branches [%d/%d]", be->idx + s->selected + 1, s->nbranches)) == NULL) return RC(FSL_RC_ERROR, "%s", "fsl_mprintf"); - rc = formatln(&wline, &width, line, view->ncols, 0, 0, false); + rc = formatln(&wline, &width, line, view->ncols, 0); if (rc) { fsl_free(line); return rc; } if (screen_is_shared(view)) @@ -10000,11 +9091,11 @@ return RC(FSL_RC_ERROR, "%s", "fsl_mprintf"); if (s->colour) c = match_colour(&s->colours, line); - rc = formatln(&wline, &width, line, view->ncols, 0, 0, false); + rc = formatln(&wline, &width, line, view->ncols, 0); if (rc) { fsl_free(line); return rc; } @@ -10031,22 +9122,21 @@ --limit; s->last_branch_onscreen = be; be = TAILQ_NEXT(be, entries); } - drawborder(view); + draw_vborder(view); return rc; } static int branch_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch) { struct fnc_branch_view_state *s = &view->state.branch; - struct fnc_view *tree_view; + struct fnc_view *timeline_view, *tree_view; struct fnc_branchlist_entry *be; - int start_col = 0, n, rc = FSL_RC_OK; - uint16_t nscroll = view->nlines - 1; + int start_col = 0, n, rc = 0; switch (ch) { case 'c': s->colour = !s->colour; break; @@ -10059,26 +9149,24 @@ case KEY_ENTER: case '\r': case ' ': if (!s->selected_branch) break; - rc = request_view(new_view, view, FNC_VIEW_TIMELINE); - break; - case 's': - /* - * Toggle branch list sort order (cf. branch --sort option): - * lexicographical (default) -> most recently used -> state - */ - if (FLAG_CHK(s->branch_flags, BRANCH_SORT_MTIME)) { - FLAG_CLR(s->branch_flags, BRANCH_SORT_MTIME); - FLAG_SET(s->branch_flags, BRANCH_SORT_STATUS); - } else if (FLAG_CHK(s->branch_flags, BRANCH_SORT_STATUS)) - FLAG_CLR(s->branch_flags, BRANCH_SORT_STATUS); - else - FLAG_SET(s->branch_flags, BRANCH_SORT_MTIME); - fnc_free_branches(&s->branches); - rc = fnc_load_branches(s); + if (view_is_parent(view)) + start_col = view_split_start_col(view->start_col); + rc = tl_branch_entry(&timeline_view, start_col, + s->selected_branch); + view->active = false; + timeline_view->active = true; + if (view_is_parent(view)) { + rc = view_close_child(view); + if (rc) + return rc; + view_set_child(view, timeline_view); + view->focus_child = true; + } else + *new_view = timeline_view; break; case 't': if (!s->selected_branch) break; if (view_is_parent(view)) @@ -10134,34 +9222,27 @@ break; } if (TAILQ_NEXT(s->last_branch_onscreen, entries) == NULL) /* Reached last entry. */ break; - branch_scroll_down(view, 1); + branch_scroll_down(s, 1); break; - case CTRL('u'): - nscroll >>= 1; - /* FALL THROUGH */ case KEY_PPAGE: case CTRL('b'): if (s->first_branch_onscreen == TAILQ_FIRST(&s->branches)) - s->selected -= MIN(nscroll, s->selected); - branch_scroll_up(s, nscroll); + s->selected = 0; + branch_scroll_up(s, MAX(0, view->nlines - 1)); break; - case CTRL('d'): - nscroll >>= 1; - /* FALL THROUGH */ case KEY_NPAGE: case CTRL('f'): if (TAILQ_NEXT(s->last_branch_onscreen, entries) == NULL) { /* No more entries off-page; move cursor down. */ if (s->selected < s->ndisplayed - 1) - s->selected += MIN(nscroll, - s->ndisplayed - s->selected - 1); + s->selected = s->ndisplayed - 1; break; } - branch_scroll_down(view, nscroll); + branch_scroll_down(s, view->nlines - 1); break; case CTRL('l'): case 'R': fnc_free_branches(&s->branches); s->branch_glob = NULL; /* Shared pointer. */ @@ -10177,10 +9258,34 @@ break; } return rc; } + +static int +tl_branch_entry(struct fnc_view **new_view, int start_col, + struct fnc_branchlist_entry *be) +{ + struct fnc_view *timeline_view; + fsl_id_t rid; + int rc = 0; + + *new_view = NULL; + + rid = fsl_uuid_to_rid(fcli_cx(), be->branch->id); + if (rid < 0) + return RC(rc, "%s", "fsl_uuid_to_rid"); + + timeline_view = view_open(0, 0, 0, start_col, FNC_VIEW_TIMELINE); + if (timeline_view == NULL) + return RC(FSL_RC_ERROR, "%s", "view_open"); + + rc = open_timeline_view(timeline_view, rid, "/", NULL); + if (!rc) + *new_view = timeline_view; + return rc; +} static int browse_branch_tree(struct fnc_view **new_view, int start_col, struct fnc_branchlist_entry *be) { @@ -10220,14 +9325,13 @@ s->first_branch_onscreen = be; be = TAILQ_PREV(be, fnc_branchlist_head, entries); } } -static int -branch_scroll_down(struct fnc_view *view, int maxscroll) +static void +branch_scroll_down(struct fnc_branch_view_state *s, int maxscroll) { - struct fnc_branch_view_state *s = &view->state.branch; struct fnc_branchlist_entry *next, *last; int idx = 0; if (s->first_branch_onscreen) next = TAILQ_NEXT(s->first_branch_onscreen, entries); @@ -10240,20 +9344,19 @@ if (last) { s->first_branch_onscreen = next; next = TAILQ_NEXT(next, entries); } } - - return FSL_RC_OK; } -static void -branch_grep_init(struct fnc_view *view) +static int +branch_search_init(struct fnc_view *view) { struct fnc_branch_view_state *s = &view->state.branch; s->matched_branch = NULL; + return 0; } static int branch_search_next(struct fnc_view *view) { @@ -10311,21 +9414,15 @@ else be = TAILQ_PREV(be, fnc_branchlist_head, entries); } if (s->matched_branch) { - int idx = s->matched_branch->idx; - if (idx >= s->first_branch_onscreen->idx && - idx <= s->last_branch_onscreen->idx) - s->selected = idx - s->first_branch_onscreen->idx; - else { - s->first_branch_onscreen = s->matched_branch; - s->selected = 0; - } + s->first_branch_onscreen = s->matched_branch; + s->selected = 0; } - return FSL_RC_OK; + return 0; } static int match_branchlist_entry(struct fnc_branchlist_entry *be, regex_t *regex) { @@ -10482,11 +9579,11 @@ { printf("%s %s\n", fcli_progname(), PRINT_VERSION); } static int -strtonumcheck(long *ret, const char *nstr, const int min, const int max) +strtonumcheck(int *ret, const char *nstr, const int min, const int max) { const char *ptr; int n; ptr = NULL; @@ -10502,78 +9599,11 @@ else if (ptr && *ptr != '\0') return RC(FSL_RC_MISUSE, "invalid char in : -n|--limit=%s [%s]", nstr, ptr); *ret = n; - return FSL_RC_OK; -} - -static int -fnc_prompt_input(struct fnc_view *view, struct input *input) -{ - int rc = FSL_RC_OK; - - if (input->prompt) - fnc_print_msg(view, input->prompt, input->clear, false, false); - - rc = cook_input(input->buf, sizeof(input->buf), view->window); - if (rc || !input->buf[0]) - return rc; - - if (input->type == INPUT_NUMERIC) { - long n = 0; - int min = INT_MIN, max = INT_MAX; - if (input->data) { - min = *(int *)input->data; - max = ((int *)input->data)[1]; - } - rc = strtonumcheck(&n, input->buf, min, max); - if (rc == FSL_RC_MISUSE) - fnc_print_msg(view, "-- numeric input only --", - true, true, true); - else if (rc == FSL_RC_RANGE || n < min || n > max) - fnc_print_msg(view, "-- line outside file range --", - true, true, true); - else - input->ret = n; - rc = FSL_RC_OK; - fcli_err_reset(); - } - - return rc; -} - -static int -cook_input(char *ret, int sz, WINDOW *win) -{ - int rc; - - nocbreak(); - echo(); - rc = wgetnstr(win, ret, sz); - cbreak(); - noecho(); - raw(); - - return rc == ERR ? FSL_RC_ERROR : FSL_RC_OK; -} - -static void -fnc_print_msg(struct fnc_view *view, const char *msg, bool clear, bool update, - bool zzz) -{ - wattr_on(view->window, A_BOLD, NULL); - mvwaddstr(view->window, view->nlines - 1, 0, msg); - if (clear) - wclrtoeol(view->window); - wattr_off(view->window, A_BOLD, NULL); - if (update) { - update_panels(); - doupdate(); - } - if (zzz) - sleep(1); + return 0; } /* * Attempt to parse string d, which must resemble either an ISO8601 formatted * date (e.g., 2021-10-10, 2020-01-01T10:10:10), disgregarding any trailing @@ -10633,83 +9663,5 @@ *ptr = NULL; return s; } -static bool -fnc_str_has_upper(const char *str) -{ - int idx; - - for (idx = 0; str[idx]; ++idx) - if (fsl_isupper(str[idx])) - return true; - - return false; -} - -/* - * If fold is true, construct a pairing for SQL queries using the SQLite LIKE - * operator to fold case with dynamically allocated strings such that: - * *op = "LIKE" - * *glob = "%%%%str%%%%" - * Otherwise, construct a case-sensitive pairing: - * *op = "GLOB" - * *glob = "*str*" - * Both *op and *glob must be disposed of by the caller. Return non-zero on - * allocation failure, else return zero. - */ -static int -fnc_make_sql_glob(char **op, char **glob, const char *str, bool fold) -{ - if (fold) { - *op = fsl_strdup("LIKE"); - if (*op == NULL) - return RC(FSL_RC_ERROR, "%s", "fsl_strdup"); - *glob = fsl_mprintf("%%%%%s%%%%", str); - if (*glob == NULL) - return RC(FSL_RC_ERROR, "%s", "fsl_mprintf"); - } else { - *op = fsl_strdup("GLOB"); - if (*op == NULL) - return RC(FSL_RC_ERROR, "%s", "fsl_strdup"); - *glob = fsl_mprintf("*%s*", str); - if (*glob == NULL) - return RC(FSL_RC_ERROR, "%s", "fsl_mprintf"); - } - - return 0; -} - -#ifdef __OpenBSD__ -/* - * Read permissions for the below unveil() calls are self-evident; we need - * to read the repository and ckout databases, and ckout dir for most all fnc - * operations. Write and create permissions are briefly listed inline, but we - * effectively veil the entire fs except the repo db, ckout dir, and /tmp. - */ -static int -init_unveil(const char *repodb, const char *ckoutdir, bool cfg) -{ - /* w repo db for 'fnc config' command: fnc_conf_setopt(). */ - if (unveil(repodb, cfg ? "rwc" : "rw") == -1) - return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), - "unveil(%s, \"rw\")", repodb); - - /* w .fslckout for fsl_ckout_changes_scan() in cmd_diff(). */ - if (unveil(ckoutdir, "rw") == -1) - return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), - "unveil(%s, \"rw\")", ckoutdir); - - /* rwc /tmp for tmpfile() in help(), create_diff(), and run_blame(). */ - if (unveil(P_tmpdir, "rwc") == -1) - return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), - "unveil(%s, \"rwc\")", P_tmpdir); - - if (unveil(NULL, NULL) == -1) - return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), - "%s", "unveil"); - - return FSL_RC_OK; -} -#endif -