Login
Changes On Branch cx-db-handle-reorg
Login

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

Changes In Branch cx-db-handle-reorg Excluding Merge-Ins

This is equivalent to a diff from 9626c2acf6 to a67b757dc0

2021-12-31
21:33
f-merge now defaults to wet-run mode. check-in: f3a4ba9472 user: stephan tags: trunk
21:30
Extended fsl__cx_attach_role() to be able to create a new db if needed (required for fsl_repo_create()) but (regardless of this change) discovered that ATTACH, when run through the new fsl_cx::dbMain handle, can no longer create new db files, which means that f-open cannot create a checkout. COMPLETELY stumped as to why that is. Edit: closing because this branch is failing in inexplicable ways and has a horrid mix of branch-relevant and branch-irrelevant changes. Pulling in the branch-irrelevant ones separately into trunk before taking another whack at the branch-relevant ones. Closed-Leaf check-in: a67b757dc0 user: stephan tags: cx-db-handle-reorg
21:26
Corrected recently-broken Makefile.in references in f-test-ciwoco. check-in: 6e8b5b6677 user: stephan tags: cx-db-handle-reorg
15:57
Reorganized fsl_cx-internal DB handles, eliminating the in-memory/temp main db and (once again) using the first of the repo/checkout which is opened as the main db. Seems to work okay but some fallout would not be terribly surprising. (Edit: moving back to cx-db-handle-reorg because of new, inexplicable inability to create checkout db via ATTACH.) check-in: 46656edc7e user: stephan tags: cx-db-handle-reorg
13:47
fsl_buffer_external() may now be passed a populated buffer, clearing it before re-initializing it. check-in: 9626c2acf6 user: stephan tags: trunk
2021-12-30
13:52
Removed some debug output added by the previous checkin. check-in: 75eab853b5 user: stephan tags: trunk

Deleted bindings/Makefile.in.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/make # help out emacs
all:
DISTCLEAN_FILES += Makefile
SUBDIRS :=
# Subdir cleanup rules and deps list must come before shakenmake.make is included
# or they must be set up manually afterwards...
ifneq (,$(CXX))
clean-.: clean-cpp
distclean-.: distclean-cpp
SUBDIRS += cpp
all: subdir-cpp
endif

clean-.: clean-s2
distclean-.: distclean-s2
include ../subdir-inc.make
SUBDIRS += s2
$(eval $(call ShakeNMake.CALL.SUBDIRS,$(SUBDIRS)))
all: subdir-s2
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































Changes to bindings/s2/shell_extend.c.
96
97
98
99
100
101
102
103

104
105


106
107
108
109
110
111
112






113
114
115
116
117
118
119
    fsl_cx_err_reset(f);
  }
  va_end(vargs);
  return rc;
}

static int cb_toss_fsl( cwal_callback_args const * args,
                        fsl_cx * f ){

  int rc;
  assert(f && f->error.code);


  rc = (FSL_RC_OOM==f->error.code)
    ? CWAL_RC_OOM
    : cb_toss(args,
              f->error.code,
              "%.*s", (int)f->error.msg.used,
              (char const *)f->error.msg.mem );
  fsl_cx_err_reset(f);






  return rc;
}

static int cb_toss_db( cwal_callback_args const * args,
                       fsl_db * db ){
  int rc;
  assert(db && db->error.code);







|
>

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







96
97
98
99
100
101
102
103
104
105
106
107
108
109

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
    fsl_cx_err_reset(f);
  }
  va_end(vargs);
  return rc;
}

static int cb_toss_fsl( cwal_callback_args const * args,
                        fsl_cx * const f,
                        int fslRc){
  int rc;
  if(!fslRc) fslRc = f->error.code;
  if(FSL_RC_OOM==fslRc) rc = CWAL_RC_OOM;
  else{
    if(f->error.code){

      rc = cb_toss(args,
                   f->error.code,
                   "%.*s", (int)f->error.msg.used,
                   (char const *)f->error.msg.mem );
      fsl_cx_err_reset(f);
    }else{
      rc = cb_toss(args, CWAL_RC_EXCEPTION,
                   "Fossil result code %s",
                   fsl_rc_cstr(fslRc));
    }
  }
  return rc;
}

static int cb_toss_db( cwal_callback_args const * args,
                       fsl_db * db ){
  int rc;
  assert(db && db->error.code);
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
                              fsl_db * const db, bool addDtor,
                              cwal_value **rv,
                              fsl_dbrole_e role){
  cwal_native * n;
  cwal_value * nv;
  int rc = 0;
  char const * fname = NULL;
  fsl_size_t nameLen = 0;
  cwal_value * tmpV = NULL;
  assert(se && db && rv);
  n = cwal_new_native(se->e, db,
                      addDtor ? cwal_finalizer_f_fsl_db : NULL,
                      FSL_TYPEID(fsl_db));
  if(!n) return CWAL_RC_OOM;
  nv = cwal_native_value(n);
  cwal_value_ref(nv);
  /* Set up  "filename" property. It's problematic because
     of libfossil's internal DB juggling :/.
  */
  if(f) fname = fsl_cx_db_file_for_role(f, role, &nameLen);
  if(!fname){
    fname = fsl_db_filename(db, &nameLen);
  }
  if(fname){
    tmpV = cwal_new_string_value(se->e, fname, (cwal_size_t)nameLen);
    cwal_value_ref(tmpV);
    rc = tmpV
      ? cwal_prop_set(nv, "filename", 8, tmpV)
      : CWAL_RC_OOM;
    cwal_value_unref(tmpV);
    tmpV = 0;
    if(rc){
      goto end;
    }
    fname = 0;
  }

  /* Set up  "name" property. */
  if(f) fname = fsl_cx_db_name_for_role(f, role, &nameLen);
  if(!fname){
    fname = fsl_db_name(db);
    nameLen = fname ? cwal_strlen(fname) : 0;
  }
  if(fname){
    tmpV =
      cwal_new_string_value(se->e, fname, (cwal_size_t)nameLen);
    cwal_value_ref(tmpV);
    rc = tmpV
      ? cwal_prop_set(nv, "name", 4, tmpV)
      : CWAL_RC_OOM;
    cwal_value_unref(tmpV);
    tmpV = NULL;
    if(rc){







<











<
<
|
<

|













<
<
|
|
<


|







327
328
329
330
331
332
333

334
335
336
337
338
339
340
341
342
343
344


345

346
347
348
349
350
351
352
353
354
355
356
357
358
359
360


361
362

363
364
365
366
367
368
369
370
371
372
                              fsl_db * const db, bool addDtor,
                              cwal_value **rv,
                              fsl_dbrole_e role){
  cwal_native * n;
  cwal_value * nv;
  int rc = 0;
  char const * fname = NULL;

  cwal_value * tmpV = NULL;
  assert(se && db && rv);
  n = cwal_new_native(se->e, db,
                      addDtor ? cwal_finalizer_f_fsl_db : NULL,
                      FSL_TYPEID(fsl_db));
  if(!n) return CWAL_RC_OOM;
  nv = cwal_native_value(n);
  cwal_value_ref(nv);
  /* Set up  "filename" property. It's problematic because
     of libfossil's internal DB juggling :/.
  */


  fname = fsl_db_filename(db, NULL);

  if(fname){
    tmpV = cwal_new_string_value(se->e, fname, fsl_strlen(fname));
    cwal_value_ref(tmpV);
    rc = tmpV
      ? cwal_prop_set(nv, "filename", 8, tmpV)
      : CWAL_RC_OOM;
    cwal_value_unref(tmpV);
    tmpV = 0;
    if(rc){
      goto end;
    }
    fname = 0;
  }

  /* Set up  "name" property. */


  fname = fsl_db_name(db);
  if(!fname) fname = fsl_db_role_name(role);

  if(fname){
    tmpV =
      cwal_new_string_value(se->e, fname, fsl_strlen(fname));
    cwal_value_ref(tmpV);
    rc = tmpV
      ? cwal_prop_set(nv, "name", 4, tmpV)
      : CWAL_RC_OOM;
    cwal_value_unref(tmpV);
    tmpV = NULL;
    if(rc){
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743



1744
1745
1746
1747

1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
    }
  }
  return rc;
}


/**
 ** If cx has a property named "db", it is returned, else if
 ** createIfNotExists is true then a new native fsl_db Object named
 ** "db" is inserted into cx and returned. Returns NULL on allocation
 ** error or if no such property exists and createIfNotExists is
 ** false.



 */
static cwal_value * fsl_cx_db_prop( fsl_cx * f,
                                    cwal_value * fv,
                                    s2_engine * se,

                                    char createIfNotExists){
  cwal_value * rv;
  fsl_db * db = fsl_cx_db(f);
  /* assert(db); */
  rv = db ? cwal_prop_get(fv, "db", 2) : NULL;
  if(db && !rv && createIfNotExists){
    int rc = fsl_db_new_native(se, f, db, 0, &rv, FSL_DBROLE_MAIN);
    if(rc) return NULL;
    if(rv){
      cwal_value_ref(rv);
      rc = cwal_prop_set_with_flags(fv, "db", 2, rv,
                                    CWAL_VAR_F_CONST);
      cwal_value_unref(rv);
      if(rc) rv = NULL;







|




>
>
>




>
|





|







1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
    }
  }
  return rc;
}


/**
 ** If fv has a property named "db", it is returned, else if
 ** createIfNotExists is true then a new native fsl_db Object named
 ** "db" is inserted into cx and returned. Returns NULL on allocation
 ** error or if no such property exists and createIfNotExists is
 ** false.
 **
 ** The dbRole arg is only used when creating a new native wrapper
 ** and its "name" property is set to fsl_db_role_name().
 */
static cwal_value * fsl_cx_db_prop( fsl_cx * f,
                                    cwal_value * fv,
                                    s2_engine * se,
                                    fsl_dbrole_e dbRole,
                                    bool createIfNotExists){
  cwal_value * rv;
  fsl_db * db = fsl_cx_db(f);
  /* assert(db); */
  rv = db ? cwal_prop_get(fv, "db", 2) : NULL;
  if(db && !rv && createIfNotExists){
    int rc = fsl_db_new_native(se, f, db, 0, &rv, dbRole);
    if(rc) return NULL;
    if(rv){
      cwal_value_ref(rv);
      rc = cwal_prop_set_with_flags(fv, "db", 2, rv,
                                    CWAL_VAR_F_CONST);
      cwal_value_unref(rv);
      if(rc) rv = NULL;
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
    : NULL;
  if(args->argc && (!dbName || !*dbName)){
    return cb_toss(args, FSL_RC_MISUSE,
                   "Expecting a non-empty string argument.");
  }
  rc = fsl_config_open( f, (dbName && *dbName) ? dbName : 0 );
  if(rc){
    rc = cb_toss_fsl(args, f);
  }else{
    *rv = args->self;
  }
  return rc;
}

static int cb_fsl_config_close( cwal_callback_args const * args,







|







1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
    : NULL;
  if(args->argc && (!dbName || !*dbName)){
    return cb_toss(args, FSL_RC_MISUSE,
                   "Expecting a non-empty string argument.");
  }
  rc = fsl_config_open( f, (dbName && *dbName) ? dbName : 0 );
  if(rc){
    rc = cb_toss_fsl(args, f, rc);
  }else{
    *rv = args->self;
  }
  return rc;
}

static int cb_fsl_config_close( cwal_callback_args const * args,
1841
1842
1843
1844
1845
1846
1847
1848
1849

1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871

1872
1873
1874
1875
1876
1877
1878
    : NULL;
  if(!dbName || !*dbName){
    return cb_toss(args, FSL_RC_MISUSE,
                   "Expecting a non-empty string argument.");
  }
  rc = fsl_repo_open( f, dbName );
  if(rc){
    rc = cb_toss_fsl(args, f);
  }else{

    *rv = args->self;
  }
  return rc;
}

static int cb_fsl_ckout_open_dir( cwal_callback_args const * args,
                                  cwal_value **rv ){
  char const * dbName = 0;
  cwal_size_t nameLen = 0;
  int rc;
  int checkParentDirs;
  THIS_F;
  dbName = args->argc
    ? cwal_value_get_cstr(args->argv[0], &nameLen)
    : 0;
  checkParentDirs = args->argc>1
    ? (cwal_value_get_bool(args->argv[1]) ? 1 : 0)
    : 1;
  rc = fsl_ckout_open_dir( f, dbName, checkParentDirs );
  if(rc){
    rc = cb_toss_fsl(args, f);
  }else{

    *rv = args->self;
  }
  return rc;
}

static int cb_fsl_login_cookie_name( cwal_callback_args const * args,
                                     cwal_value ** rv){







|

>














|





|

>







1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
    : NULL;
  if(!dbName || !*dbName){
    return cb_toss(args, FSL_RC_MISUSE,
                   "Expecting a non-empty string argument.");
  }
  rc = fsl_repo_open( f, dbName );
  if(rc){
    rc = cb_toss_fsl(args, f, rc);
  }else{
    fsl_cx_db_prop(f, natV, se, FSL_DBROLE_REPO, true);
    *rv = args->self;
  }
  return rc;
}

static int cb_fsl_ckout_open_dir( cwal_callback_args const * args,
                                  cwal_value **rv ){
  char const * dbName = 0;
  cwal_size_t nameLen = 0;
  int rc;
  int checkParentDirs;
  THIS_F;
  dbName = args->argc
    ? cwal_value_get_cstr(args->argv[0], &nameLen)
    : ".";
  checkParentDirs = args->argc>1
    ? (cwal_value_get_bool(args->argv[1]) ? 1 : 0)
    : 1;
  rc = fsl_ckout_open_dir( f, dbName, checkParentDirs );
  if(rc){
    rc = cb_toss_fsl(args, f, rc);
  }else{
    fsl_cx_db_prop(f, natV, se, FSL_DBROLE_CKOUT, true);
    *rv = args->self;
  }
  return rc;
}

static int cb_fsl_login_cookie_name( cwal_callback_args const * args,
                                     cwal_value ** rv){
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
                            cwal_finalizer_f_fsl_cx,
                            FSL_TYPEID(fsl_cx));
  if(!v){
    fsl_cx_finalize( f );
    return CWAL_RC_OOM;
  }
  cwal_value_prototype_set( v, fsl_cx_prototype(se) );
  fsl_cx_db_prop( f, v, se, 1 ) /* initialize this->db */;
  *rv  = v;
  return 0;
}

/**
   If parent contains a Db property with the given name, that property
   is disconnected from its native and removed from parent, but its Db







|







1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
                            cwal_finalizer_f_fsl_cx,
                            FSL_TYPEID(fsl_cx));
  if(!v){
    fsl_cx_finalize( f );
    return CWAL_RC_OOM;
  }
  cwal_value_prototype_set( v, fsl_cx_prototype(se) );
  //fsl_cx_db_prop( f, v, se, 1 ) /* initialize this->db */;
  *rv  = v;
  return 0;
}

/**
   If parent contains a Db property with the given name, that property
   is disconnected from its native and removed from parent, but its Db
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
      cwal_native_clear(nat, 0);
      cwal_prop_unset(parent, dbName, dbNameLen);
    }
  }
}

static int cb_fsl_cx_close( cwal_callback_args const * args,
                         cwal_value **rv ){
  cwal_value * dbNs;
  THIS_F;
  /* It's important that we clear the Value/Native bindings
     to all of the context's databases because clients can do this:

     var db = f.db;
     f.close();
     db.something(...)

     Which, if we're not careful here, can lead to them having
     not only a stale fsl_db handle, but one which points back
     to a stale fsl_cx pointer.

     Thank you, valgrind.
  */
  dbNs = fsl_cx_db_prop(f, natV, se, 0);
  if(dbNs){
    cb_fsl_clear_handles(natV, "db");
  }
  if(fsl_cx_db_config(f)){
    fsl_config_close(f);
  }
  if(fsl_cx_db_ckout(f)){
    fsl_ckout_close(f);
    /* also closes its repo db */
  }else if(fsl_cx_db_repo(f)){
    fsl_repo_close(f);
  }
  *rv = args->self;
  return 0;
}


static int cb_fsl_cx_finalize( cwal_callback_args const * args,
                              cwal_value **rv ){
  THIS_F;
  if(fsl_cx_db_prop(f, args->self, se, 0)){
    cb_fsl_cx_close(args, rv);
  }
  cwal_native_clear( nat, 1 );
  return 0;
}

static int cb_fsl_cx_user_name( cwal_callback_args const * args,







|















|



<
<
<
|
<
<
<
<
<








|







1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011



2012





2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
      cwal_native_clear(nat, 0);
      cwal_prop_unset(parent, dbName, dbNameLen);
    }
  }
}

