/* ** Initialize a blob to be the content of a file. If the filename ** is blank or "-" then read from standard input. ** ** Any prior content of the blob is discarded, not freed. ** ** Return the number of bytes read. Calls fossil_fatal() error (i.e. ** it exit()s and does not return). */ int blob_read_from_file(Blob *pBlob, const char *zFilename){ int size, got; FILE *in; if( zFilename==0 || zFilename[0]==0 || (zFilename[0]=='-' && zFilename[1]==0) ){ return blob_read_from_channel(pBlob, stdin, -1); } size = file_wd_size(zFilename); blob_zero(pBlob); if( size<0 ){ fossil_fatal("no such file: %s", zFilename); } if( size==0 ){ return 0; } blob_resize(pBlob, size); in = fossil_fopen(zFilename, "rb"); if( in==0 ){ fossil_fatal("cannot open %s for reading", zFilename); } got = fread(blob_buffer(pBlob), 1, size, in); fclose(in); if( got<size ){ blob_resize(pBlob, got); } return got; }
/* ** COMMAND: test-tag ** %fossil test-tag (+|*|-)TAGNAME ARTIFACT-ID ?VALUE? ** ** Add a tag or anti-tag to the rebuildable tables of the local repository. ** No tag artifact is created so the new tag is erased the next ** time the repository is rebuilt. This routine is for testing ** use only. */ void testtag_cmd(void){ const char *zTag; const char *zValue; int rid; int tagtype; db_must_be_within_tree(); if( g.argc!=4 && g.argc!=5 ){ usage("TAGNAME ARTIFACT-ID ?VALUE?"); } zTag = g.argv[2]; switch( zTag[0] ){ case '+': tagtype = 1; break; case '*': tagtype = 2; break; case '-': tagtype = 0; break; default: fossil_fatal("tag should begin with '+', '*', or '-'"); return; } rid = name_to_rid(g.argv[3]); if( rid==0 ){ fossil_fatal("no such object: %s", g.argv[3]); } g.markPrivate = content_is_private(rid); zValue = g.argc==5 ? g.argv[4] : 0; db_begin_transaction(); tag_insert(zTag, tagtype, zValue, -1, 0.0, rid); db_end_transaction(0); }
/* ** Figure out what user is at the controls. ** ** (1) Use the --user and -U command-line options. ** ** (2) If the local database is open, check in VVAR. ** ** (3) Check the default user in the repository ** ** (4) Try the USER environment variable. ** ** (5) Try the USERNAME environment variable. ** ** (6) Check if the user can be extracted from the remote URL. ** ** The user name is stored in g.zLogin. The uid is in g.userUid. */ void user_select(void){ char *zUrl; if( g.userUid ) return; if( g.zLogin ){ if( attempt_user(g.zLogin)==0 ){ fossil_fatal("no such user: %s", g.zLogin); }else{ return; } } if( g.localOpen && attempt_user(db_lget("default-user",0)) ) return; if( attempt_user(db_get("default-user", 0)) ) return; if( attempt_user(fossil_getenv("USER")) ) return; if( attempt_user(fossil_getenv("USERNAME")) ) return; zUrl = db_get("last-sync-url", 0); if( zUrl ){ url_parse(zUrl); if( attempt_user(g.urlUser) ) return; } fossil_print( "Cannot figure out who you are! Consider using the --user\n" "command line option, setting your USER environment variable,\n" "or setting a default user with \"fossil user default USER\".\n" ); fossil_fatal("cannot determine user"); }
/* ** COMMAND: bundle ** ** Usage: %fossil bundle SUBCOMMAND ARGS... ** ** fossil bundle append BUNDLE FILE... ** ** Add files named on the command line to BUNDLE. This subcommand has ** little practical use and is mostly intended for testing. ** ** fossil bundle cat BUNDLE UUID... ** ** Extract one or more artifacts from the bundle and write them ** consecutively on standard output. This subcommand was designed ** for testing and introspection of bundles and is not something ** commonly used. ** ** fossil bundle export BUNDLE ?OPTIONS? ** ** Generate a new bundle, in the file named BUNDLE, that contains a ** subset of the check-ins in the repository (usually a single branch) ** described by the --branch, --from, --to, and/or --checkin options, ** at least one of which is required. If BUNDLE already exists, the ** specified content is added to the bundle. ** ** --branch BRANCH Package all check-ins on BRANCH. ** --from TAG1 --to TAG2 Package check-ins between TAG1 and TAG2. ** --checkin TAG Package the single check-in TAG ** --standalone Do no use delta-encoding against ** artifacts not in the bundle ** ** fossil bundle extend BUNDLE ** ** The BUNDLE must already exist. This subcommand adds to the bundle ** any check-ins that are descendants of check-ins already in the bundle, ** and any tags that apply to artifacts in the bundle. ** ** fossil bundle import BUNDLE ?--publish? ** ** Import all content from BUNDLE into the repository. By default, the ** imported files are private and will not sync. Use the --publish ** option makes the import public. ** ** fossil bundle ls BUNDLE ** ** List the contents of BUNDLE on standard output ** ** fossil bundle purge BUNDLE ** ** Remove from the repository all files that are used exclusively ** by check-ins in BUNDLE. This has the effect of undoing a ** "fossil bundle import". ** ** SUMMARY: ** fossil bundle append BUNDLE FILE... Add files to BUNDLE ** fossil bundle cat BUNDLE UUID... Extract file from BUNDLE ** fossil bundle export BUNDLE ?OPTIONS? Create a new BUNDLE ** --branch BRANCH --from TAG1 --to TAG2 Check-ins to include ** --checkin TAG Use only check-in TAG ** --standalone Omit dependencies ** fossil bundle extend BUNDLE Update with newer content ** fossil bundle import BUNDLE ?OPTIONS? Import a bundle ** --publish Publish the import ** --force Cross-repo import ** fossil bundle ls BUNDLE List content of a bundle ** fossil bundle purge BUNDLE Undo an import ** ** See also: publish */ void bundle_cmd(void){ const char *zSubcmd; int n; if( g.argc<4 ) usage("SUBCOMMAND BUNDLE ?OPTIONS?"); zSubcmd = g.argv[2]; db_find_and_open_repository(0,0); n = (int)strlen(zSubcmd); if( strncmp(zSubcmd, "append", n)==0 ){ bundle_append_cmd(); }else if( strncmp(zSubcmd, "cat", n)==0 ){ bundle_cat_cmd(); }else if( strncmp(zSubcmd, "export", n)==0 ){ bundle_export_cmd(); }else if( strncmp(zSubcmd, "extend", n)==0 ){ fossil_fatal("not yet implemented"); }else if( strncmp(zSubcmd, "import", n)==0 ){ bundle_import_cmd(); }else if( strncmp(zSubcmd, "ls", n)==0 ){ bundle_ls_cmd(); }else if( strncmp(zSubcmd, "purge", n)==0 ){ bundle_purge_cmd(); }else{ fossil_fatal("unknown subcommand for bundle: %s", zSubcmd); } }
/* ** Identify a subsection of the check-in tree using command-line switches. ** There must be one of the following switch available: ** ** --branch BRANCHNAME All check-ins on the most recent ** instance of BRANCHNAME ** --from TAG1 [--to TAG2] Check-in TAG1 and all primary descendants ** up to and including TAG2 ** --checkin TAG Check-in TAG only ** ** Store the RIDs for all applicable check-ins in the zTab table that ** should already exist. Invoke fossil_fatal() if any kind of error is ** seen. */ void subtree_from_arguments(const char *zTab){ const char *zBr; const char *zFrom; const char *zTo; const char *zCkin; int rid = 0, endRid; zBr = find_option("branch",0,1); zFrom = find_option("from",0,1); zTo = find_option("to",0,1); zCkin = find_option("checkin",0,1); if( zCkin ){ if( zFrom ) fossil_fatal("cannot use both --checkin and --from"); if( zBr ) fossil_fatal("cannot use both --checkin and --branch"); rid = symbolic_name_to_rid(zCkin, "ci"); endRid = rid; }else{ endRid = zTo ? name_to_typed_rid(zTo, "ci") : 0; } if( zFrom ){ rid = name_to_typed_rid(zFrom, "ci"); }else if( zBr ){ rid = name_to_typed_rid(zBr, "br"); }else if( zCkin==0 ){ fossil_fatal("need one of: --branch, --from, --checkin"); } db_multi_exec("INSERT OR IGNORE INTO \"%w\" VALUES(%d)", zTab, rid); if( rid!=endRid ){ Blob sql; blob_zero(&sql); blob_appendf(&sql, "WITH RECURSIVE child(rid) AS (VALUES(%d) UNION ALL " " SELECT cid FROM plink, child" " WHERE plink.pid=child.rid" " AND plink.isPrim", rid); if( endRid>0 ){ double endTime = db_double(0.0, "SELECT mtime FROM event WHERE objid=%d", endRid); blob_appendf(&sql, " AND child.rid!=%d" " AND (SELECT mtime FROM event WHERE objid=plink.cid)<=%.17g", endRid, endTime ); } if( zBr ){ blob_appendf(&sql, " AND EXISTS(SELECT 1 FROM tagxref" " WHERE tagid=%d AND tagtype>0" " AND value=%Q and rid=plink.cid)", TAG_BRANCH, zBr); } blob_appendf(&sql, ") INSERT OR IGNORE INTO \"%w\" SELECT rid FROM child;", zTab); db_multi_exec("%s", blob_str(&sql)/*safe-for-%s*/); } }
/* fossil bundle import BUNDLE ?OPTIONS? ** ** Attempt to import the changes contained in BUNDLE. Make the change ** private so that they do not sync. ** ** OPTIONS: ** --force Import even if the project-code does not match ** --publish Imported changes are not private */ static void bundle_import_cmd(void){ int forceFlag = find_option("force","f",0)!=0; int isPriv = find_option("publish",0,0)==0; char *zMissingDeltas; verify_all_options(); if ( g.argc!=4 ) usage("import BUNDLE ?OPTIONS?"); bundle_attach_file(g.argv[3], "b1", 1); /* Only import a bundle that was generated from a repo with the same ** project code, unless the --force flag is true */ if( !forceFlag ){ if( !db_exists("SELECT 1 FROM config, bconfig" " WHERE config.name='project-code'" " AND bconfig.bcname='project-code'" " AND config.value=bconfig.bcvalue;") ){ fossil_fatal("project-code in the bundle does not match the " "repository project code. (override with --force)."); } } /* If the bundle contains deltas with a basis that is external to the ** bundle and those external basis files are missing from the local ** repo, then the delta encodings cannot be decoded and the bundle cannot ** be extracted. */ zMissingDeltas = db_text(0, "SELECT group_concat(substr(delta,1,10),' ')" " FROM bblob" " WHERE typeof(delta)='text' AND length(delta)=40" " AND NOT EXISTS(SELECT 1 FROM blob WHERE uuid=bblob.delta)"); if( zMissingDeltas && zMissingDeltas[0] ){ fossil_fatal("delta basis artifacts not found in repository: %s", zMissingDeltas); } db_begin_transaction(); db_multi_exec( "CREATE TEMP TABLE bix(" " blobid INTEGER PRIMARY KEY," " delta INTEGER" ");" "CREATE INDEX bixdelta ON bix(delta);" "INSERT INTO bix(blobid,delta)" " SELECT blobid," " CASE WHEN typeof(delta)=='integer'" " THEN delta ELSE 0 END" " FROM bblob" " WHERE NOT EXISTS(SELECT 1 FROM blob WHERE uuid=bblob.uuid AND size>=0);" "CREATE TEMP TABLE got(rid INTEGER PRIMARY KEY ON CONFLICT IGNORE);" ); manifest_crosslink_begin(); bundle_import_elements(0, 0, isPriv); manifest_crosslink_end(0); describe_artifacts_to_stdout("IN got", "Imported content:"); db_end_transaction(0); }
/* ** Add a control record to the repository that either creates ** or cancels a tag. */ void tag_add_artifact( const char *zPrefix, /* Prefix to prepend to tag name */ const char *zTagname, /* The tag to add or cancel */ const char *zObjName, /* Name of object attached to */ const char *zValue, /* Value for the tag. Might be NULL */ int tagtype, /* 0:cancel 1:singleton 2:propagated */ const char *zDateOvrd, /* Override date string */ const char *zUserOvrd /* Override user name */ ){ int rid; int nrid; char *zDate; Blob uuid; Blob ctrl; Blob cksum; static const char zTagtype[] = { '-', '+', '*' }; assert( tagtype>=0 && tagtype<=2 ); user_select(); blob_zero(&uuid); blob_append(&uuid, zObjName, -1); if( name_to_uuid(&uuid, 9, "*") ){ fossil_fatal("%s", g.zErrMsg); return; } rid = name_to_rid(blob_str(&uuid)); g.markPrivate = content_is_private(rid); blob_zero(&ctrl); #if 0 if( validate16(zTagname, strlen(zTagname)) ){ fossil_fatal( "invalid tag name \"%s\" - might be confused with" " a hexadecimal artifact ID", zTagname ); } #endif zDate = date_in_standard_format(zDateOvrd ? zDateOvrd : "now"); blob_appendf(&ctrl, "D %s\n", zDate); blob_appendf(&ctrl, "T %c%s%F %b", zTagtype[tagtype], zPrefix, zTagname, &uuid); if( tagtype>0 && zValue && zValue[0] ){ blob_appendf(&ctrl, " %F\n", zValue); }else{ blob_appendf(&ctrl, "\n"); } blob_appendf(&ctrl, "U %F\n", zUserOvrd ? zUserOvrd : g.zLogin); md5sum_blob(&ctrl, &cksum); blob_appendf(&ctrl, "Z %b\n", &cksum); nrid = content_put(&ctrl); manifest_crosslink(nrid, &ctrl); assert( blob_is_reset(&ctrl) ); }
/* ** Convert a name to a rid. If the name can be any of the various forms ** accepted: ** ** * SHA1 hash or prefix thereof ** * symbolic name ** * date ** * label:date ** * prev, previous ** * next ** * tip ** ** This routine is used by command-line routines to resolve command-line inputs ** into a rid. */ int name_to_typed_rid(const char *zName, const char *zType){ int rid; if( zName==0 || zName[0]==0 ) return 0; rid = symbolic_name_to_rid(zName, zType); if( rid<0 ){ fossil_fatal("ambiguous name: %s", zName); }else if( rid==0 ){ fossil_fatal("not found: %s", zName); } return rid; }
/* ** Get the contents of a file within the check-in "revision". If ** revision==NULL then get the file content for the current checkout. */ int historical_version_of_file( const char *revision, /* The check-in containing the file */ const char *file, /* Full treename of the file */ Blob *content, /* Put the content here */ int *pIsLink, /* Set to true if file is link. */ int *pIsExe, /* Set to true if file is executable */ int *pIsBin, /* Set to true if file is binary */ int errCode /* Error code if file not found. Panic if <= 0. */ ) { Manifest *pManifest; ManifestFile *pFile; int rid=0; if( revision ) { rid = name_to_typed_rid(revision,"ci"); } else if( !g.localOpen ) { rid = name_to_typed_rid(db_get("main-branch","trunk"),"ci"); } else { rid = db_lget_int("checkout", 0); } if( !is_a_version(rid) ) { if( errCode>0 ) return errCode; fossil_fatal("no such check-in: %s", revision); } pManifest = manifest_get(rid, CFTYPE_MANIFEST, 0); if( pManifest ) { pFile = manifest_file_find(pManifest, file); if( pFile ) { int rc; rid = uuid_to_rid(pFile->zUuid, 0); if( pIsExe ) *pIsExe = ( manifest_file_mperm(pFile)==PERM_EXE ); if( pIsLink ) *pIsLink = ( manifest_file_mperm(pFile)==PERM_LNK ); manifest_destroy(pManifest); rc = content_get(rid, content); if( rc && pIsBin ) { *pIsBin = looks_like_binary(content); } return rc; } manifest_destroy(pManifest); if( errCode<=0 ) { fossil_fatal("file %s does not exist in check-in: %s", file, revision); } } else if( errCode<=0 ) { if( revision==0 ) { revision = db_text("current", "SELECT uuid FROM blob WHERE rid=%d", rid); } fossil_fatal("could not parse manifest for check-in: %s", revision); } return errCode; }
/* ** Copy the content of a file from one place to another. */ void file_copy(const char *zFrom, const char *zTo) { FILE *in, *out; int got; char zBuf[8192]; in = fossil_fopen(zFrom, "rb"); if( in==0 ) fossil_fatal("cannot open \"%s\" for reading", zFrom); out = fossil_fopen(zTo, "wb"); if( out==0 ) fossil_fatal("cannot open \"%s\" for writing", zTo); while( (got=fread(zBuf, 1, sizeof(zBuf), in))>0 ) { fwrite(zBuf, 1, got, out); } fclose(in); fclose(out); }
/* ** Extract an item from content from the bundle */ static void bundle_extract_item( int blobid, /* ID of the item to extract */ Blob *pOut /* Write the content into this blob */ ){ Stmt q; Blob x, basis, h1, h2; static Bag busy; db_prepare(&q, "SELECT uuid, delta, data FROM bblob" " WHERE blobid=%d", blobid); if( db_step(&q)!=SQLITE_ROW ){ db_finalize(&q); fossil_fatal("no such item: %d", blobid); } if( bag_find(&busy, blobid) ) fossil_fatal("delta loop"); blob_zero(&x); db_column_blob(&q, 2, &x); blob_uncompress(&x, &x); if( db_column_type(&q,1)==SQLITE_INTEGER ){ bundle_extract_item(db_column_int(&q,1), &basis); blob_delta_apply(&basis, &x, pOut); blob_reset(&basis); blob_reset(&x); }else if( db_column_type(&q,1)==SQLITE_TEXT ){ int rid = db_int(0, "SELECT rid FROM blob WHERE uuid=%Q", db_column_text(&q,1)); if( rid==0 ){ fossil_fatal("cannot find delta basis %s", db_column_text(&q,1)); } content_get(rid, &basis); db_column_blob(&q, 2, &x); blob_delta_apply(&basis, &x, pOut); blob_reset(&basis); blob_reset(&x); }else{ *pOut = x; } blob_zero(&h1); db_column_blob(&q, 0, &h1); sha1sum_blob(pOut, &h2); if( blob_compare(&h1, &h2)!=0 ){ fossil_fatal("SHA1 hash mismatch - wanted %s, got %s", blob_str(&h1), blob_str(&h2)); } blob_reset(&h1); blob_reset(&h2); bag_remove(&busy, blobid); db_finalize(&q); }
/* ** Open a connection to the server. The server is defined by the following ** variables: ** ** pUrlData->name Name of the server. Ex: www.fossil-scm.org ** pUrlData->port TCP/IP port. Ex: 80 ** pUrlData->isHttps Use TLS for the connection ** ** Return the number of errors. */ int transport_open(UrlData *pUrlData){ int rc = 0; if( transport.isOpen==0 ){ if( pUrlData->isSsh ){ rc = transport_ssh_open(pUrlData); if( rc==0 ) transport.isOpen = 1; }else if( pUrlData->isHttps ){ #ifdef FOSSIL_ENABLE_SSL rc = ssl_open(pUrlData); if( rc==0 ) transport.isOpen = 1; #else socket_set_errmsg("HTTPS: Fossil has been compiled without SSL support"); rc = 1; #endif }else if( pUrlData->isFile ){ sqlite3_uint64 iRandId; sqlite3_randomness(sizeof(iRandId), &iRandId); transport.zOutFile = mprintf("%s-%llu-out.http", g.zRepositoryName, iRandId); transport.zInFile = mprintf("%s-%llu-in.http", g.zRepositoryName, iRandId); transport.pFile = fossil_fopen(transport.zOutFile, "wb"); if( transport.pFile==0 ){ fossil_fatal("cannot output temporary file: %s", transport.zOutFile); } transport.isOpen = 1; }else{ rc = socket_open(pUrlData); if( rc==0 ) transport.isOpen = 1; } } return rc; }
/* ** Obtain a list of all fields of the TICKET table. Put them ** in sorted order in azField[]. ** ** Also allocate space for azValue[] and azAppend[] and initialize ** all the values there to zero. */ static void getAllTicketFields(void){ Stmt q; int i; if( nField>0 ) return; db_prepare(&q, "PRAGMA table_info(ticket)"); while( db_step(&q)==SQLITE_ROW ){ const char *zField = db_column_text(&q, 1); if( strncmp(zField,"tkt_",4)==0 ) continue; if( nField%10==0 ){ azField = realloc(azField, sizeof(azField)*3*(nField+10) ); if( azField==0 ){ fossil_fatal("out of memory"); } } azField[nField] = mprintf("%s", zField); nField++; } db_finalize(&q); qsort(azField, nField, sizeof(azField[0]), nameCmpr); azAppend = &azField[nField]; memset(azAppend, 0, sizeof(azAppend[0])*nField); azValue = &azAppend[nField]; for(i=0; i<nField; i++){ azValue[i] = ""; } }
/* ** Add a single file named zName to the VFILE table with vid. ** ** Omit any file whose name is pOmit. */ static int add_one_file( const char *zPath, /* Tree-name of file to add. */ int vid, /* Add to this VFILE */ int caseSensitive /* True if filenames are case sensitive */ ){ const char *zCollate = caseSensitive ? "binary" : "nocase"; if( !file_is_simple_pathname(zPath) ){ fossil_fatal("filename contains illegal characters: %s", zPath); } if( db_exists("SELECT 1 FROM vfile" " WHERE pathname=%Q COLLATE %s", zPath, zCollate) ){ db_multi_exec("UPDATE vfile SET deleted=0" " WHERE pathname=%Q COLLATE %s", zPath, zCollate); }else{ char *zFullname = mprintf("%s%s", g.zLocalRoot, zPath); db_multi_exec( "INSERT INTO vfile(vid,deleted,rid,mrid,pathname,isexe,islink)" "VALUES(%d,0,0,0,%Q,%d,%d)", vid, zPath, file_wd_isexe(zFullname), file_wd_islink(zFullname)); fossil_free(zFullname); } if( db_changes() ){ fossil_print("ADDED %s\n", zPath); return 1; }else{ fossil_print("SKIP %s\n", zPath); return 0; } }
/* ** COMMAND: tarball* ** ** Usage: %fossil tarball VERSION OUTPUTFILE [--name DIRECTORYNAME] [-R|--repository REPO] ** ** Generate a compressed tarball for a specified version. If the --name ** option is used, its argument becomes the name of the top-level directory ** in the resulting tarball. If --name is omitted, the top-level directory ** named is derived from the project name, the check-in date and time, and ** the artifact ID of the check-in. */ void tarball_cmd(void){ int rid; Blob tarball; const char *zName; zName = find_option("name", 0, 1); db_find_and_open_repository(0, 0); if( g.argc!=4 ){ usage("VERSION OUTPUTFILE"); } rid = name_to_typed_rid(g.argv[2], "ci"); if( rid==0 ){ fossil_fatal("Checkin not found: %s", g.argv[2]); return; } if( zName==0 ){ zName = db_text("default-name", "SELECT replace(%Q,' ','_') " " || strftime('_%%Y-%%m-%%d_%%H%%M%%S_', event.mtime) " " || substr(blob.uuid, 1, 10)" " FROM event, blob" " WHERE event.objid=%d" " AND blob.rid=%d", db_get("project-name", "unnamed"), rid, rid ); } tarball_of_checkin(rid, &tarball, zName); blob_write_to_file(&tarball, g.argv[3]); blob_reset(&tarball); }
/* ** add a Pax Interchange header to the scratch buffer ** ** format: <length> <key>=<value>\n ** the tricky part is that each header contains its own ** size in decimal, counting that length. */ static void add_pax_header( const char *zField, const char *zValue, int nValue ){ /* calculate length without length field */ int blen = strlen(zField) + nValue + 3; /* calculate the length of the length field */ int next10 = 1; int n; for(n = blen; n > 0; ){ blen++; next10 *= 10; n /= 10; } /* adding the length extended the length field? */ if(blen > next10){ blen++; } /* build the string */ blob_appendf(&tball.pax, "%d %s=%*.*s\n", blen, zField, nValue, nValue, zValue); /* this _must_ be right */ if(blob_size(&tball.pax) != blen){ fossil_fatal("internal error: PAX tar header has bad length"); } }
/* ** Write a ticket into the repository. */ static int ticket_put( Blob *pTicket, /* The text of the ticket change record */ const char *zTktId, /* The ticket to which this change is applied */ int needMod /* True if moderation is needed */ ){ int result; int rid = content_put_ex(pTicket, 0, 0, 0, needMod); if( rid==0 ){ fossil_fatal("trouble committing ticket: %s", g.zErrMsg); } if( needMod ){ moderation_table_create(); db_multi_exec( "INSERT INTO modreq(objid, tktid) VALUES(%d,'%s')", rid, zTktId ); }else{ db_multi_exec("INSERT OR IGNORE INTO unsent VALUES(%d);", rid); db_multi_exec("INSERT OR IGNORE INTO unclustered VALUES(%d);", rid); } manifest_crosslink_begin(); result = (manifest_crosslink(rid, pTicket, MC_NONE)==0); assert( blob_is_reset(pTicket) ); if( !result ){ result = manifest_crosslink_end(MC_PERMIT_HOOKS); }else{ manifest_crosslink_end(MC_NONE); } return result; }
/* ** Verify that all entries in the aMime[] table are in sorted order. ** Abort with a fatal error if any is out-of-order. */ static void mimetype_verify(void){ int i; for(i=1; i<ArraySize(aMime); i++){ if( fossil_strcmp(aMime[i-1].zSuffix,aMime[i].zSuffix)>=0 ){ fossil_fatal("mimetypes out of sequence: %s before %s", aMime[i-1].zSuffix, aMime[i].zSuffix); } } }
/* ** Recursively read all files from the directory zPath and install ** every file read as a new artifact in the repository. */ void recon_read_dir(char *zPath){ DIR *d; struct dirent *pEntry; Blob aContent; /* content of the just read artifact */ static int nFileRead = 0; void *zUnicodePath; char *zUtf8Name; zUnicodePath = fossil_utf8_to_filename(zPath); d = opendir(zUnicodePath); if( d ){ while( (pEntry=readdir(d))!=0 ){ Blob path; char *zSubpath; if( pEntry->d_name[0]=='.' ){ continue; } zUtf8Name = fossil_filename_to_utf8(pEntry->d_name); zSubpath = mprintf("%s/%s", zPath, zUtf8Name); fossil_filename_free(zUtf8Name); if( file_isdir(zSubpath)==1 ){ recon_read_dir(zSubpath); } blob_init(&path, 0, 0); blob_appendf(&path, "%s", zSubpath); if( blob_read_from_file(&aContent, blob_str(&path))==-1 ){ fossil_fatal("some unknown error occurred while reading \"%s\"", blob_str(&path)); } content_put(&aContent); blob_reset(&path); blob_reset(&aContent); free(zSubpath); fossil_print("\r%d", ++nFileRead); fflush(stdout); } closedir(d); }else { fossil_fatal("encountered error %d while trying to open \"%s\".", errno, g.argv[3]); } fossil_filename_free(zUnicodePath); }
/* ** Load the record identify by rid. Make sure we can reproduce it ** without error. ** ** Panic if anything goes wrong. If this procedure returns it means ** that everything is OK. */ static void verify_rid(int rid){ Blob uuid, hash, content; if( content_size(rid, 0)<0 ){ return; /* No way to verify phantoms */ } blob_zero(&uuid); db_blob(&uuid, "SELECT uuid FROM blob WHERE rid=%d", rid); if( blob_size(&uuid)!=UUID_SIZE ){ fossil_fatal("not a valid rid: %d", rid); } if( content_get(rid, &content) ){ sha1sum_blob(&content, &hash); blob_reset(&content); if( blob_compare(&uuid, &hash) ){ fossil_fatal("hash of rid %d (%b) does not match its uuid (%b)", rid, &hash, &uuid); } blob_reset(&hash); } blob_reset(&uuid); }
/* ** COMMAND: test-ticket-rebuild ** ** Usage: %fossil test-ticket-rebuild TICKETID|all ** ** Rebuild the TICKET and TICKETCHNG tables for the given ticket ID ** or for ALL. */ void test_ticket_rebuild(void){ db_find_and_open_repository(0, 0); if( g.argc!=3 ) usage("TICKETID|all"); if( fossil_strcmp(g.argv[2], "all")==0 ){ ticket_rebuild(); }else{ const char *zUuid; zUuid = db_text(0, "SELECT substr(tagname,5) FROM tag" " WHERE tagname GLOB 'tkt-%q*'", g.argv[2]); if( zUuid==0 ) fossil_fatal("no such ticket: %s", g.argv[2]); ticket_rebuild_entry(zUuid); } }
/* ** Get the current working directory. ** ** On windows, the name is converted from unicode to UTF8 and all '\\' ** characters are converted to '/'. No conversions are needed on ** unix. */ void win32_getcwd(char *zBuf, int nBuf){ int i; char *zUtf8; wchar_t *zWide = fossil_malloc( sizeof(wchar_t)*nBuf ); if( GetCurrentDirectoryW(nBuf, zWide)==0 ){ fossil_fatal("cannot find current working directory."); } zUtf8 = fossil_filename_to_utf8(zWide); fossil_free(zWide); for(i=0; zUtf8[i]; i++) if( zUtf8[i]=='\\' ) zUtf8[i] = '/'; strncpy(zBuf, zUtf8, nBuf); fossil_filename_free(zUtf8); }
/* ** Prompt the user for the password for g.urlUser. Store the result ** in g.urlPasswd. */ void url_prompt_for_password(void){ if( isatty(fileno(stdin)) ){ char *zPrompt = mprintf("\rpassword for %s: ", g.urlUser); Blob x; prompt_for_password(zPrompt, &x, 0); free(zPrompt); g.urlPasswd = mprintf("%b", &x); blob_reset(&x); }else{ fossil_fatal("missing or incorrect password for user \"%s\"", g.urlUser); } }
/* ** COMMAND: artifact* ** ** Usage: %fossil artifact ARTIFACT-ID ?OUTPUT-FILENAME? ?OPTIONS? ** ** Extract an artifact by its SHA1 hash and write the results on ** standard output, or if the optional 4th argument is given, in ** the named output file. ** ** Options: ** -R|--repository FILE Extract artifacts from repository FILE ** ** See also: finfo */ void artifact_cmd(void){ int rid; Blob content; const char *zFile; db_find_and_open_repository(OPEN_ANY_SCHEMA, 0); if( g.argc!=4 && g.argc!=3 ) usage("ARTIFACT-ID ?FILENAME? ?OPTIONS?"); zFile = g.argc==4 ? g.argv[3] : "-"; rid = name_to_rid(g.argv[2]); if( rid==0 ){ fossil_fatal("%s",g.zErrMsg); } content_get(rid, &content); blob_write_to_file(&content, zFile); }
/* ** Resets the timer associated with the given ID, as obtained via ** fossil_timer_start(), to the current CPU time values. */ sqlite3_uint64 fossil_timer_reset(int timerId){ if( timerId>0 && timerId<=FOSSIL_TIMER_COUNT ){ struct FossilTimer * start = &fossilTimerList[timerId-1]; if( !start->id ){ fossil_fatal("Invalid call to reset a non-allocated " "timer (#%d)", timerId); /*NOTREACHED*/ }else{ sqlite3_uint64 const rc = fossil_timer_fetch(timerId); fossil_cpu_times( &start->u, &start->s ); return rc; } } return 0; }
/* ** Returns the difference in CPU times in microseconds since ** fossil_timer_start() was called and returned the given timer ID (or ** since it was last reset). Returns 0 if timerId is out of range. */ sqlite3_uint64 fossil_timer_fetch(int timerId){ if( timerId>0 && timerId<=FOSSIL_TIMER_COUNT ){ struct FossilTimer * start = &fossilTimerList[timerId-1]; if( !start->id ){ fossil_fatal("Invalid call to fetch a non-allocated " "timer (#%d)", timerId); /*NOTREACHED*/ }else{ sqlite3_uint64 eu = 0, es = 0; fossil_cpu_times( &eu, &es ); return (eu - start->u) + (es - start->s); } } return 0; }
/* ** Reads symlink destination path and puts int into blob. ** Any prior content of the blob is discarded, not freed. ** ** Returns length of destination path. ** ** On windows, zeros blob and returns 0. */ int blob_read_link(Blob *pBlob, const char *zFilename){ #if !defined(_WIN32) char zBuf[1024]; ssize_t len = readlink(zFilename, zBuf, 1023); if( len < 0 ){ fossil_fatal("cannot read symbolic link %s", zFilename); } zBuf[len] = 0; /* null-terminate */ blob_zero(pBlob); blob_appendf(pBlob, "%s", zBuf); return len; #else blob_zero(pBlob); return 0; #endif }
/* ** COMMAND: test-cycle-compress ** ** Compress and uncompress each file named on the command line. ** Verify that the original content is recovered. */ void test_cycle_compress(void){ int i; Blob b1, b2, b3; for(i=2; i<g.argc; i++){ blob_read_from_file(&b1, g.argv[i]); blob_compress(&b1, &b2); blob_uncompress(&b2, &b3); if( blob_compare(&b1, &b3) ){ fossil_fatal("compress/uncompress cycle failed for %s", g.argv[i]); } blob_reset(&b1); blob_reset(&b2); blob_reset(&b3); } fossil_print("ok\n"); }
/* fossil bundle cat BUNDLE UUID... ** ** Write elements of a bundle on standard output */ static void bundle_cat_cmd(void){ int i; Blob x; verify_all_options(); if( g.argc<5 ) usage("cat BUNDLE UUID..."); bundle_attach_file(g.argv[3], "b1", 1); blob_zero(&x); for(i=4; i<g.argc; i++){ int blobid = db_int(0,"SELECT blobid FROM bblob WHERE uuid LIKE '%q%%'", g.argv[i]); if( blobid==0 ){ fossil_fatal("no such artifact in bundle: %s", g.argv[i]); } bundle_extract_item(blobid, &x); blob_write_to_file(&x, "-"); blob_reset(&x); } }
/* ** Get message string of the last system error. Return a pointer to the ** message string. Call fossil_mbcs_free() to deallocate any memory used ** to store the message string when done. */ static char *win32_get_last_errmsg(void){ DWORD nMsg; DWORD nErr = GetLastError(); LPWSTR tmp = NULL; char *zMsg = NULL; /* Try first to get the error text in english. */ nMsg = FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, nErr, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPWSTR) &tmp, 0, NULL ); if( !nMsg ){ /* No english, get what the system has available. */ nMsg = FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, nErr, 0, (LPWSTR) &tmp, 0, NULL ); } if( nMsg ){ zMsg = fossil_unicode_to_utf8(tmp); }else{ fossil_fatal("unable to get system error message."); } if( tmp ){ LocalFree((HLOCAL) tmp); } return zMsg; }