static int cb_fsl_cx_close( cwal_callback_args const * args,
                            cwal_value **rv ){
  cwal_value * dbNs;
  THIS_F;
  /* It's important that we clear the Value/Native bindings
     to all of the context's databases because clients can do this:

     var db = f.db;
     f.close();
     db.something(...)

     Which, if we're not careful here, can lead to them having
     not only a stale fsl_db handle, but one which points back
     to a stale fsl_cx pointer.

     Thank you, valgrind.
  */
  dbNs = fsl_cx_db_prop(f, natV, se, FSL_DBROLE_NONE, false);
  if(dbNs){
    cb_fsl_clear_handles(natV, "db");
  }



  fsl_cx_close_dbs(f);





  *rv = args->self;
  return 0;
}


static int cb_fsl_cx_finalize( cwal_callback_args const * args,
                              cwal_value **rv ){
  THIS_F;
  if(fsl_cx_db_prop(f, args->self, se, FSL_DBROLE_NONE, false)){
    cb_fsl_cx_close(args, rv);
  }
  cwal_native_clear( nat, 1 );
  return 0;
}

static int cb_fsl_cx_user_name( cwal_callback_args const * args,
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
  if(rc){
    /* Undecided: throw or return undefined if no entry found? */
#if 1
    if(FSL_RC_NOT_FOUND==rc){
      *rv = cwal_value_undefined();
      rc = 0;
    }else{
      rc = cb_toss_fsl(args, f);
    }
#else
    rc = cb_toss_fsl(args, f);
#endif
  }else{
    if(toUuid){
      assert(uuid);
      *rv = cwal_new_string_value(args->engine, uuid, cwal_strlen(uuid));
      fsl_free(uuid);
      if(!*rv){







|


|







2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
  if(rc){
    /* Undecided: throw or return undefined if no entry found? */
#if 1
    if(FSL_RC_NOT_FOUND==rc){
      *rv = cwal_value_undefined();
      rc = 0;
    }else{
      rc = cb_toss_fsl(args, f, rc);
    }
#else
    rc = cb_toss_fsl(args, f, rc);
#endif
  }else{
    if(toUuid){
      assert(uuid);
      *rv = cwal_new_string_value(args->engine, uuid, cwal_strlen(uuid));
      fsl_free(uuid);
      if(!*rv){
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
    }
  }
  rc = (rid>0)
    ? fsl_content_get(f, rid, &fbuf)
    : fsl_content_get_sym(f, sym, &fbuf);
  if(rc){
    assert(f->error.code);
    rc = cb_toss_fsl(args, f);
  }else{
    cwal_buffer * cbuf = cwal_new_buffer(args->engine, 0);
    if(!cbuf) rc = CWAL_RC_OOM;
    else{
      cwal_value * cbufV = cwal_buffer_value(cbuf);
      cwal_value_ref(cbufV);
      rc = fsl_buffer_to_cwal_buffer(args->engine, &fbuf, cbuf);







|







2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
    }
  }
  rc = (rid>0)
    ? fsl_content_get(f, rid, &fbuf)
    : fsl_content_get_sym(f, sym, &fbuf);
  if(rc){
    assert(f->error.code);
    rc = cb_toss_fsl(args, f, rc);
  }else{
    cwal_buffer * cbuf = cwal_new_buffer(args->engine, 0);
    if(!cbuf) rc = CWAL_RC_OOM;
    else{
      cwal_value * cbufV = cwal_buffer_value(cbuf);
      cwal_value_ref(cbufV);
      rc = fsl_buffer_to_cwal_buffer(args->engine, &fbuf, cbuf);
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
  /* TODO: script mapping for fsl_satype_e values for 3nd arg.
   */
  rc = sym
    ? fsl_deck_load_sym(f, &mf, sym, mfType)
    : fsl_deck_load_rid(f, &mf, rid, mfType)
    ;
  if(rc){
    if(f->error.code) rc = cb_toss_fsl(args, f);
    else{
      rc = sym
        ? cb_toss(args, rc, "Loading manifest '%s' failed with code %d/%s",
                  sym, rc, fsl_rc_cstr(rc))
        : cb_toss(args, rc, "Loading manifest RID %d failed with code %d/%s",
                  (int)rid, rc, fsl_rc_cstr(rc));
    }







|







2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
  /* TODO: script mapping for fsl_satype_e values for 3nd arg.
   */
  rc = sym
    ? fsl_deck_load_sym(f, &mf, sym, mfType)
    : fsl_deck_load_rid(f, &mf, rid, mfType)
    ;
  if(rc){
    if(f->error.code) rc = cb_toss_fsl(args, f, rc);
    else{
      rc = sym
        ? cb_toss(args, rc, "Loading manifest '%s' failed with code %d/%s",
                  sym, rc, fsl_rc_cstr(rc))
        : cb_toss(args, rc, "Loading manifest RID %d failed with code %d/%s",
                  (int)rid, rc, fsl_rc_cstr(rc));
    }
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
  arg = args->argv[0];
  if(cwal_value_is_integer(arg)){
    rid1 = (fsl_id_t)cwal_value_get_integer(arg);
  }else if(!(sym = cwal_value_get_cstr(arg,NULL))){
    goto misuse;
  }else{
    rc = fsl_sym_to_rid(f, sym, FSL_SATYPE_ANY, &rid1);
    if(rc) return cb_toss_fsl(args, f);
  }

  /* The v2 arg... */
  arg = args->argv[1];
  if(cwal_value_is_integer(arg)){
    rid2 = (fsl_id_t)cwal_value_get_integer(arg);
  }else if(!(sym = cwal_value_get_cstr(arg,NULL))){
    goto misuse;
  }else{
    rc = fsl_sym_to_rid(f, sym, FSL_SATYPE_ANY, &rid2);
    if(rc) return cb_toss_fsl(args, f);
  }

  assert(rid1>0);
  assert(rid2>0);

  rc = fsl_content_get(f, rid1, &c1);
  if(!rc) rc = fsl_content_get(f, rid2, &c2);
  if(rc){
    rc = cb_toss_fsl(args, f);
    goto end;
  }
  diffFlags = FSL_DIFF_LINENO | FSL_DIFF_SIDEBYSIDE;
  if((args->argc>2) && cwal_props_can((arg = args->argv[2]))){
    do{
      /* Collect diff flags from object */
      cwal_value * v;







|










|








|







2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
  arg = args->argv[0];
  if(cwal_value_is_integer(arg)){
    rid1 = (fsl_id_t)cwal_value_get_integer(arg);
  }else if(!(sym = cwal_value_get_cstr(arg,NULL))){
    goto misuse;
  }else{
    rc = fsl_sym_to_rid(f, sym, FSL_SATYPE_ANY, &rid1);
    if(rc) return cb_toss_fsl(args, f, rc);
  }

  /* The v2 arg... */
  arg = args->argv[1];
  if(cwal_value_is_integer(arg)){
    rid2 = (fsl_id_t)cwal_value_get_integer(arg);
  }else if(!(sym = cwal_value_get_cstr(arg,NULL))){
    goto misuse;
  }else{
    rc = fsl_sym_to_rid(f, sym, FSL_SATYPE_ANY, &rid2);
    if(rc) return cb_toss_fsl(args, f, rc);
  }

  assert(rid1>0);
  assert(rid2>0);

  rc = fsl_content_get(f, rid1, &c1);
  if(!rc) rc = fsl_content_get(f, rid2, &c2);
  if(rc){
    rc = cb_toss_fsl(args, f, rc);
    goto end;
  }
  diffFlags = FSL_DIFF_LINENO | FSL_DIFF_SIDEBYSIDE;
  if((args->argc>2) && cwal_props_can((arg = args->argv[2]))){
    do{
      /* Collect diff flags from object */
      cwal_value * v;
Changes to bindings/s2/unit2/000-200-context.s2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17



18
19
20
21
22
23
24
assert 'Fossil' === typename Fossil;
assert 'Db' === typename Fossil.Db;
assert 'Stmt' === typename Fossil.Db.Stmt;
assert 'Context' === typename Fossil.Context;

scope {
    var f = new Fossil.Context({traceSql:false});
    //print('f =',f);
    assert 'Context' === typename f;
    assert f inherits Fossil.Context;
    const DB = f.db;
    assert DB inherits Fossil.Db;
    assert DB.name === 'main' /* this is our "main" db */;

    assert f === f.openCheckout();
    assert f === f.openConfig();
    assert f === f.closeConfig();



    var counter = 0;
    assert DB === DB.each({
        sql:<<<_SQL
            SELECT mtime FROM event LIMIT 2
        _SQL,
        callback:'++counter'
    });










<
|
<




>
>
>







1
2
3
4
5
6
7
8
9
10

11

12
13
14
15
16
17
18
19
20
21
22
23
24
25
assert 'Fossil' === typename Fossil;
assert 'Db' === typename Fossil.Db;
assert 'Stmt' === typename Fossil.Db.Stmt;
assert 'Context' === typename Fossil.Context;

scope {
    var f = new Fossil.Context({traceSql:false});
    //print('f =',f);
    assert 'Context' === typename f;
    assert f inherits Fossil.Context;

    assert !f.db;


    assert f === f.openCheckout();
    assert f === f.openConfig();
    assert f === f.closeConfig();
    const DB = f.db;
    assert DB inherits Fossil.Db;
    assert DB.name === 'ckout' /* this is our "main" db */;
    var counter = 0;
    assert DB === DB.each({
        sql:<<<_SQL
            SELECT mtime FROM event LIMIT 2
        _SQL,
        callback:'++counter'
    });
Changes to f-apps/f-open.c.
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
  if(!keep){
    prev_ckout = 0;
  } else{
    fsl_ckout_version_info(f, &prev_ckout, 0);
  }
  assert(dbRepo && dbRepo->dbh);
  if(!fsl_db_exists(dbRepo,"SELECT 1 FROM %s.event WHERE type='ci'",
                    fsl_db_role_label(FSL_DBROLE_REPO))){
    // Assume there are no checkins in this repo, so nothing for us to do.
    f_out("Repo contains no checkins, so there is nothing to check out.\n");
    goto end;
  }
  rc = fsl_sym_to_rid(f, sym, FSL_SATYPE_CHECKIN, &rv);
  if(rc){
    if(FSL_RC_NOT_FOUND==rc){







|







300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
  if(!keep){
    prev_ckout = 0;
  } else{
    fsl_ckout_version_info(f, &prev_ckout, 0);
  }
  assert(dbRepo && dbRepo->dbh);
  if(!fsl_db_exists(dbRepo,"SELECT 1 FROM %s.event WHERE type='ci'",
                    fsl_db_role_name(FSL_DBROLE_REPO))){
    // Assume there are no checkins in this repo, so nothing for us to do.
    f_out("Repo contains no checkins, so there is nothing to check out.\n");
    goto end;
  }
  rc = fsl_sym_to_rid(f, sym, FSL_SATYPE_CHECKIN, &rv);
  if(rc){
    if(FSL_RC_NOT_FOUND==rc){
Changes to f-apps/f-test-ciwoco.c.
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
  rc = setup_deck(&d, "Files added w/o checkout.");
  assert(0==rc);

  //////////////////////////////////////////////////////////////
  // Step 3: add some files...
  char const * fnames[] = {
    "f-test-ciwoco.c",
    "Makefile.in",
    NULL
  };
  for( int i = 0; (fname = fnames[i]); ++i ){
    rc = fsl_buffer_fill_from_filename(&content, fname);
    assert(0==rc);
    rc = fsl_deck_F_set_content(&d, fname, &content,
                                FSL_FILE_PERM_REGULAR, NULL);
    assert(0==rc);
    f_out("Added file: %s\n", fname);
  }

  //////////////////////////////////////////////////////////////
  // Step 4: save the deck...
  rc = fsl_deck_save(&d, false);
  assert(0==rc);
  f_out("Saved checkin #%"FSL_ID_T_PFMT"\n", d.rid);

  //////////////////////////////////////////////////////////////
  // Step 5: ...
  f_out("Now we'll try again so we can ensure that deltaing "
        "of parent file content works.\n");
  fsl_deck_derive(&d);
  setup_deck(&d, "Modified Makefile.in.");
  fname = "Makefile.in";
  rc = fsl_buffer_fill_from_filename(&content, fname);
  assert(0==rc);
  rc = fsl_buffer_append(&content,
                         "\n# This is an edit. There are many "
                         "like it, but this one is mine.\n", -1);
  assert(0==rc);
  rc = fsl_deck_F_set_content(&d, fname, &content,







|



|


















|
|







113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
  rc = setup_deck(&d, "Files added w/o checkout.");
  assert(0==rc);

  //////////////////////////////////////////////////////////////
  // Step 3: add some files...
  char const * fnames[] = {
    "f-test-ciwoco.c",
    "GNUmakefile",
    NULL
  };
  for( int i = 0; (fname = fnames[i]); ++i ){
    rc = fsl_buffer_fill_from_filename(&content, fname); 
    assert(0==rc);
    rc = fsl_deck_F_set_content(&d, fname, &content,
                                FSL_FILE_PERM_REGULAR, NULL);
    assert(0==rc);
    f_out("Added file: %s\n", fname);
  }

  //////////////////////////////////////////////////////////////
  // Step 4: save the deck...
  rc = fsl_deck_save(&d, false);
  assert(0==rc);
  f_out("Saved checkin #%"FSL_ID_T_PFMT"\n", d.rid);

  //////////////////////////////////////////////////////////////
  // Step 5: ...
  f_out("Now we'll try again so we can ensure that deltaing "
        "of parent file content works.\n");
  fsl_deck_derive(&d);
  setup_deck(&d, "Modified GNUmakefile.");
  fname = "GNUmakefile";
  rc = fsl_buffer_fill_from_filename(&content, fname);
  assert(0==rc);
  rc = fsl_buffer_append(&content,
                         "\n# This is an edit. There are many "
                         "like it, but this one is mine.\n", -1);
  assert(0==rc);
  rc = fsl_deck_F_set_content(&d, fname, &content,
Changes to include/fossil-scm/auth.h.
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
   returns a copy of zPw) if the project code is not set, under
   the assumption that this is "the first xfer request of a
   clone."  Whether or not that will apply at this level to
   libfossil remains to be seen.

   TODO? Does fossil still use SHA1 for this?
*/
FSL_EXPORT char * fsl_sha1_shared_secret( fsl_cx * f, char const * zLoginName, char const * zPw );

/**
   Fetches the login group name (if any) for the given context's
   current repositorty db. If f has no opened repo, 0 is returned.

   If the repo belongs to a login group, its name is returned in the
   form of a NUL-terminated string. The returned value (which may be
   0) is owned by the caller, who must eventually fsl_free() it. The
   value (unlike in fossil(1)) is not cached because it may change
   via modification of the login group.
*/
FSL_EXPORT char * fsl_repo_login_group_name(fsl_cx * f);

/**
   Fetches the login cookie name associated with the current repository
   db, or 0 if no repository is opened.

   The returned (NUL-terminated) string is owned by the caller, who
   must eventually fsl_free() it. The value is not cached in f because
   it may change during the lifetime of a repo (if a login group is
   set or removed).

   The login cookie name is a string in the form "fossil-XXX", where
   XXX is the first 16 hex digits of either the repo's
   'login-group-code' or 'project-code' config values (in that order).
*/
FSL_EXPORT char * fsl_repo_login_cookie_name(fsl_cx * f);

/**
   Searches for a user ID (from the repo.user.uid DB field) for a given
   username and password. The password may be either its hashed form or
   non-hashed form (if it is not exactly 40 bytes long, that is!).

   On success, 0 is returned and *pId holds the ID of the
   user found (if any).  *pId will be set to 0 if no match for the
   name/password was found, or positive if a match was found.

   If any of the arguments are NULL, FSL_RC_MISUSE is returned. f must
   have an opened repo, else FSL_RC_NOT_A_REPO is returned.

*/
FSL_EXPORT int fsl_repo_login_search_uid(fsl_cx * f, char const * zUsername,
                                         char const * zPasswd, fsl_id_t * pId);

/**
   Clears all login state for the given user ID. If the ID is <=0 then
   ALL logins are cleared. Has no effect on the built-in pseudo-users.

   Returns non-0 on error, and not finding a matching user ID is not
   considered an error.

   f must have an opened repo, or FSL_RC_NOT_A_REPO is returned.

   TODO: there are currently no APIs for _setting_ the state this
   function clears!
*/
FSL_EXPORT int fsl_repo_login_clear( fsl_cx * f, fsl_id_t userId );


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_AUTH_H_INCLUDED */







|











|














|














|














|







42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
   returns a copy of zPw) if the project code is not set, under
   the assumption that this is "the first xfer request of a
   clone."  Whether or not that will apply at this level to
   libfossil remains to be seen.

   TODO? Does fossil still use SHA1 for this?
*/
FSL_EXPORT char * fsl_sha1_shared_secret( fsl_cx * const f, char const * zLoginName, char const * zPw );

/**
   Fetches the login group name (if any) for the given context's
   current repositorty db. If f has no opened repo, 0 is returned.

   If the repo belongs to a login group, its name is returned in the
   form of a NUL-terminated string. The returned value (which may be
   0) is owned by the caller, who must eventually fsl_free() it. The
   value (unlike in fossil(1)) is not cached because it may change
   via modification of the login group.
*/
FSL_EXPORT char * fsl_repo_login_group_name(fsl_cx * const f);

/**
   Fetches the login cookie name associated with the current repository
   db, or 0 if no repository is opened.

   The returned (NUL-terminated) string is owned by the caller, who
   must eventually fsl_free() it. The value is not cached in f because
   it may change during the lifetime of a repo (if a login group is
   set or removed).

   The login cookie name is a string in the form "fossil-XXX", where
   XXX is the first 16 hex digits of either the repo's
   'login-group-code' or 'project-code' config values (in that order).
*/
FSL_EXPORT char * fsl_repo_login_cookie_name(fsl_cx * const f);

/**
   Searches for a user ID (from the repo.user.uid DB field) for a given
   username and password. The password may be either its hashed form or
   non-hashed form (if it is not exactly 40 bytes long, that is!).

   On success, 0 is returned and *pId holds the ID of the
   user found (if any).  *pId will be set to 0 if no match for the
   name/password was found, or positive if a match was found.

   If any of the arguments are NULL, FSL_RC_MISUSE is returned. f must
   have an opened repo, else FSL_RC_NOT_A_REPO is returned.

*/
FSL_EXPORT int fsl_repo_login_search_uid(fsl_cx * const f, char const * zUsername,
                                         char const * zPasswd, fsl_id_t * pId);

/**
   Clears all login state for the given user ID. If the ID is <=0 then
   ALL logins are cleared. Has no effect on the built-in pseudo-users.

   Returns non-0 on error, and not finding a matching user ID is not
   considered an error.

   f must have an opened repo, or FSL_RC_NOT_A_REPO is returned.

   TODO: there are currently no APIs for _setting_ the state this
   function clears!
*/
FSL_EXPORT int fsl_repo_login_clear( fsl_cx * const f, fsl_id_t userId );


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_AUTH_H_INCLUDED */
Changes to include/fossil-scm/checkout.h.
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  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-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.
*/

#include "db.h" /* MUST come first b/c of config macros */







|







9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

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

/** @file checkout.h

    fossil-checkout.h declares APIs specifically dealing with
    checkout-side state, as opposed to purely repository-db-side state
    or non-content-related APIs.
*/

#include "db.h" /* MUST come first b/c of config macros */
2798
2799
2800
2801
2802
2803
2804





















































































































2805
2806
2807
2808
2809

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







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





2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926

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

/**
   Tries to open a checked-out fossil repository db in the given
   directory. 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 dirName is NULL, "." is implied.

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


/**
   If fsl_ckout_open_dir() (or similar) has been used to open a
   checkout db, this call closes that db.

   If an associated repository is also opened (as it should always be
   when a checkout is opened), it is necessarily closed by this
   operation because a checkout db is only valid with its associated
   repository. If no checkout is opened but a repository is, this
   function DOES NOT close that repository: use fsl_repo_close() or
   fsl_cx_close_dbs() to close it (noting that all dbs are implicitly
   closed by fsl_cx_finalize()).

   In the general case, fsl_repo_close() or fsl_cx_close_dbs(),
   instead of this routine, can be used to close a checkout 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.

   Sidebar: this is NOT related to fossil(1)'s "close" feature, which
   "closes" a checkout by deleting the checkout database.

   @see fsl_ckout_open()
   @see fsl_repo_close()
   @see fsl_cx_close_dbs()
*/
FSL_EXPORT int fsl_ckout_close( fsl_cx * const f );

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_CHECKOUT_H_INCLUDED */
Changes to include/fossil-scm/cli.h.
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546

    fcli_cx() returns the API's fsl_cx instance. It will be non-NULL
    (but might not have an opened checkout/repository) if fsl_setup()
    succeeds.
*/
FSL_EXPORT fcli_t fcli;

/**
   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.
*/
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
   fcli_pre_setup() for a workaround for that.)








<
<
<
<
<
<
<
<
<
<







523
524
525
526
527
528
529










530
531
532
533
534
535
536

    fcli_cx() returns the API's fsl_cx instance. It will be non-NULL
    (but might not have an opened checkout/repository) if fsl_setup()
    succeeds.
*/
FSL_EXPORT fcli_t fcli;











/**
   Initializes fcli's state and CLI flags processing.

   MUST BE CALLED BEFORE fsl_malloc() and friends are used, as this
   swaps out the allocator with one which aborts on OOM. (But see
   fcli_pre_setup() for a workaround for that.)

Changes to include/fossil-scm/confdb.h.
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  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-confdb.h

    fossil-confdb.h declares APIs dealing with fossil's various
    configuration option storage backends.
*/

#include "core.h" /* MUST come first b/c of config macros */








|







8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  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 confdb.h

    fossil-confdb.h declares APIs dealing with fossil's various
    configuration option storage backends.
*/

#include "core.h" /* MUST come first b/c of config macros */

Changes to include/fossil-scm/core.h.
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  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-core.h

  This file declares the core SCM-related public APIs.
*/

#include "fossil-scm/util.h" /* MUST come first b/c of config macros */
#include <time.h> /* struct tm, time_t */
#if defined(__cplusplus)







|







9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

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

/** @file core.h

  This file declares the core SCM-related public APIs.
*/

#include "fossil-scm/util.h" /* MUST come first b/c of config macros */
#include <time.h> /* struct tm, time_t */
#if defined(__cplusplus)
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
   fsl_cx_db_repo() and fsl_cx_db_ckout() will always return the same
   database handle, but they can tell whether a given role has been
   attached or not and will fail in their documented ways when the
   role's corresponding database has not yet been attached. e.g.
   `fsl_cx_db_repo()` will return `NULL` if a repo database is not
   attached.

   @see fsl_db_role_label()
   @see fsl_cx_db_name_for_role()
   @see fsl_cx_db_file_for_role()
*/
enum fsl_dbrole_e {
/**
   Sentinel "no role" value.
*/







|







113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
   fsl_cx_db_repo() and fsl_cx_db_ckout() will always return the same
   database handle, but they can tell whether a given role has been
   attached or not and will fail in their documented ways when the
   role's corresponding database has not yet been attached. e.g.
   `fsl_cx_db_repo()` will return `NULL` if a repo database is not
   attached.

   @see fsl_db_role_name()
   @see fsl_cx_db_name_for_role()
   @see fsl_cx_db_file_for_role()
*/
enum fsl_dbrole_e {
/**
   Sentinel "no role" value.
*/
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
FSL_EXPORT int fsl_outputf( fsl_cx * const f, char const * fmt, ... );

/**
   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,
   FSL_RC_OOM if copying of the userName fails.








<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







945
946
947
948
949
950
951




























































952
953
954
955
956
957
958
FSL_EXPORT int fsl_outputf( fsl_cx * const f, char const * fmt, ... );

/**
   va_list counterpart to fsl_outputf().
*/
FSL_EXPORT int fsl_outputfv( fsl_cx * const f, char const * fmt, va_list args );





























































/**
   Sets or clears (if userName is NULL or empty) the default
   repository user name for operations which require one.

   Returns 0 on success, FSL_RC_MISUSE if f is NULL,
   FSL_RC_OOM if copying of the userName fails.

1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
   default user name set. The returned bytes are owned by f and will
   be invalidated by any future calls to fsl_cx_user_set().

   @see fsl_cx_user_guess()
*/
FSL_EXPORT char const * fsl_cx_user_get( fsl_cx const * const f );

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

/**
   Tries to open a checked-out fossil repository db in the given
   directory. 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 );


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







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







987
988
989
990
991
992
993















































































































































































































































































994
995
996
997
998
999
1000
   default user name set. The returned bytes are owned by f and will
   be invalidated by any future calls to fsl_cx_user_set().

   @see fsl_cx_user_guess()
*/
FSL_EXPORT char const * fsl_cx_user_get( fsl_cx const * 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().
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422

   Note that the role of FSL_DBROLE_TEMP is invalid here.
*/
FSL_EXPORT char const * fsl_cx_db_file_for_role(fsl_cx const * f,
                                                fsl_dbrole_e r,
                                                fsl_size_t * len);

/**
   Similar to fsl_cx_db_file_ckout() and friends except that it
   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
   db connection is closed. If len is not NULL then *len is (on







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







1049
1050
1051
1052
1053
1054
1055





























1056
1057
1058
1059
1060
1061
1062

   Note that the role of FSL_DBROLE_TEMP is invalid here.
*/
FSL_EXPORT char const * fsl_cx_db_file_for_role(fsl_cx const * f,
                                                fsl_dbrole_e r,
                                                fsl_size_t * len);































/**
   If f has an opened checkout db (from fsl_ckout_open_dir()) then
   this function returns the directory part of the path for the
   checkout, including (for historical and internal convenience
   reasons) a trailing slash. The returned bytes are valid until that
   db connection is closed. If len is not NULL then *len is (on
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460



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


1475
1476
1477
1478
1479
1480
1481
1482


1483
1484
1485
1486
1487
1488
1489
*/
FSL_EXPORT char const * fsl_cx_ckout_dir_name(fsl_cx const * f,
                                              fsl_size_t * len);

/**
   Returns a handle to f's main db (which may or may not have any
   relationship to the repo/checkout/config databases - that's
   unspecified!), or NULL if f has no opened repo or checkout db.  The
   returned object is owned by f and the client MUST NOT do any of the
   following:

   - Close the db handle.

   - Use transactions without using fsl_db_transaction_begin()
   and friends.

   - Fiddle with the handle's internals. Doing so might confuse its
   owning context.

   Clients MAY add new user-defined functions, use the handle with
   fsl_db_prepare(), and other "mundane" db-related tasks.

   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.

   @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
   fsl_repo_open(), fsl_ckout_open_dir(), or similar, this
   returns a pointer to that database, else it returns NULL.



   @see fsl_cx_db()
*/
FSL_EXPORT fsl_db * fsl_cx_db_repo( fsl_cx * const f );

/**
   If f is not NULL and has had a checkout opened via
   fsl_ckout_open_dir() or similar, this returns a pointer to that
   database, else it returns NULL.



   @see fsl_cx_db()
*/
FSL_EXPORT fsl_db * fsl_cx_db_ckout( fsl_cx * const f );

/**
   A helper which fetches f's repository db. If f has no repo db







|



















|
|
|
>
>
>
|
|












>
>








>
>







1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
*/
FSL_EXPORT char const * fsl_cx_ckout_dir_name(fsl_cx const * f,
                                              fsl_size_t * len);

/**
   Returns a handle to f's main db (which may or may not have any
   relationship to the repo/checkout/config databases - that's
   unspecified!), or NULL if f has no opened repo or checkout db. The
   returned object is owned by f and the client MUST NOT do any of the
   following:

   - Close the db handle.

   - Use transactions without using fsl_db_transaction_begin()
   and friends.

   - Fiddle with the handle's internals. Doing so might confuse its
   owning context.

   Clients MAY add new user-defined functions, use the handle with
   fsl_db_prepare(), and other "mundane" db-related tasks.

   Note that the global config db uses a separate db handle accessible
   via fsl_cx_db_config().

   Design notes:

   The current (2021-12-31) architecture treats one of the REPO or
   CHECKOUT dbs as its MAIN db and ATTACHes (if needed) the other
   one. Even so, it uses separate fsl_db instances to track each one
   so that we can keep track of their file names. Prior to 2021-12-31,
   the API internally opened a TEMP/IN-MEMORY db and attached both the
   repo and checkout dbs to it. Though easier to work with internally,
   that approach has minor locking- and consistency-related issues
   which justified rewiring it.

   @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
   fsl_repo_open(), fsl_ckout_open_dir(), or similar, this
   returns a pointer to that database, else it returns NULL.

   Note that this may return the same db handle as fsl_cx_db_ckout().

   @see fsl_cx_db()
*/
FSL_EXPORT fsl_db * fsl_cx_db_repo( fsl_cx * const f );

/**
   If f is not NULL and has had a checkout opened via
   fsl_ckout_open_dir() or similar, this returns a pointer to that
   database, else it returns NULL.

   Note that this may return the same db handle as fsl_cx_db_repo().

   @see fsl_cx_db()
*/
FSL_EXPORT fsl_db * fsl_cx_db_ckout( fsl_cx * const f );

/**
   A helper which fetches f's repository db. If f has no repo db
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
FSL_EXPORT void 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_label(FSL_DBROLE_CONFIG).

   @see fsl_config_open()
   @see fsl_config_close()
*/
FSL_EXPORT fsl_db * fsl_cx_db_config( fsl_cx * const f );

/**







|







1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
FSL_EXPORT void 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).

   @see fsl_config_open()
   @see fsl_config_close()
*/
FSL_EXPORT fsl_db * fsl_cx_db_config( fsl_cx * const f );

/**
2028
2029
2030
2031
2032
2033
2034
2035

2036
2037
2038
2039
2040

2041
2042
2043
2044
2045
2046
2047
   fsl_db_transaction_level(), or 0 if f has no db opened.

   @see fsl_cx_db()
*/
FSL_EXPORT int fsl_cx_transaction_level(fsl_cx * const f);
/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_transaction_begin().

*/
FSL_EXPORT int fsl_cx_transaction_begin(fsl_cx * const f);
/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_transaction_end().

*/
FSL_EXPORT int fsl_cx_transaction_end(fsl_cx * const f, bool doRollback);

/**
   Installs or (if f is NULL) uninstalls a confirmation callback for
   use by operations on f which require user confirmation. The exact
   implications of *not* installing a confirmer depend on the







|
>




|
>







1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
   fsl_db_transaction_level(), or 0 if f has no db opened.

   @see fsl_cx_db()
*/
FSL_EXPORT int fsl_cx_transaction_level(fsl_cx * const f);
/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_transaction_begin(). Returns FSL_RC_MISUSE, and updates f's
   error state, if f has no repo or checkout db opened.
*/
FSL_EXPORT int fsl_cx_transaction_begin(fsl_cx * const f);
/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_transaction_end(). Returns FSL_RC_MISUSE, and updates f's
   error state, if f has no repo or checkout db opened.
*/
FSL_EXPORT int fsl_cx_transaction_end(fsl_cx * const f, bool doRollback);

/**
   Installs or (if f is NULL) uninstalls a confirmation callback for
   use by operations on f which require user confirmation. The exact
   implications of *not* installing a confirmer depend on the
Changes to include/fossil-scm/db.h.
1549
1550
1551
1552
1553
1554
1555
1556


1557
1558
1559
1560
1561
1562
1563
*/
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.



   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.

   If db has any pending transactions, they are rolled







|
>
>







1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
*/
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 but any memory which might be owned
   by the db handle (e.g. its filename, which can be set
   independently of being opened) will be cleaned up.

   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.

   If db has any pending transactions, they are rolled
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
  
/**
   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 (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_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
   for script bindings.








|
<







1612
1613
1614
1615
1616
1617
1618
1619

1620
1621
1622
1623
1624
1625
1626
  
/**
   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 (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);


/**
   Allocates a new fsl_db instance(). Returns NULL on allocation
   error. Note that fsl_db instances can often be used from the
   stack - allocating them dynamically is an uncommon case necessary
   for script bindings.

Added include/fossil-scm/deprecated.h.








































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/* -*- 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_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, some of it rather unnecessary.
*/

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


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

#endif
/* ORG_FOSSIL_SCM_LIBFOSSIL_DEPRECATED_H_INCLUDED */
Changes to include/fossil-scm/internal.h.
279
280
281
282
283
284
285
286
287
288
289
290
291


292
293


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

/* The fsl_cx class is documented in main public header. */
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.

     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 DBs get ATTACHed to that one. Their separate


     handles (this->{repo,ckout}.db) are used to store the name
     and file path to each one (even though they have no real db


     handle associated with them).

     As of 20211230, f->config.db is its own handle, not ATTACHed with
     the others. Its db gets renamed to
     fsl_db_role_label(FSL_DBROLE_CONFIG).

     Internal code should rely as little as possible on the actual
     arrangement of internal DB handles, and should use
     fsl_cx_db_repo(), fsl_cx_db_ckout(), and fsl_cx_db_config() to
     get a handle to the specific db they want. 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.

     Reminder to self 2021-12-03: sqlite has since added an option
     to give the MAIN db a name of one's choice:

     ```
     sqlite3_db_config(db, SQLITE_DBCONFIG_MAINDBNAME,...)
     ```

     that could be used to solve our connection-juggling problems by
     OPEN()'ing the first (repo/checkout/config) db and ATTACHing the others
     to that. Prior to the above API addition, that was not feasible because
     it meant that juggling the db names was a true pain in the butt.

     However, the global config throws a wrench in that: we need to be
     able to open and close that particular db on demand because it's
     used by an arbitrary number of applications and we need to avoid
     locking it. If an app (like `f-config`) were to open that db
     first, it would become the main db and we could no longer close
     it once a repo and/or checkout had been attached. That said, we
     could get away with using a completely separate sqlite3 instance
     for that particular db if we really wanted to. There's no
     pressing need to keep that db on the same connection as the
     checkout/repo.
  */
  fsl_db dbMem;

  /**
     Holds info directly related to a checkout database.
  */
  struct {
    /**
       Holds the filename of the current checkout db and possibly
       related state. Historically (very historically) it could also







|


|
|
|
>
>
|
|
>
>
|



|





|

|
<
<
<
<
<
<
<
<









<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310








311
312
313
314
315
316
317
318
319





































320
321
322
323
324
325
326

/* The fsl_cx class is documented in main public header. */
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.

     As of this writing (20211231) the following
     applies:

     dbMain always points to the first one of this->repo.db or
     this->ckout.db which is opened. this->dbMain->role holds a
     bitmask of the role(s) which is/are connected (FSL_DBROLE_REPO
     and FSL_DBROLE_CKOUT, noting that we never open a checkout
     without its associated repo, but a repo without a checkout is a
     common use case).

     The first db which gets opened gets its name aliased to its
     fsl_db_role_name() value so that we needn't concern ourselves,
     from SQL code, with which db is "main".

     As of 20211230, f->config.db is its own handle, not ATTACHed with
     the others. Its db gets renamed to
     fsl_db_role_name(FSL_DBROLE_CONFIG).

     Internal code should rely as little as possible on the actual
     arrangement of internal DB handles, and should use
     fsl_cx_db_repo(), fsl_cx_db_ckout(), and fsl_cx_db_config() to
     get a handle to the specific db they want. Currently they will
     always return NULL or may return the same handle, but that design decision
     might change at some point, so the public API treats them as
     separate entities.








  */
  fsl_db * dbMain;

  /**
     Marker which tells us whether fsl_cx_finalize() needs
     to fsl_free() this instance or not.
  */
  void const * allocStamp;






































  /**
     Holds info directly related to a checkout database.
  */
  struct {
    /**
       Holds the filename of the current checkout db and possibly
       related state. Historically (very historically) it could also
750
751
752
753
754
755
756

757


758

759

760
761
762
763
764
765
766
767
768

       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 {

      fsl_stmt deltaSrcId;


      fsl_stmt uuidToRid;

      fsl_stmt uuidToRidGlob;

      fsl_stmt contentSize;
      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;







>

>
>

>

>

|







709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732

       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;
      fsl_stmt nextEntry/*placeholder*/;
    } 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;
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
/** @internal

    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*/        \
    },                                            \
    {/*repo*/ fsl_db_empty_m /*db*/,                  \
       0/*user*/                                     \







<







798
799
800
801
802
803
804

805
806
807
808
809
810
811
/** @internal

    Initialized-with-defaults fsl_cx struct.
*/
#define fsl_cx_empty_m {                                \
    NULL /*dbMain*/,                                    \
    NULL/*allocStamp*/,                               \

    {/*ckout*/                                        \
      fsl_db_empty_m /*db*/,                          \
      NULL /*dir*/, 0/*dirLen*/,                    \
      -1/*rid*/, NULL/*uuid*/, 0/*mtime*/        \
    },                                            \
    {/*repo*/ fsl_db_empty_m /*db*/,                  \
       0/*user*/                                     \
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313

/** @internal

    Clears and frees all (char*) members of db but leaves the rest
    intact. If alsoErrorState is true then the error state is also
    freed, else it is kept as well.
*/
void fsl__db_clear_strings(fsl_db * const db, bool alsoErrorState );

/** @internal

    Returns 0 if db appears to have a current repository schema, 1
    if it appears to have an out of date schema, and -1 if it
    appears to not be a repository. Results are undefined if db is
    NULL or not opened.
*/
int fsl__db_repo_verify_schema(fsl_db * db);


/** @internal

    Flags for APIs which add phantom blobs to the repository.  The
    values in this enum derive from fossil(1) code and should not be
    changed without careful forethought and (afterwards) testing.  A







|








|







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

/** @internal

    Clears and frees all (char*) members of db but leaves the rest
    intact. If alsoErrorState is true then the error state is also
    freed, else it is kept as well.
*/
void fsl__db_clear_strings(fsl_db * const db, bool alsoErrorState);

/** @internal

    Returns 0 if db appears to have a current repository schema, 1
    if it appears to have an out of date schema, and -1 if it
    appears to not be a repository. Results are undefined if db is
    NULL or not opened.
*/
int fsl__db_repo_verify_schema(fsl_db * const db);


/** @internal

    Flags for APIs which add phantom blobs to the repository.  The
    values in this enum derive from fossil(1) code and should not be
    changed without careful forethought and (afterwards) testing.  A
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
   to the db.
*/
int fsl__search_doc_touch(fsl_cx * const f, fsl_satype_e saType,
                         fsl_id_t rid, const char * docName);

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

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


/** @internal

   Installs or reinstalls the checkout database schema into f's open
   checkout db. Returns 0 on success, FSL_RC_NOT_A_CKOUT if f has
   no opened checkout, or an code if a lower-level operation fails.








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


















<







1649
1650
1651
1652
1653
1654
1655


















1656
1657

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

1676
1677
1678
1679
1680
1681
1682
   to the db.
*/
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.


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


/** @internal

   Installs or reinstalls the checkout database schema into f's open
   checkout db. Returns 0 on success, FSL_RC_NOT_A_CKOUT if f has
   no opened checkout, or an code if a lower-level operation fails.

2314
2315
2316
2317
2318
2319
2320
















































2321
2322
2323
2324
2325
2326
2327
   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

    Maximum length of a line in a text file, in bytes. (2**15 = 32k)
*/
#define FSL__LINE_LENGTH_MASK_SZ  15








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







2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
   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.
*/
void fsl__cx_clear_repo_caches(fsl_cx * const f);

/** @internal

    Returns one of the various fsl_db objects owned by f, or NULL.

    ACHTUNG and REMINDER TO SELF: the current (2021-12) design means
    that only, at most, the FSL_DBROLE_CONFIG and _one_ of
    FSL_DBROLE_REPO/FSL_DBROLE_CKOUT actually have an opened db handle.

    If passed FSL_DBROLE_MAIN, it will return whichever of the
    REPO/CKOUT dbs are OPENed (not ATTACHed), or NULL if neither is.

    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

   Plug in fsl_cx-specific db functionality into the given db handle.
   This must only be passed the MAIN db handle for the context and it
   must do so before f->dbMain is assigned. That is, db must be one of
   the REPOSITORY or CHECKOUT dbs (whichever gets opened first).
*/
int fsl__cx_init_db(fsl_cx * const f, fsl_db * const db);

/** @internal

    Opens or 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. createIfNotExists specifies to use open mode
    of FSL_OPEN_F_RWC instead of FSL_OPEN_F_RWC. Normally that is NOT
    what's desired.

    This function has very specific preconditions which are assert()ed.
    See the code for details.
*/
int fsl__cx_attach_role(fsl_cx * const f, const char *zDbName,
                        fsl_dbrole_e r, bool createIfNotExists);

/** @internal

    Maximum length of a line in a text file, in bytes. (2**15 = 32k)
*/
#define FSL__LINE_LENGTH_MASK_SZ  15

Changes to include/fossil-scm/repo.h.
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  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-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.
*/

#include "db.h" /* MUST come first b/c of config macros */







|







9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

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

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

#include "db.h" /* MUST come first b/c of config macros */
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
   which contains a checkin with the given rid, else it returns
   false.

   As a special case, if rid==0 then this only returns true
   if the repository currently has no content in the blob
   table.
*/
FSL_EXPORT char fsl_rid_is_a_checkin(fsl_cx * f, fsl_id_t rid);

/**
   Fetches the list of all directory names for a given checkin record
   id or (if rid is negative) the whole repo over all of its combined
   history. Each name entry in the list is appended to tgt. The
   results are reduced to unique names only and are sorted
   lexically. If addSlash is true then each entry will include a







|







2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
   which contains a checkin with the given rid, else it returns
   false.

   As a special case, if rid==0 then this only returns true
   if the repository currently has no content in the blob
   table.
*/
FSL_EXPORT char fsl_rid_is_a_checkin(fsl_cx * const f, fsl_id_t rid);

/**
   Fetches the list of all directory names for a given checkin record
   id or (if rid is negative) the whole repo over all of its combined
   history. Each name entry in the list is appended to tgt. The
   results are reduced to unique names only and are sorted
   lexically. If addSlash is true then each entry will include a
4031
4032
4033
4034
4035
4036
4037







































































































































































































































4038
4039
4040
4041
4042
4043
   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);








































































































































































































































#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_REPO_H_INCLUDED */







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






4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
   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 );

/**
   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() has been used to open a respository db, this
   call closes that db. If an associated checkout is opened, it is
   also closed, since a checkout is only valid with its associated
   repository.

   Returns 0 on success or if no 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.

   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_ckout_close()
   @see fsl_repo_create()
*/
FSL_EXPORT int fsl_repo_close( fsl_cx * const f );

/**
   UNTESTED.

   Returns true if f has an opened repository database which is
   opened in read-only mode, else returns false.
*/
FSL_EXPORT bool fsl_repo_is_readonly(fsl_cx const * f);


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_REPO_H_INCLUDED */
Changes to include/fossil-scm/util.h.
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

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

*/

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

#include "config.h" /* MUST come first b/c of config macros */







|







10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

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

*/

/** @file util.h

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

#include "config.h" /* MUST come first b/c of config macros */
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
   untransformed characters and the strlen of *xlate for others.
   Bytes returned via xlate are static and immutable.

   Results are undefined if xlate is NULL.
*/
FSL_EXPORT fsl_size_t fsl_htmlize_xlate(int c, char const ** xlate);

/**
   Flags for use with text-diff generation APIs,
   e.g. fsl_diff_text().

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








<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







3390
3391
3392
3393
3394
3395
3396


























































































































3397
3398
3399
3400
3401
3402
3403
   untransformed characters and the strlen of *xlate for others.
   Bytes returned via xlate are static and immutable.

   Results are undefined if xlate is NULL.
*/
FSL_EXPORT fsl_size_t fsl_htmlize_xlate(int c, char const ** xlate);




























































































































/** @enum fsl_diff2_flag_e

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

Changes to include/libfossil.h.
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  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.
*/








|







8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  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 libfossil.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.
*/

31
32
33
34
35
36
37

38
39
40
#include "fossil-scm/repo.h"
#include "fossil-scm/checkout.h"
#include "fossil-scm/confdb.h"
#include "fossil-scm/hash.h"
#include "fossil-scm/auth.h"
#include "fossil-scm/vpath.h"
#include "fossil-scm/cli.h"


#endif
/* ORG_FOSSIL_SCM_LIBFOSSIL_H_INCLUDED */







>



31
32
33
34
35
36
37
38
39
40
41
#include "fossil-scm/repo.h"
#include "fossil-scm/checkout.h"
#include "fossil-scm/confdb.h"
#include "fossil-scm/hash.h"
#include "fossil-scm/auth.h"
#include "fossil-scm/vpath.h"
#include "fossil-scm/cli.h"
#include "fossil-scm/deprecated.h"

#endif
/* ORG_FOSSIL_SCM_LIBFOSSIL_H_INCLUDED */
Changes to make-libf.make.in.
260
261
262
263
264
265
266
267

268
269
270
271
272
273
274
	$(DIR.inc-fossil)/checkout.h \
	$(DIR.inc-fossil)/confdb.h \
	$(DIR.inc-fossil)/vpath.h \
	$(DIR.inc-fossil)/internal.h \
	$(DIR.inc-fossil)/auth.h \
	$(DIR.inc-fossil)/forum.h \
	$(DIR.inc-fossil)/pages.h \
	$(DIR.inc-fossil)/cli.h

$(libfossil.h.SRC):
$(libfossil.c.SRC):
libfossil.h_MAKEFILES := $(filter-out $(ShakeNMake.CISH_DEPS_FILE),$(MAKEFILE_LIST))
$(libfossil.h): $(libfossil.h_MAKEFILES) $(libfossil.h.SRC) $(libfossil-config.h)
$(libfossil.c): $(libfossil.h_MAKEFILES) $(libfossil.h) $(libfossil.c.SRC)
$(libfossil-config.h): $(libfossil.h_MAKEFILES)
	@echo "Generating $@ ..."







|
>







260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
	$(DIR.inc-fossil)/checkout.h \
	$(DIR.inc-fossil)/confdb.h \
	$(DIR.inc-fossil)/vpath.h \
	$(DIR.inc-fossil)/internal.h \
	$(DIR.inc-fossil)/auth.h \
	$(DIR.inc-fossil)/forum.h \
	$(DIR.inc-fossil)/pages.h \
	$(DIR.inc-fossil)/cli.h \
	$(DIR.inc-fossil)/deprecated.h
$(libfossil.h.SRC):
$(libfossil.c.SRC):
libfossil.h_MAKEFILES := $(filter-out $(ShakeNMake.CISH_DEPS_FILE),$(MAKEFILE_LIST))
$(libfossil.h): $(libfossil.h_MAKEFILES) $(libfossil.h.SRC) $(libfossil-config.h)
$(libfossil.c): $(libfossil.h_MAKEFILES) $(libfossil.h) $(libfossil.c.SRC)
$(libfossil-config.h): $(libfossil.h_MAKEFILES)
	@echo "Generating $@ ..."
Changes to src/auth.c.
15
16
17
18
19
20
21
22

23
24
25
26
27
28
29
  This file contains routines related to working with user authentication.
*/
#include "fossil-scm/internal.h"
#include "fossil-scm/hash.h"
#include "fossil-scm/confdb.h"


FSL_EXPORT char * fsl_sha1_shared_secret( fsl_cx * f, char const * zLoginName,

                                          char const * zPw ){
    if(!f || !zPw || !zLoginName) return 0;
    else{
        fsl_sha1_cx hash = fsl_sha1_cx_empty;
        unsigned char zResult[20];
        char zDigest[41];
        if(!f->cache.projectCode){







|
>







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  This file contains routines related to working with user authentication.
*/
#include "fossil-scm/internal.h"
#include "fossil-scm/hash.h"
#include "fossil-scm/confdb.h"


FSL_EXPORT char * fsl_sha1_shared_secret( fsl_cx * const f,
                                          char const * zLoginName,
                                          char const * zPw ){
    if(!f || !zPw || !zLoginName) return 0;
    else{
        fsl_sha1_cx hash = fsl_sha1_cx_empty;
        unsigned char zResult[20];
        char zDigest[41];
        if(!f->cache.projectCode){
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        fsl_sha1_update(&hash, zPw, fsl_strlen(zPw));
        fsl_sha1_final(&hash, zResult);
        fsl_sha1_digest_to_base16(zResult, zDigest);
        return fsl_strndup( zDigest, FSL_STRLEN_SHA1 );
    }
}

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

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

FSL_EXPORT int fsl_repo_login_search_uid(fsl_cx * f, char const * zUsername,
                                         char const * zPasswd,
                                         fsl_id_t * userId){
  int rc;
  char * zSecret;
  fsl_db * db;
  if(!f || !userId
     || !zUsername || !*zUsername







|






|












|







47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
        fsl_sha1_update(&hash, zPw, fsl_strlen(zPw));
        fsl_sha1_final(&hash, zResult);
        fsl_sha1_digest_to_base16(zResult, zDigest);
        return fsl_strndup( zDigest, FSL_STRLEN_SHA1 );
    }
}

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

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

FSL_EXPORT int fsl_repo_login_search_uid(fsl_cx * const f, char const * zUsername,
                                         char const * zPasswd,
                                         fsl_id_t * userId){
  int rc;
  char * zSecret;
  fsl_db * db;
  if(!f || !userId
     || !zUsername || !*zUsername
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
                     "   AND login NOT IN ('anonymous','nobody','developer','reader')"
                     "   AND (pw=%Q OR (length(pw)<>40 AND pw=%Q))",
                     zUsername, zSecret, zPasswd);
  fsl_free(zSecret);
  return rc;
}

FSL_EXPORT int fsl_repo_login_clear( fsl_cx * f, fsl_id_t userId ){
  fsl_db * db;
  if(!f) return FSL_RC_MISUSE;
  else if(!(db = fsl_needs_repo(f))) return FSL_RC_NOT_A_REPO;
  else{
    int const rc = fsl_db_exec(db,
                       "UPDATE user SET cookie=NULL, ipaddr=NULL, "
                       " cexpire=0 WHERE "







|







95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
                     "   AND login NOT IN ('anonymous','nobody','developer','reader')"
                     "   AND (pw=%Q OR (length(pw)<>40 AND pw=%Q))",
                     zUsername, zSecret, zPasswd);
  fsl_free(zSecret);
  return rc;
}

FSL_EXPORT int fsl_repo_login_clear( fsl_cx * const f, fsl_id_t userId ){
  fsl_db * db;
  if(!f) return FSL_RC_MISUSE;
  else if(!(db = fsl_needs_repo(f))) return FSL_RC_NOT_A_REPO;
  else{
    int const rc = fsl_db_exec(db,
                       "UPDATE user SET cookie=NULL, ipaddr=NULL, "
                       " cexpire=0 WHERE "
Changes to src/checkout.c.
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
  };
  int rc;
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return f->error.code;
  if(dropIfExists){
    char const * t;
    int i;
    char const * dbName = fsl_db_role_label(FSL_DBROLE_CKOUT);
    for(i=0; 0!=(t = tNames[i]); ++i){
      rc = fsl_db_exec(db, "DROP TABLE IF EXISTS %s.%s /*%s()*/",
                       dbName, t, __func__);
      if(rc) break;
    }
    if(!rc){
      rc = fsl_db_exec(db, "DROP TRIGGER IF EXISTS "







|







675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
  };
  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);
    for(i=0; 0!=(t = tNames[i]); ++i){
      rc = fsl_db_exec(db, "DROP TABLE IF EXISTS %s.%s /*%s()*/",
                       dbName, t, __func__);
      if(rc) break;
    }
    if(!rc){
      rc = fsl_db_exec(db, "DROP TRIGGER IF EXISTS "
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
                           "DELETE FROM vfile;"
                           "DELETE FROM vmerge;"
                           "DELETE FROM vvar WHERE name IN"
                           "('checkout','checkout-hash') "
                           "/*%s()*/", __func__);
}

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

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







<
<
<









|







738
739
740
741
742
743
744



745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
                           "DELETE FROM vfile;"
                           "DELETE FROM vmerge;"
                           "DELETE FROM vvar WHERE name IN"
                           "('checkout','checkout-hash') "
                           "/*%s()*/", __func__);
}




/**
   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);
  assert(dbC->filename);
  assert(*dbC->filename);
  rc = fsl_file_canonical_name(dbC->filename, &ckDir, false);
  if(rc) return rc;
  char * zCanon = fsl_buffer_take(&ckDir);
  //MARKER(("dbC->filename=%s\n", dbC->filename));
  //MARKER(("zCanon=%s\n", zCanon));
843
844
845
846
847
848
849
850





851







852
853
854
855
856
857
858
859
860
861
862
  /**
     Create and attach ckout db...
  */
  assert(!fsl_cx_db_ckout(f));
  const char * dbName = opt->ckoutDbFile
    ? opt->ckoutDbFile : fsl_preferred_ckout_db_name();
  fsl_cx_err_reset(f);
  int fsl_cx_attach_role(fsl_cx * const , const char *, fsl_dbrole_e)





    /* defined in cx.c */;







  rc = fsl_cx_attach_role(f, dbName, FSL_DBROLE_CKOUT);
  if(rc) goto end;
  fsl_db * const theDbC = fsl_cx_db_ckout(f);
  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);
  if(!rc){







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


|







840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
  /**
     Create and attach ckout db...
  */
  assert(!fsl_cx_db_ckout(f));
  const char * dbName = opt->ckoutDbFile
    ? opt->ckoutDbFile : fsl_preferred_ckout_db_name();
  fsl_cx_err_reset(f);

#if 0
  if(!fsl_is_file(dbName)){
    /* A bit of an ugly workaround: create an empty file, if needed,
       so that the following ATTACH can work. */
    FILE * const fi = fsl_fopen(dbName, "w");
    if(!fi){
      rc = fsl_cx_err_set(f, FSL_RC_IO, "Cannot create new checkout db: %s",
                          dbName);
      goto end;
    }
    fsl_fclose(fi);
  }  
#endif
  rc = fsl__cx_attach_role(f, dbName, FSL_DBROLE_CKOUT, true);
  if(rc) goto end;
  fsl_db * const theDbC = fsl_cx_db_ckout(f);
  dbC = fsl__cx_db_for_role(f, FSL_DBROLE_CKOUT);
  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);
  if(!rc){
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
  end:
  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);
    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);







|







879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
  end:
  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);
    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);
Changes to src/cx.c.
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    fsl__cx_reset(*tgt, true) /* just to be safe */;
    f = *tgt;
    *f = fsl_cx_empty;
    f->allocStamp = allocStamp;
  }else{
    f = fsl_cx_malloc();
    if(!f) return FSL_RC_OOM;

    *tgt = f;
  }
  memset(&f->cache.mcache, 0, sizeof(f->cache.mcache));
  f->output = param->output;
  f->cxConfig = param->config;

  enum {







<







100
101
102
103
104
105
106

107
108
109
110
111
112
113
    fsl__cx_reset(*tgt, true) /* just to be safe */;
    f = *tgt;
    *f = fsl_cx_empty;
    f->allocStamp = allocStamp;
  }else{
    f = fsl_cx_malloc();
    if(!f) return FSL_RC_OOM;

    *tgt = f;
  }
  memset(&f->cache.mcache, 0, sizeof(f->cache.mcache));
  f->output = param->output;
  f->cxConfig = param->config;

  enum {
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

178




179

180
181
182
183
184
185
186





187

188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
      /* Clean up pseudo-leak valgrind complains about:
         https://www.sqlite.org/c3ref/auto_extension.html */;
  }
#endif
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
  f->dbMem.f = f;
  rc = fsl_db_open( &f->dbMem, "", 0 );
  if(!rc){
    extern int fsl__cx_init_db(fsl_cx * const, fsl_db * const);
    rc = fsl__cx_init_db(f, &f->dbMem);
  }
  if(!rc) rc = fsl__cx_install_timeline_crosslinkers(f);
  if(!rc){
    f->cache.tempDirs = fsl_temp_dirs_get();
    if(!f->cache.tempDirs) rc = FSL_RC_OOM;

  }
  return rc;
}

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

static void fsl__cx_reset(fsl_cx * const f, bool closeDatabases){

  fsl_checkin_discard(f);




#define SFREE(X) fsl_free(X); X = NULL

#define STMT(X) fsl_stmt_finalize(&f->cache.stmt.X)
  STMT(deltaSrcId);
  STMT(uuidToRid);
  STMT(uuidToRidGlob);
  STMT(contentSize);
  STMT(nextEntry);
#undef STMT





  if(closeDatabases){

    fsl_cx_close_dbs(f);
    /*
      Reminder: f->dbMem is NOT closed here: it's an internal detail,
      not public state. We could arguably close and reopen it here,
      but then we introduce a potenital error case (OOM) where we
      currently have none (thus the void return).

      2021-11-09: it turns out we've had an error case all along
      here: if any cached statements are opened for one of the dbs,
      that can prohibit its detachement.
    */
    SFREE(f->ckout.dir);
    f->ckout.dirLen = 0;
    /* assert(NULL==f->dbMain); */
  }
  SFREE(f->repo.user);
  SFREE(f->ckout.uuid);
  SFREE(f->cache.projectCode);
  SFREE(f->ticket.titleColumn);
  SFREE(f->ticket.statusColumn);
#undef SFREE







<
<

<
<
<
|
|
|
|
>














|
>
|
>
>
>
>
|
>







>
>
>
>
>

>

<
<
<
<
<
<
<
<
<
<


|







145
146
147
148
149
150
151


152



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195










196
197
198
199
200
201
202
203
204
205
      /* Clean up pseudo-leak valgrind complains about:
         https://www.sqlite.org/c3ref/auto_extension.html */;
  }
#endif
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif


  if(!rc){



    rc = fsl__cx_install_timeline_crosslinkers(f);
    if(!rc){
      f->cache.tempDirs = fsl_temp_dirs_get();
      if(!f->cache.tempDirs) rc = FSL_RC_OOM;
    }
  }
  return rc;
}

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);
  f->cache.allowSymlinks =
    f->cache.caseInsensitive =
    f->cache.seenDeltaManifest = -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(nextEntry);
#undef STMT
}

static void fsl__cx_reset(fsl_cx * const f, bool closeDatabases){
  fsl_checkin_discard(f);
#define SFREE(X) fsl_free(X); X = NULL
  if(closeDatabases){
    fsl__cx_finalize_cached_stmt(f);
    fsl_cx_close_dbs(f);










    SFREE(f->ckout.dir);
    f->ckout.dirLen = 0;
    assert(NULL==f->dbMain);
  }
  SFREE(f->repo.user);
  SFREE(f->ckout.uuid);
  SFREE(f->cache.projectCode);
  SFREE(f->ticket.titleColumn);
  SFREE(f->ticket.statusColumn);
#undef SFREE
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
    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;
  }








<







244
245
246
247
248
249
250

251
252
253
254
255
256
257
    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);

  *f = fsl_cx_empty;
  if(&fsl_cx_empty == allocStamp){
    fsl_free(f);
  }else{
    f->allocStamp = allocStamp;
  }

274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
}

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

int fsl_cx_err_set_e( fsl_cx * const f, fsl_error * const err ){
  if(!f) return FSL_RC_MISUSE;







<







270
271
272
273
274
275
276

277
278
279
280
281
282
283
  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
}

void fsl_cx_err_reset(fsl_cx * const f){
  //f->interrupted = 0; // No! ONLY modify this via fsl_cx_interrupt()
  fsl_error_reset(&f->error);

  fsl_db_err_reset(&f->repo.db);
  fsl_db_err_reset(&f->config.db);
  fsl_db_err_reset(&f->ckout.db);
}

int fsl_cx_err_set_e( fsl_cx * const f, fsl_error * const err ){
  if(!f) return FSL_RC_MISUSE;
379
380
381
382
383
384
385
386


387


388
389

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


442
443
444
445
446
447
448
449
450
451
452
453

454



455
456
457
458


459
460
461





462



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529

530
531
532
533
534
535
536


537
538
539
540
541
542
543

544
545
546
547
548
549
550
551









552

553
554
555























556
557
558


559
560
561
562
563
564
565
566
567
568
569



570
571
572


573
574

575

576
577
578

579

580






581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597



598




599
600
601

602
603
604
605
606
607

608
609
610

611



612
613
614
615
616
617
618
619
620
621
622
623
624

625
626
627
628
629
630
631

632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
}

fsl_db * fsl_cx_db_config( fsl_cx * const f ){
  return f->config.db.dbh ? &f->config.db : NULL;
}

fsl_db * fsl_cx_db_repo( fsl_cx * const f ){
  if(f->dbMain && (FSL_DBROLE_REPO & f->dbMain->role)) return f->dbMain;


  else if(f->repo.db.dbh) return &f->repo.db;


  else return NULL;
}


fsl_db * fsl_needs_repo(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_repo(f);
  if(!db){
    fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                   "Fossil context has no opened repository db.");
  }
  return db;
}

fsl_db * fsl_needs_ckout(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_ckout(f);
  if(!db){
    fsl_cx_err_set(f, FSL_RC_NOT_A_CKOUT,
                   "Fossil context has no opened checkout db.");
  }
  return db;
}

fsl_db * fsl_cx_db_ckout( fsl_cx * const f ){
  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;
}
/** @internal

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

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

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


    case FSL_DBROLE_NONE:
    default:
      return NULL;
  }
}

/**
    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){
  assert(FSL_DBROLE_CONFIG!=r && "Config db now has its own handle.");

  if(NULL==f->dbMain) return FSL_RC_MISUSE;



  else if(!(r & f->dbMain->role)){
    assert(!"Misuse: cannot detach unattached role.");
    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. 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;
        fsl__db_clear_strings(db, true);
      }
    }
    return rc;
  }
}


/** @internal

    Attaches the given db file to f with the given role. This function "should"
    be static but we need it in fsl_repo.c when creating a new repository.
*/
int fsl_cx_attach_role(fsl_cx * const f, const char *zDbName,
                       fsl_dbrole_e r){
  char const * label = fsl_db_role_label(r);
  fsl_db * const db = fsl_cx_db_for_role(f, r);
  char ** nameDest = NULL;
  int rc;
  assert(FSL_DBROLE_CONFIG!=r && "Config db now has its own handle.");
  if(!f->dbMain){
    fsl__fatal(FSL_RC_MISUSE,"Internal API misuse: f->dbMain has "
              "not been set, so cannot attach role.");
    return FSL_RC_MISUSE;
  }
  else if(r & f->dbMain->role){
    assert(!"Misuse: role is already attached.");
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Db role %s is already attached.",
                          label);                          
  }
#if 0
  MARKER(("r=%s db=%p, ckout.db=%p\n", label,
          (void*)db, (void*)&f->ckout.db));
  MARKER(("r=%s db=%p, repo.db=%p\n", label,
          (void*)db, (void*)&f->repo.db));
  MARKER(("r=%s db=%p, dbMain=%p\n", label,
          (void*)db, (void*)f->dbMain));
#endif
  assert(db);
  assert(label);
  assert(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_MAIN:
    case FSL_DBROLE_NONE:
    default:
      assert(!"cannot happen/not legal");
      return FSL_RC_RANGE;
  }
  *nameDest = fsl_strdup(zDbName);


  db->name = *nameDest ? fsl_strdup(label) : NULL;
  if(!db->name){
    rc = FSL_RC_OOM;
    /* Design note: we do the strdup() before the ATTACH because if
       the attach succeeds and strdup fails, detaching the db will
       almost certainly fail because it must allocate for its prepared
       statement and other internals. We would end up having to leave

       the db attached and returning a failure, which could lead to a
       memory leak (or worse) downstream.
    */
  }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;
}

void fsl_config_close( fsl_cx * const f ){
  fsl_db_close(&f->config.db);
}

int fsl_repo_close( fsl_cx * const 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);
    f->cache.allowSymlinks =
      f->cache.caseInsensitive =
      f->cache.seenDeltaManifest = -1;
    return rc;
  }
}

int fsl_ckout_close( fsl_cx * const f ){
  if(fsl_cx_transaction_level(f)){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close checkout with opened transaction.");



  }else{




    int rc = 0;
    fsl_db * const db = &f->ckout.db;
    if(f->dbMain && (FSL_DBROLE_CKOUT & f->dbMain->role)){

      /* Checkout db is ATTACHed. */
      rc = fsl_cx_detach_role(f, FSL_DBROLE_CKOUT);
      fsl_repo_close(f)
        /* Because the repo is implicitly opened, we "should"
           implicitly close it. This is debatable but "probably almost
           always" desired. i can't currently envisage a reasonable

           use-case which requires closing the checkout but keeping
           the repo opened.  The repo can always be re-opened by
           itself. */;

    }else{



      fsl_db_close(db);
    }
    fsl_free(f->ckout.uuid);
    f->ckout.uuid = NULL;
    f->ckout.rid = 0;
    assert(!db->dbh);
    return rc;
  }
}

/**
   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){
  /* char *zVFileDef; */
  int rc;
  fsl_int_t const lsize = fsl_file_size(zDbName);
  if( -1 == lsize  ){
    return FSL_RC_NOT_FOUND /* might be FSL_RC_ACCESS? */;

  }
  if( lsize%1024!=0 || lsize<4096 ){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "File's size is not correct for a "
                          "checkout db: %s",
                          zDbName);
  }
  rc = fsl_cx_attach_role(f, zDbName, FSL_DBROLE_CKOUT);
  return rc;
}


int fsl_cx_execv( fsl_cx * const f, char const * sql, va_list args ){
  int const rc = (f->dbMain && sql)
    ? fsl_db_execv(f->dbMain, sql, args)







|
>
>
|
>
>
|

>



















<
<
<
<
<
<



<

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








|
>
>










|

>
|
>
>
>


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












<
<
<
<
<
<
|
|
|
|
<

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













<

<



>






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

>
>
>
>
>
>
>
>
>
|
>

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










|
>
>
>


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

<
<

<
|
<
<







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


|
>

|




|
>


|




|







374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408






409
410
411

412












413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444

445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462






463
464
465
466
467
468
469
470
471
472
473
474
475
476






477
478
479
480

481


482


483






484
485
486
487
488
489
490
491
492
493
494
495
496

497

498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513



514
515
516
517
518
519


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

534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587


588
589
590
591
592
593
594
595
596
597
598
599


600

601


602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619

620
621

622



623
624
625
626
627
628
629
630
631
632
633




634
635
636

637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
}

fsl_db * fsl_cx_db_config( fsl_cx * const f ){
  return f->config.db.dbh ? &f->config.db : NULL;
}

fsl_db * fsl_cx_db_repo( fsl_cx * const f ){
  return f->dbMain && (f->dbMain->role & FSL_DBROLE_REPO)
    ? f->dbMain : NULL;
}

fsl_db * fsl_cx_db_ckout( fsl_cx * const f ){
  return f->dbMain && (f->dbMain->role & FSL_DBROLE_CKOUT)
    ? f->dbMain : NULL;
}


fsl_db * fsl_needs_repo(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_repo(f);
  if(!db){
    fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                   "Fossil context has no opened repository db.");
  }
  return db;
}

fsl_db * fsl_needs_ckout(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_ckout(f);
  if(!db){
    fsl_cx_err_set(f, FSL_RC_NOT_A_CKOUT,
                   "Fossil context has no opened checkout db.");
  }
  return db;
}







fsl_db * fsl_cx_db( fsl_cx * const f ){
  return f->dbMain;
}














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->repo.db.dbh
        ? &f->repo.db
        : (f->ckout.db.dbh ? &f->ckout.db : NULL);
    case FSL_DBROLE_NONE:
    default:
      return NULL;
  }
}

/**
    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){
  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){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close/detach db: none opened.");
  }
  else if(!(r & f->dbMain->role)){
    assert(!"Misuse: cannot detach unattached role.");
    return fsl_cx_err_set(f, FSL_RC_NOT_A_CKOUT,

                          "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;
    fsl__cx_finalize_cached_stmt(f);
    if(db->dbh){
      /* This is our MAIN db. CLOSE it. If we still have a secondary
         db open, this will cause Grief later on. TODO: assert that
         our secondary db is not still attached. */
      assert(f->dbMain == db);
      fsl_db_close(db);
      f->dbMain = NULL;
    }else{// This is our secondary db. DETACH it.
      assert(f->dbMain != db);
      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. */;    






      rc = fsl_db_detach( f->dbMain, fsl_db_role_name(r) );
      //MARKER(("rc=%s %s %s\n", fsl_rc_cstr(rc), fsl_db_role_name(r),
      //        fsl_buffer_cstr(&f->dbMain->error.msg)));
      if(rc){
        fsl_cx_uplift_db_error(f, f->dbMain);
      }else{
        f->dbMain->role &= ~r;
        fsl__db_clear_strings(db, true);
      }
    }
    return rc;
  }
}







int fsl__cx_attach_role(fsl_cx * const f, const char *zDbName,
                        fsl_dbrole_e r, bool createIfNotExists){
  char const * label = fsl_db_role_name(r);
  fsl_db * const db = fsl__cx_db_for_role(f, r);

  int rc;


  assert(!db->dbh && "Internal API misuse: don't call this when db is connected.");


  






#if 0
  MARKER(("r=%s db=%p, ckout.db=%p\n", label,
          (void*)db, (void*)&f->ckout.db));
  MARKER(("r=%s db=%p, repo.db=%p\n", label,
          (void*)db, (void*)&f->repo.db));
  MARKER(("r=%s db=%p, dbMain=%p\n", label,
          (void*)db, (void*)f->dbMain));
#endif
  assert(db);
  assert(label);
  assert(f->dbMain != db);
  assert(!db->filename);
  assert(!db->name);

  switch(r){

    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");
      return FSL_RC_RANGE;
  }
  db->f = f;
  if(!f->dbMain){
    // This is our first/main db. OPEN it.
    db->name = fsl_strdup(label);
    if(!db->name){
      rc = FSL_RC_OOM;



      goto end;
    }
    rc = fsl_db_open( db, zDbName, createIfNotExists
                      ? FSL_OPEN_F_RWC : FSL_OPEN_F_RW
                      /* ^^^ RWC is not really what we want here (RW
                         is preferred), but RWC is currently required


                         for fsl_repo_create(). */);
    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,
                                       label);
    if(sqrc){
      rc = fsl__db_errcode(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);
      /* Should we fsl__cx_detach_role() here? */
    }
  }else{
    // This is our secondary db. ATTACH it.
    assert(db != f->dbMain);
    db->filename = fsl_strdup(zDbName);
    db->name = db->filename ? fsl_strdup(label) : NULL;
    if(!db->name){
      rc = FSL_RC_OOM;
    }else{
      //MARKER(("db is r/o? %s %s %d\n", f->dbMain->name, f->dbMain->filename,
      //        sqlite3_db_readonly(f->dbMain->dbh, f->dbMain->name)));
      //rc = fsl_cx_exec(f, "attach %Q as %Q;", zDbName, label);
      //MARKER(("fsl_db_exec(...) rc=%s\n", fsl_rc_cstr(rc)));
      rc = fsl_db_attach(f->dbMain, zDbName, label);
      //MARKER(("fsl_db_attach(...,%s,%s) rc=%s\n", zDbName, label, fsl_rc_cstr(rc)));
      if(rc){
        fsl_cx_uplift_db_error2(f, f->dbMain, rc);
      }else{
        /*MARKER(("Attached %p role %d %s %s\n",
          (void const *)db, r, db->name, db->filename));*/
        f->dbMain->role |= r;
      }
    }
  }
  end:
  return rc;
}

void fsl_config_close( fsl_cx * const f ){
  fsl_db_close(&f->config.db);
}

int fsl_repo_close( fsl_cx * const f ){
  if(fsl_cx_transaction_level(f)){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close repository with an "
                          "opened transaction.");
  }else if(!fsl_cx_db_repo(f)){
    return 0;
  }else{
    int rc = 0;
    if(f->ckout.db.dbh){
      /* Repo/checkout pairs are (almost) always opened checkout-first,
         the exception being fsl_repo_ckout_open(). */
      assert(f->dbMain == &f->ckout.db);
      /* Repo db is ATTACHed to checkout. Need to detach repo before
         closing checkout. */
      rc = fsl__cx_detach_role(f, FSL_DBROLE_REPO);
      if(0==rc){
        rc = fsl__cx_detach_role(f, FSL_DBROLE_CKOUT);


      }
    }else{
      fsl_db * const dbC = fsl_cx_db_ckout(f);
      assert(&f->repo.db == f->dbMain);
      if(dbC){
        /* Checkout is ATTACHed to the repo. Need to detach it before
           closing repo. */
        rc = fsl__cx_detach_role(f, FSL_DBROLE_CKOUT);
      }
      if(0==rc){
        rc = fsl__cx_detach_role(f, FSL_DBROLE_REPO);
      }


    }

    fsl__cx_clear_repo_caches(f);


    return rc;
  }
}

int fsl_ckout_close( fsl_cx * const f ){
  if(fsl_cx_transaction_level(f)){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close checkout with an "
                          "opened transaction.");
  }else if(!fsl_cx_db_ckout(f)){
    return 0;
  }else if(f->repo.db.dbh){
    assert(!"Can't happen: repo is MAIN w/ a repo/ckout pair?!?");
    fsl__fatal(FSL_RC_MISUSE,"Can't happen: repo is MAIN w/ "
               "a repo/ckout pair?!?");
  }
  int rc;
  if(fsl_cx_db_repo(f)){

    /* We're part of a repo/checkout pair (as it should be). Close
       both. */

    rc = fsl_repo_close(f) /* will close both */;



    if(0==rc){
      assert(!f->ckout.db.dbh);
      assert(!f->repo.db.dbh);
      assert(!f->dbMain);
    }
  }else{
    /* This case "really shouldn't" happen: an opened checkout without
       an associated repo. For the sake of completeness, though... */
    assert(f->dbMain && (f->dbMain->role & FSL_DBROLE_CKOUT));
    rc = fsl__cx_detach_role(f, FSL_DBROLE_CKOUT);
  }




  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 and
   update f's error state.
*/
static int fsl__cx_ckout_open_db(fsl_cx * const f, const char *zDbName){
  /* char *zVFileDef; */
  int rc;
  fsl_int_t const lsize = fsl_file_size(zDbName);
  if( -1 == lsize  ){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND /* might be FSL_RC_ACCESS? */,
                          "Cannot stat() db file [%s].", zDbName);
  }
  if( lsize%1024!=0 || lsize<4096 ){
    return fsl_cx_err_set(f, FSL_RC_CONSISTENCY,
                          "File's size is not correct for a "
                          "checkout db: %s",
                          zDbName);
  }
  rc = fsl__cx_attach_role(f, zDbName, FSL_DBROLE_CKOUT, false);
  return rc;
}


int fsl_cx_execv( fsl_cx * const f, char const * sql, va_list args ){
  int const rc = (f->dbMain && sql)
    ? fsl_db_execv(f->dbMain, sql, args)
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
    schema's tables.
 */
static int fsl_config_file_reset(fsl_cx * const f, char const * dbName){
  fsl_db DB = fsl_db_empty;
  fsl_db * db = &DB;
  int rc = 0;
  bool isAttached = false;
  const char * zPrefix = fsl_db_role_label(FSL_DBROLE_CONFIG);
  if(-1 != fsl_file_size(dbName)){
    rc = fsl_file_unlink(dbName);
    if(rc){
      return fsl_cx_err_set(f, rc,
                            "Error %s while removing old config file (%s)",
                            fsl_rc_cstr(rc), dbName);
    }
  }
  /**
     Hoop-jumping: because the schema file has a cfg. prefix for the
     table(s), and we cannot assign an arbitrary name to an open()'d
     db, we first open the db (making the the "main" db), then
     ATTACH it to itself to provide the fsl_db_role_label() alias.
  */
  rc = fsl_db_open(db, dbName, FSL_OPEN_F_RWC);
  if(rc) goto end;
  rc = fsl_db_attach(db, dbName, zPrefix);
  if(rc) goto end;
  isAttached = true;
  rc = fsl_db_exec_multi(db, "%s", fsl_schema_config());







|












|







736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
    schema's tables.
 */
static int fsl_config_file_reset(fsl_cx * const f, char const * dbName){
  fsl_db DB = fsl_db_empty;
  fsl_db * db = &DB;
  int rc = 0;
  bool isAttached = false;
  const char * zPrefix = fsl_db_role_name(FSL_DBROLE_CONFIG);
  if(-1 != fsl_file_size(dbName)){
    rc = fsl_file_unlink(dbName);
    if(rc){
      return fsl_cx_err_set(f, rc,
                            "Error %s while removing old config file (%s)",
                            fsl_rc_cstr(rc), dbName);
    }
  }
  /**
     Hoop-jumping: because the schema file has a cfg. prefix for the
     table(s), and we cannot assign an arbitrary name to an open()'d
     db, we first open the db (making the the "main" db), then
     ATTACH it to itself to provide the fsl_db_role_name() alias.
  */
  rc = fsl_db_open(db, dbName, FSL_OPEN_F_RWC);
  if(rc) goto end;
  rc = fsl_db_attach(db, dbName, zPrefix);
  if(rc) goto end;
  isAttached = true;
  rc = fsl_db_exec_multi(db, "%s", fsl_schema_config());
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
  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_label(FSL_DBROLE_CONFIG));
    if(sqrc) rc = fsl__db_errcode(&f->config.db, sqrc);
  }
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, &f->config.db, rc);
    fsl_db_close(&f->config.db);
  }
  end:







|







870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
  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);
  }
  end:
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
  }else{
    int rc;
    if(0!=fsl_file_access( repoDbFile, F_OK )){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Repository db [%s] not found or cannot be read.",
                          repoDbFile);
    }else{
      rc = fsl_cx_attach_role(f, repoDbFile, FSL_DBROLE_REPO);
      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);







|







1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
  }else{
    int rc;
    if(0!=fsl_file_access( repoDbFile, F_OK )){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Repository db [%s] not found or cannot be read.",
                          repoDbFile);
    }else{
      rc = fsl__cx_attach_role(f, repoDbFile, FSL_DBROLE_REPO, false);
      if(!rc && !(FSL_CX_F_IS_OPENING_CKOUT & f->flags)){
        rc = fsl_cx_after_open(f);
      }
      if(!rc){
        fsl_db * const db = fsl_cx_db_repo(f);
        fsl_cx_username_from_repo(f);
        fsl_cx_allows_symlinks(f, true);
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046

1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067

1068


1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082



1083
1084
1085
1086
1087
1088
1089
  }
}

/**
    Tries to open the repository from which the current checkout
    derives. Returns 0 on success.
*/
static int fsl_repo_open_for_ckout(fsl_cx * f){
  char * repoDb = NULL;
  int rc;
  fsl_buffer nameBuf = fsl_buffer_empty;

  fsl_db * db = fsl_cx_db_ckout(f);
  assert(f);
  assert(f->ckout.dir);
  assert(db);
  rc = fsl_db_get_text(db, &repoDb, NULL,
                       "SELECT value FROM vvar "
                       "WHERE name='repository'");
  if(rc) fsl_cx_uplift_db_error( f, db );
  else if(repoDb){
    if(!fsl_is_absolute_path(repoDb)){
      /* Make it relative to the checkout db dir */
      rc = fsl_buffer_appendf(&nameBuf, "%s/%s", f->ckout.dir, repoDb);
      fsl_free(repoDb);
      if(rc) {
        fsl_buffer_clear(&nameBuf);
        return rc;
      }
      repoDb = (char*)nameBuf.mem /* transfer ownership */;
      nameBuf = fsl_buffer_empty;
    }
    rc = fsl_file_canonical_name(repoDb, &nameBuf, 0);

    fsl_free(repoDb);


    if(!rc){
      repoDb = fsl_buffer_str(&nameBuf);
      assert(repoDb);
      rc = fsl_repo_open(f, repoDb);
    }
    fsl_buffer_reserve(&nameBuf, 0);
  }else{
    /* This can only happen if we are not using a proper
       checkout db or someone has removed the repo link.
    */
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "Could not determine this checkout's "
                        "repository db file.");
  }



  return rc;
}

static void fsl_ckout_mtime_set(fsl_cx * const f){
  f->ckout.mtime = f->ckout.rid>0
    ? fsl_db_g_double(fsl_cx_db_repo(f), 0.0,
                      "SELECT mtime FROM event "







|


|
>











|

|
<
<
<
<
|

|
>
|
>
>

<
<
|

<








>
>
>







1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078




1079
1080
1081
1082
1083
1084
1085
1086


1087
1088

1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
  }
}

/**
    Tries to open the repository from which the current checkout
    derives. Returns 0 on success.
*/
static int fsl_repo_open_for_ckout(fsl_cx * const f){
  char * repoDb = NULL;
  int rc;
  fsl_buffer * const nameCanon = fsl__cx_scratchpad(f);
  fsl_buffer * const repoDbAbs = fsl__cx_scratchpad(f);
  fsl_db * db = fsl_cx_db_ckout(f);
  assert(f);
  assert(f->ckout.dir);
  assert(db);
  rc = fsl_db_get_text(db, &repoDb, NULL,
                       "SELECT value FROM vvar "
                       "WHERE name='repository'");
  if(rc) fsl_cx_uplift_db_error( f, db );
  else if(repoDb){
    if(!fsl_is_absolute_path(repoDb)){
      /* Make it relative to the checkout db dir */
      rc = fsl_buffer_appendf(repoDbAbs, "%s%s", f->ckout.dir, repoDb);
      fsl_free(repoDb);
      if(rc) goto end;




      repoDb = fsl_buffer_str(repoDbAbs);
    }
    rc = fsl_file_canonical_name(repoDb, nameCanon, 0);
    if(fsl_buffer_str(repoDbAbs) != repoDb){
      fsl_free(repoDb);
    }
    repoDb = NULL;
    if(!rc){


      rc = fsl_repo_open(f, fsl_buffer_cstr(nameCanon));
    }

  }else{
    /* This can only happen if we are not using a proper
       checkout db or someone has removed the repo link.
    */
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "Could not determine this checkout's "
                        "repository db file.");
  }
  end:
  fsl__cx_scratchpad_yield(f, nameCanon);
  fsl__cx_scratchpad_yield(f, repoDbAbs);
  return rc;
}

static void fsl_ckout_mtime_set(fsl_cx * const f){
  f->ckout.mtime = f->ckout.rid>0
    ? fsl_db_g_double(fsl_cx_db_repo(f), 0.0,
                      "SELECT mtime FROM event "
1322
1323
1324
1325
1326
1327
1328



1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
  fsl_buffer * const bufD = fsl__cx_scratchpad(f);
  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;



  }
  rc = fsl_file_canonical_name( dirName, bufD, false );
  if(rc) goto end;
  dirName = fsl_buffer_cstr(bufD);
  rc = fsl_ckout_db_search(dirName, checkParentDirs, buf);
  if(rc){
    if(FSL_RC_NOT_FOUND==rc){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Could not find checkout under [%s].",
                          dirName ? dirName : ".");
    }
    goto end;
  }
  assert(buf->used>1 /* "/<FILENAME>" */);
  zName = fsl_buffer_cstr(buf);
  rc = fsl_cx_ckout_open_db(f, zName);
  if(0==rc){
    /* Checkout db is now opened. Fiddle some internal
       bits...
    */
    unsigned char * end = buf->mem+buf->used-1;
    /* Find dir part */
    while(end>buf->mem && (unsigned char)'/'!=*end) --end;







>
>
>















|







1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
  fsl_buffer * const bufD = fsl__cx_scratchpad(f);
  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);
  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;
  }
  assert(buf->used>1 /* "/<FILENAME>" */);
  zName = fsl_buffer_cstr(buf);
  rc = fsl__cx_ckout_open_db(f, zName);
  if(0==rc){
    /* Checkout db is now opened. Fiddle some internal
       bits...
    */
    unsigned char * end = buf->mem+buf->used-1;
    /* Find dir part */
    while(end>buf->mem && (unsigned char)'/'!=*end) --end;
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
  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);
  char const * rc = db ? db->filename : NULL;
  if(len) *len = fsl_strlen(rc);
  return rc;
}

char const * fsl_cx_db_name_for_role(fsl_cx const * f,
                                     fsl_dbrole_e r,
                                     fsl_size_t * len){
  if(FSL_DBROLE_MAIN == r){
    /* special case to be removed when f->dbMem bits are
       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;
  }
}

char const * fsl_cx_db_file_config(fsl_cx const * f,







|





|








|







1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
  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);
  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 * const f,
                                     fsl_dbrole_e r,
                                     fsl_size_t * len){
  if(FSL_DBROLE_MAIN == r){
    /* special case to be removed when f->dbMem bits are
       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;
  }
}

char const * fsl_cx_db_file_config(fsl_cx const * f,
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678

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

int fsl_cx_close_dbs( fsl_cx * const f ){
  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.");
  }
  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;
  fsl_config_close(f);
  /* 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);







<















|







1668
1669
1670
1671
1672
1673
1674

1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697

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

int fsl_cx_close_dbs( fsl_cx * const f ){
  if(fsl_cx_transaction_level(f)){

    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close the databases when a "
                          "transaction is pending.");
  }
  if(NULL==f->dbMain) return 0;
  int rc = 0, rc1;
  rc = fsl__db_cached_clear_role(f->dbMain, 0);
  if(rc) return fsl_cx_uplift_db_error(f, f->dbMain);
  rc1 = fsl_ckout_close(f);
  if(rc1) rc = rc1;
  rc1 = fsl_repo_close(f);
  if(rc1) rc = rc1;
  fsl_config_close(f);
  /* Forcibly reset the role and db strings for this case, even
     if closing ostensibly fails. */
  assert(NULL==f->dbMain);
  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);
1782
1783
1784
1785
1786
1787
1788

1789
1790




1791
1792
1793

1794
1795




1796
1797
1798
1799
1800
1801
1802
int fsl_cx_transaction_level(fsl_cx * const f){
  return f->dbMain
    ? fsl_db_transaction_level(f->dbMain)
    : 0;
}

int fsl_cx_transaction_begin(fsl_cx * const f){

  int const rc = fsl_db_transaction_begin(f->dbMain);
  return rc ? fsl_cx_uplift_db_error2(f, f->dbMain, rc) : 0;




}

int fsl_cx_transaction_end(fsl_cx * const f, bool doRollback){

  int const rc = fsl_db_transaction_end(f->dbMain, doRollback);
  return rc ? fsl_cx_uplift_db_error2(f, f->dbMain, rc) : 0;




}

void fsl_cx_confirmer(fsl_cx * f,
                      fsl_confirmer const * newConfirmer,
                      fsl_confirmer * prevConfirmer){
  if(prevConfirmer) *prevConfirmer = f->confirmer;
  f->confirmer = newConfirmer ? *newConfirmer : fsl_confirmer_empty;







>
|
|
>
>
>
>



>
|
|
>
>
>
>







1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
int fsl_cx_transaction_level(fsl_cx * const f){
  return f->dbMain
    ? fsl_db_transaction_level(f->dbMain)
    : 0;
}

int fsl_cx_transaction_begin(fsl_cx * const f){
  if(f->dbMain){
    int const rc = fsl_db_transaction_begin(f->dbMain);
    return rc ? fsl_cx_uplift_db_error2(f, f->dbMain, rc) : 0;
  }else{
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "No repo/checkout databases are opened.");
  }
}

int fsl_cx_transaction_end(fsl_cx * const f, bool doRollback){
  if(f->dbMain){
    int const rc = fsl_db_transaction_end(f->dbMain, doRollback);
    return rc ? fsl_cx_uplift_db_error2(f, f->dbMain, rc) : 0;
  }else{
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "No repo/checkout databases are opened.");
  }
}

void fsl_cx_confirmer(fsl_cx * f,
                      fsl_confirmer const * newConfirmer,
                      fsl_confirmer * prevConfirmer){
  if(prevConfirmer) *prevConfirmer = f->confirmer;
  f->confirmer = newConfirmer ? *newConfirmer : fsl_confirmer_empty;
Changes to src/db.c.
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
       allocating a copy with a prefix. That has the advantage of not
       allocating (so an OOM message can be reported with a message)
       but the disadvantage of exposing the 3rd-party error string
       without any indication that it's coming from a 3rd party. */
    : (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);
}








|







75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
       allocating a copy with a prefix. That has the advantage of not
       allocating (so an OOM message can be reported with a message)
       but the disadvantage of exposing the 3rd-party error string
       without any indication that it's coming from a 3rd party. */
    : (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);
}

148
149
150
151
152
153
154
155


156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

178
179
180
181
182
183
184
  }
  return rc;
}

void fsl_db_close( fsl_db * const db ){
  void const * const allocStamp = db->allocStamp;
  fsl_cx * const f = db->f;
  if(!db->dbh) return;


  fsl_db_stmt_cache_clear(db);
  if(db->f && db->f->dbMain==db){
    /*
      Horrible, horrible dependency, and only necessary if the
      fsl_cx API gets sloppy or repo/checkout/config DBs are
      otherwised closed improperly (i.e. not via the fsl_cx API).
    */
    assert(0 != db->role);
    f->dbMain = NULL;
  }
  while(db->beginCount>0){
    fsl_db_transaction_end(db, 1);
  }
  if(0!=db->openStatementCount){
    MARKER(("WARNING: %d open statement(s) left on db [%s].\n",
            (int)db->openStatementCount, db->filename));
  }
  if(db->dbh){
    sqlite3_close_v2(db->dbh);
    /* Ignore results in the style of "destructors
       may not throw.". */
  }

  fsl__db_clear_strings(db, true);
  fsl_db_cleanup_beforeCommit(db);
  fsl_buffer_clear(&db->cachePrepBuf);
  *db = fsl_db_empty;
  if(&fsl_db_empty == allocStamp){
    fsl_free( db );
  }else{







|
>
>





|








|
|


|
|
|

>







148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
  }
  return rc;
}

void fsl_db_close( fsl_db * const db ){
  void const * const allocStamp = db->allocStamp;
  fsl_cx * const f = db->f;
  if(!db->dbh){
    goto end;
  }
  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
      otherwise closed improperly (i.e. not via the fsl_cx API).
    */
    assert(0 != db->role);
    f->dbMain = NULL;
  }
  while(db->beginCount>0){
    fsl_db_transaction_end(db, 1);
  }
  if(0!=db->openStatementCount){
    MARKER(("WARNING: %d open statement(s) left on db [%s]. Cached?=%p\n",
            (int)db->openStatementCount, db->filename, (void*)db->cacheHead));
  }
  if(db->dbh){
    sqlite3_close_v2(db->dbh)
      /* Ignore results in the style of "destructors may not
         throw." */;
  }
  end:
  fsl__db_clear_strings(db, true);
  fsl_db_cleanup_beforeCommit(db);
  fsl_buffer_clear(&db->cachePrepBuf);
  *db = fsl_db_empty;
  if(&fsl_db_empty == allocStamp){
    fsl_free( db );
  }else{
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
  if(db && (db->error.code||db->error.msg.used)){
    fsl_error_reset(&db->error);
  }
}


int fsl_db_attach(fsl_db * const db, const char *zDbName, const char *zLabel){
  return (db && db->dbh && zDbName && *zDbName && zLabel && *zLabel)
    ? fsl_db_exec(db, "ATTACH DATABASE %Q AS %s", zDbName, zLabel)
    : FSL_RC_MISUSE;
}
int fsl_db_detach(fsl_db * const db, const char *zLabel){
  return (db && db->dbh && zLabel && *zLabel)
    ? fsl_db_exec(db, "DETACH DATABASE %s /*%s()*/", zLabel, __func__)
    : FSL_RC_MISUSE;
}

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

/**
    Returns the db name for the given role.
 */
const char * fsl_db_role_label(fsl_dbrole_e r){
  switch(r){
    case FSL_DBROLE_CONFIG:
      return "cfg";
    case FSL_DBROLE_REPO:
      return "repo";
    case FSL_DBROLE_CKOUT:
      return "ckout";







|
|



|
|










|







195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
  if(db && (db->error.code||db->error.msg.used)){
    fsl_error_reset(&db->error);
  }
}


int fsl_db_attach(fsl_db * const db, const char *zDbName, const char *zLabel){
  return (db->dbh && zDbName && *zDbName && zLabel && *zLabel)
    ? fsl_db_exec(db, "ATTACH DATABASE %Q AS %Q", zDbName, zLabel)
    : FSL_RC_MISUSE;
}
int fsl_db_detach(fsl_db * const db, const char *zLabel){
  return (db->dbh && zLabel && *zLabel)
    ? fsl_db_exec(db, "DETACH DATABASE %Q /*%s()*/", zLabel, __func__)
    : FSL_RC_MISUSE;
}

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

/**
    Returns the db name for the given role.
 */
const char * fsl_db_role_name(fsl_dbrole_e r){
  switch(r){
    case FSL_DBROLE_CONFIG:
      return "cfg";
    case FSL_DBROLE_REPO:
      return "repo";
    case FSL_DBROLE_CKOUT:
      return "ckout";
1100
1101
1102
1103
1104
1105
1106
1107
1108



1109
1110
1111
1112
1113
1114
1115
1116
}

int fsl_db_open( fsl_db * const db, char const * dbFile,
                 int openFlags ){
  int rc;
  fsl_dbh_t * dbh = NULL;
  int isMem = 0;
  if(!db || !dbFile) return FSL_RC_MISUSE;
  else if(db->dbh) return FSL_RC_MISUSE;



  else if(!(isMem = (!*dbFile || 0==fsl_strcmp(":memory:", dbFile)))
          && !(FSL_OPEN_F_CREATE & openFlags)
          && fsl_file_access(dbFile, 0)){
    return fsl_error_set(&db->error, FSL_RC_NOT_FOUND,
                         "DB file not found: %s", dbFile);
  }
  else{
    int sOpenFlags = 0;







|
|
>
>
>
|







1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
}

int fsl_db_open( fsl_db * const db, char const * dbFile,
                 int openFlags ){
  int rc;
  fsl_dbh_t * dbh = NULL;
  int isMem = 0;
  if(!dbFile) return FSL_RC_MISUSE;
  else if(db->dbh){
    return fsl_error_set(&db->error, FSL_RC_MISUSE,
                         "Cannot open db: it's already opened.");
  }else if(!(isMem =
             (!*dbFile/*TEMP db*/ || 0==fsl_strcmp(":memory:", dbFile)))
          && !(FSL_OPEN_F_CREATE & openFlags)
          && fsl_file_access(dbFile, 0)){
    return fsl_error_set(&db->error, FSL_RC_NOT_FOUND,
                         "DB file not found: %s", dbFile);
  }
  else{
    int sOpenFlags = 0;
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
  return rc;
}

bool fsl_db_table_exists(fsl_db * const db,
                        fsl_dbrole_e whichDb,
                        const char *zTable
){
  const char *zDb = fsl_db_role_label( whichDb );
  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;
}








|







1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
  return rc;
}

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

Changes to src/repo.c.
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
  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;
  extern int fsl_cx_attach_role(fsl_cx * f, const char *zDbName, fsl_dbrole_e r)
    /* Internal routine from cx.c */;
  if(!opt || !opt->filename) return FSL_RC_MISUSE;
  fileExists = 0 == fsl_file_access(opt->filename,0);
  if(fileExists && !opt->allowOverwrite){
    return f
      ? fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                       "File already exists and "
                       "allowOverwrite is false: %s",







<
<







914
915
916
917
918
919
920


921
922
923
924
925
926
927
  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;


  if(!opt || !opt->filename) return FSL_RC_MISUSE;
  fileExists = 0 == fsl_file_access(opt->filename,0);
  if(fileExists && !opt->allowOverwrite){
    return f
      ? fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                       "File already exists and "
                       "allowOverwrite is false: %s",
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
    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);
  if(rc){
    goto end2;
  }
  db = fsl_cx_db(f);
  if(!f->repo.user){
    f->repo.user = fsl_user_name_guess()
      /* Ignore OOM error here - we'll use 'root'







|







966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
    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);
  if(rc){
    goto end2;
  }
  db = fsl_cx_db(f);
  if(!f->repo.user){
    f->repo.user = fsl_user_name_guess()
      /* Ignore OOM error here - we'll use 'root'
1119
1120
1121
1122
1123
1124
1125

1126
1127
1128
1129
1130
1131
1132
1133
1134
1135

1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156

1157
1158
1159
1160
1161
1162
1163
      fsl_cx_uplift_db_error(f, db);
      goto detach;
    }
    inTrans2 = 1;
    /*
       Copy all settings from the supplied template repository.
    */

    rc = fsl_db_exec(db,
                     "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-*';",
                     inopConfig, inopDb);
    if(rc) goto detach;
    rc = fsl_db_exec(db,
                     "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
       template repository into the one being setup.  The other
       columns are not copied because they contain security
       information or other data specific to the other repository.
       The list of columns copied by this SQL statement may need to be
       revised in the future.
    */
    rc = fsl_db_exec(db, "UPDATE repo.user SET"
      "  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');"

    );

    detach:
    fsl_free(inopConfig);
    fsl_free(inopDb);
    if(inTrans2){
      if(!rc) rc = fsl_db_transaction_end(db,0);







>

|



|


|
|
>











|








|
>







1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
      fsl_cx_uplift_db_error(f, db);
      goto detach;
    }
    inTrans2 = 1;
    /*
       Copy all settings from the supplied template repository.
    */
    char const * zRepoLabel = fsl_db_role_name(FSL_DBROLE_REPO);
    rc = fsl_db_exec(db,
                     "INSERT OR REPLACE INTO %s.config"
                     " SELECT name,value,mtime FROM settingSrc.config"
                     "  WHERE (name IN %s OR name IN %s)"
                     "    AND name NOT GLOB 'project-*';",
                     zRepoLabel, inopConfig, inopDb);
    if(rc) goto detach;
    rc = fsl_db_exec(db,
                     "REPLACE INTO %s.reportfmt "
                     "SELECT * FROM settingSrc.reportfmt;",
                     zRepoLabel);
    if(rc) goto detach;

    /*
       Copy the user permissions, contact information, last modified
       time, and photo for all the "system" users from the supplied
       template repository into the one being setup.  The other
       columns are not copied because they contain security
       information or other data specific to the other repository.
       The list of columns copied by this SQL statement may need to be
       revised in the future.
    */
    rc = fsl_db_exec(db, "UPDATE %s.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');",
      zRepoLabel
    );

    detach:
    fsl_free(inopConfig);
    fsl_free(inopDb);
    if(inTrans2){
      if(!rc) rc = fsl_db_transaction_end(db,0);
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
      fsl_stmt_finalize(&s);
    }
    return rc;
  }
}

/* UNTESTED */
char fsl_repo_is_readonly(fsl_cx const * f){
  if(!f || !f->dbMain) return 0;
  else{
    int const roleId = f->ckout.db.dbh ? FSL_DBROLE_MAIN : FSL_DBROLE_REPO
      /* If CKOUT is attached, it is the main DB and REPO is ATTACHed. */
      ;
    char const * zRole = fsl_db_role_label(roleId);
    assert(f->dbMain);
    return sqlite3_db_readonly(f->dbMain->dbh, zRole) ? 1 : 0;
  }
}

int fsl__repo_record_filename(fsl_cx * const f){
  fsl_db * dbR = fsl_needs_repo(f);







|
|




|







1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
      fsl_stmt_finalize(&s);
    }
    return rc;
  }
}

/* UNTESTED */
bool fsl_repo_is_readonly(fsl_cx const * f){
  if(!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);
    assert(f->dbMain);
    return sqlite3_db_readonly(f->dbMain->dbh, zRole) ? 1 : 0;
  }
}

int fsl__repo_record_filename(fsl_cx * const f){
  fsl_db * dbR = fsl_needs_repo(f);
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
  dbConf = fsl_cx_db_config(f);
  if(dbConf){
    int const dbRole = (f->dbMain==&f->config.db)
      ? FSL_DBROLE_MAIN : FSL_DBROLE_CONFIG;
    rc = fsl_db_exec(dbConf,
                     "INSERT OR IGNORE INTO %s.global_config(name,value) "
                     "VALUES('repo:%q',1)",
                     fsl_db_role_label(dbRole),
                     fsl_buffer_cstr(full));
    if(rc){
      fsl_cx_uplift_db_error(f, dbConf);
      goto end;
    }
  }

  dbC = fsl_cx_db_ckout(f);
  if(dbC && (zCDir=f->ckout.dir)){
    /* If we have a checkout, update its repo's list of checkouts... */
    /* Assumption: if we have an opened checkout, dbR is ATTACHed with
       the role REPO. */
    int ro;
    assert(dbR);
    ro = sqlite3_db_readonly(dbR->dbh,
                             fsl_db_role_label(FSL_DBROLE_REPO));
    assert(ro>=0);
    if(!ro){
      fsl_buffer localRoot = fsl_buffer_empty;
      rc = fsl_file_canonical_name(zCDir, &localRoot, 1);
      if(0==rc){
        if(dbConf){
          /*
            If global config is open, write the checkout db's name to it.
          */
          int const dbRole = (f->dbMain==&f->config.db)
            ? FSL_DBROLE_MAIN : FSL_DBROLE_CONFIG;
          rc = fsl_db_exec(dbConf,
                           "REPLACE INTO INTO %s.global_config(name,value) "
                           "VALUES('ckout:%q',1)",
                           fsl_db_role_label(dbRole),
                           fsl_buffer_cstr(&localRoot));
        }
        if(0==rc){
          /* We know that repo is ATTACHed to ckout here. */
          assert(dbR == dbC);
          rc = fsl_db_exec(dbR,
                           "REPLACE INTO %s.config(name, value, mtime) "
                           "VALUES('ckout:%q', 1, now())",
                           fsl_db_role_label(FSL_DBROLE_REPO),
                           fsl_buffer_cstr(&localRoot));
        }
      }
      fsl_buffer_clear(&localRoot);
    }
  }

  end:
  if(rc && !f->error.code && f->dbMain->error.code){
    fsl_cx_uplift_db_error(f, f->dbMain);
  }
  fsl__cx_scratchpad_yield(f, full);
  return rc;

}

char fsl_rid_is_a_checkin(fsl_cx * f, fsl_id_t rid){
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  if(!db || (rid<0)) return 0;
  else if(0==rid){
    /* Corner case: empty repo */
    return !fsl_db_exists(db, "SELECT 1 FROM blob WHERE rid>0");
  }
  else{







|















|














|








|
















|







1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
  dbConf = fsl_cx_db_config(f);
  if(dbConf){
    int const dbRole = (f->dbMain==&f->config.db)
      ? FSL_DBROLE_MAIN : FSL_DBROLE_CONFIG;
    rc = fsl_db_exec(dbConf,
                     "INSERT OR IGNORE INTO %s.global_config(name,value) "
                     "VALUES('repo:%q',1)",
                     fsl_db_role_name(dbRole),
                     fsl_buffer_cstr(full));
    if(rc){
      fsl_cx_uplift_db_error(f, dbConf);
      goto end;
    }
  }

  dbC = fsl_cx_db_ckout(f);
  if(dbC && (zCDir=f->ckout.dir)){
    /* If we have a checkout, update its repo's list of checkouts... */
    /* Assumption: if we have an opened checkout, dbR is ATTACHed with
       the role REPO. */
    int ro;
    assert(dbR);
    ro = sqlite3_db_readonly(dbR->dbh,
                             fsl_db_role_name(FSL_DBROLE_REPO));
    assert(ro>=0);
    if(!ro){
      fsl_buffer localRoot = fsl_buffer_empty;
      rc = fsl_file_canonical_name(zCDir, &localRoot, 1);
      if(0==rc){
        if(dbConf){
          /*
            If global config is open, write the checkout db's name to it.
          */
          int const dbRole = (f->dbMain==&f->config.db)
            ? FSL_DBROLE_MAIN : FSL_DBROLE_CONFIG;
          rc = fsl_db_exec(dbConf,
                           "REPLACE INTO INTO %s.global_config(name,value) "
                           "VALUES('ckout:%q',1)",
                           fsl_db_role_name(dbRole),
                           fsl_buffer_cstr(&localRoot));
        }
        if(0==rc){
          /* We know that repo is ATTACHed to ckout here. */
          assert(dbR == dbC);
          rc = fsl_db_exec(dbR,
                           "REPLACE INTO %s.config(name, value, mtime) "
                           "VALUES('ckout:%q', 1, now())",
                           fsl_db_role_name(FSL_DBROLE_REPO),
                           fsl_buffer_cstr(&localRoot));
        }
      }
      fsl_buffer_clear(&localRoot);
    }
  }

  end:
  if(rc && !f->error.code && f->dbMain->error.code){
    fsl_cx_uplift_db_error(f, f->dbMain);
  }
  fsl__cx_scratchpad_yield(f, full);
  return rc;

}

char fsl_rid_is_a_checkin(fsl_cx * const f, fsl_id_t rid){
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  if(!db || (rid<0)) return 0;
  else if(0==rid){
    /* Corner case: empty repo */
    return !fsl_db_exists(db, "SELECT 1 FROM blob WHERE rid>0");
  }
  else{
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
  /**
     Update the repository schema for Fossil version 2.0.  (2017-02-28)
     (1) Change the CHECK constraint on BLOB.UUID so that the length
     is greater than or equal to 40, not exactly equal to 40.
  */
  zBlobSchema =
    fsl_db_g_text(frs->db, NULL, "SELECT sql FROM %!Q.sqlite_schema"
                  " WHERE name='blob'", fsl_db_role_label(FSL_DBROLE_REPO));
  if(!zBlobSchema){
    /* ^^^^ reminder: fossil(1) simply ignores this case, silently
       doing nothing instead. */
    rc = fsl_cx_uplift_db_error(frs->f, frs->db);
    if(!rc){
      rc = fsl_cx_err_set(frs->f, FSL_RC_DB,
                          "Unknown error fetching blob table schema.");







|







1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
  /**
     Update the repository schema for Fossil version 2.0.  (2017-02-28)
     (1) Change the CHECK constraint on BLOB.UUID so that the length
     is greater than or equal to 40, not exactly equal to 40.
  */
  zBlobSchema =
    fsl_db_g_text(frs->db, NULL, "SELECT sql FROM %!Q.sqlite_schema"
                  " WHERE name='blob'", fsl_db_role_name(FSL_DBROLE_REPO));
  if(!zBlobSchema){
    /* ^^^^ reminder: fossil(1) simply ignores this case, silently
       doing nothing instead. */
    rc = fsl_cx_uplift_db_error(frs->f, frs->db);
    if(!rc){
      rc = fsl_cx_err_set(frs->f, FSL_RC_DB,
                          "Unknown error fetching blob table schema.");
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
      int rc2 = 0;
      zBlobSchema[i] = '>';
      sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE, 0, &rc2);
      rc = fsl_cx_exec_multi(frs->f,
           "PRAGMA writable_schema=ON;"
           "UPDATE %!Q.sqlite_schema SET sql=%Q WHERE name LIKE 'blob';"
           "PRAGMA writable_schema=OFF;",
           fsl_db_role_label(FSL_DBROLE_REPO), zBlobSchema
      );
      sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE, 1, &rc2);
      break;
    }
  }
  if(rc) goto end;
  rc = fsl_cx_exec(frs->f,
    "CREATE VIEW IF NOT EXISTS "
    "  %!Q.artifact(rid,rcvid,size,atype,srcid,hash,content) AS "
    "    SELECT blob.rid,rcvid,size,1,srcid,uuid,content"
    "      FROM blob LEFT JOIN delta ON (blob.rid=delta.rid);",
    fsl_db_role_label(FSL_DBROLE_REPO)
  );
  
  end:
  fsl_free(zBlobSchema);
  return rc;
}








|











|







1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
      int rc2 = 0;
      zBlobSchema[i] = '>';
      sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE, 0, &rc2);
      rc = fsl_cx_exec_multi(frs->f,
           "PRAGMA writable_schema=ON;"
           "UPDATE %!Q.sqlite_schema SET sql=%Q WHERE name LIKE 'blob';"
           "PRAGMA writable_schema=OFF;",
           fsl_db_role_name(FSL_DBROLE_REPO), zBlobSchema
      );
      sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE, 1, &rc2);
      break;
    }
  }
  if(rc) goto end;
  rc = fsl_cx_exec(frs->f,
    "CREATE VIEW IF NOT EXISTS "
    "  %!Q.artifact(rid,rcvid,size,atype,srcid,hash,content) AS "
    "    SELECT blob.rid,rcvid,size,1,srcid,uuid,content"
    "      FROM blob LEFT JOIN delta ON (blob.rid=delta.rid);",
    fsl_db_role_name(FSL_DBROLE_REPO)
  );
  
  end:
  fsl_free(zBlobSchema);
  return rc;
}

2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
                       "'concealed','accesslog','modreq',"
                       "'purgeevent','purgeitem','unversioned',"
                      "'ticket','ticketchng',"
                       "'subscriber','pending_alert','chat'"
                      ")"
     " AND name NOT GLOB 'sqlite_*'"
     " AND name NOT GLOB 'fx_*'",
     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",
                            fsl_stmt_g_text(&q, 0, NULL));
  }
  fsl_stmt_finalize(&q);
  if(0==rc && fsl_buffer_size(sql)){







|







2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
                       "'concealed','accesslog','modreq',"
                       "'purgeevent','purgeitem','unversioned',"
                      "'ticket','ticketchng',"
                       "'subscriber','pending_alert','chat'"
                      ")"
     " AND name NOT GLOB 'sqlite_*'"
     " AND name NOT GLOB 'fx_*'",
     fsl_db_role_name(FSL_DBROLE_REPO)
  );
  while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
    rc = fsl_buffer_appendf(sql, "DROP TABLE IF EXISTS %!Q;\n",
                            fsl_stmt_g_text(&q, 0, NULL));
  }
  fsl_stmt_finalize(&q);
  if(0==rc && fsl_buffer_size(sql)){
Changes to src/udf.c.
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472

473
474
475
476
477
478
479
480
481
482
483
    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);
  assert(db==&f->dbMem && "Currently the case - may change later.");
  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);







<
<
<
<
<



|











|


|
>
|
<
<
<







442
443
444
445
446
447
448





449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469



470
471
472
473
474
475
476
    return;
  }
  fsl_cx_glob_list(f, globType, &li, false);
  assert(li);
  sqlite3_result_int(context, fsl_glob_list_matches(li, p2) ? 1 : 0);
}






int fsl__cx_init_db(fsl_cx * const f, fsl_db * const db){
  int rc;
  assert(!f->dbMain);
  assert((db==&f->repo.db || db==&f->ckout.db));
  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 main.foreign_keys=OFF;"
                         // ^^^ vmerge table relies on this for its magical
                         // vmerge.id values.
                         //"PRAGMA main.temp_store=FILE;"
                         //"PRAGMA main.temp_store=MEMORY;"
                         //"PRAGMA main.journal_mode=WAL;"



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