View source with raw comments or as raw
    1/*  Part of SWISH
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2015-2017, VU University Amsterdam
    7			      CWI Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(gitty_driver_files,
   37	  [ gitty_close/1,		% +Store
   38	    gitty_file/4,		% +Store, ?Name, ?Ext, ?Hash
   39
   40	    gitty_update_head/4,	% +Store, +Name, +OldCommit, +NewCommit
   41	    delete_head/2,		% +Store, +Name
   42	    set_head/3,			% +Store, +Name, +Hash
   43	    store_object/4,		% +Store, +Hash, +Header, +Data
   44	    delete_object/2,		% +Store, +Hash
   45
   46	    gitty_hash/2,		% +Store, ?Hash
   47	    load_plain_commit/3,	% +Store, +Hash, -Meta
   48	    load_object/5,		% +Store, +Hash, -Data, -Type, -Size
   49	    gitty_object_file/3,	% +Store, +Hash, -File
   50
   51	    repack_objects/2,           % +Store, +Options
   52            pack_objects/6,             % +Store, +Objs, +Packs, +PackDir,
   53					% -File, +Opts
   54            unpack_packs/1,             % +Store
   55            unpack_pack/2,              % +Store, +PackFile
   56
   57            attach_pack/2,		% +Store, +PackFile
   58            gitty_fsck/1,               % +Store
   59            fsck_pack/1,                % +PackFile
   60            load_object_from_pack/4,	% +Hash, -Data, -Type, -Size
   61
   62	    gitty_rescan/1		% Store
   63	  ]).   64:- use_module(library(apply)).   65:- use_module(library(zlib)).   66:- use_module(library(filesex)).   67:- use_module(library(lists)).   68:- use_module(library(apply)).   69:- use_module(library(error)).   70:- use_module(library(debug)).   71:- use_module(library(zlib)).   72:- use_module(library(hash_stream)).   73:- use_module(library(option)).   74:- use_module(library(dcg/basics)).

Gitty plain files driver

This version of the driver uses plain files to store the gitty data. It consists of a nested directory structure with files named after the hash. Objects and hash computation is the same as for git. The heads (files) are computed on startup by scanning all objects. There is a file ref/head that is updated if a head is updated. Other clients can watch this file and update their notion of the head. This implies that the store can handle multiple clients that can access a shared file system, optionally shared using NFS from different machines.

The store is simple and robust. The main disadvantages are long startup times as the store holds more objects and relatively high disk usage due to rounding the small objects to disk allocation units.

bug
- Shared access does not work on Windows.
   94:- dynamic
   95    head/4,				% Store, Name, Ext, Hash
   96    store/2,				% Store, Updated
   97    commit/3,				% Store, Hash, Meta
   98    heads_input_stream_cache/2,		% Store, Stream
   99    pack_object/6,                      % Hash, Type, Size, Offset, Store,PackFile
  100    attached_packs/1,                   % Store
  101    attached_pack/2.                    % Store, PackFile
  102
  103:- volatile
  104    head/4,
  105    store/2,
  106    commit/3,
  107    heads_input_stream_cache/2,
  108    pack_object/6,
  109    attached_packs/1,
  110    attached_pack/2.  111
  112:- multifile
  113    gitty:check_object/4.  114
  115% enable/disable syncing remote servers running on  the same file store.
  116% This facility requires shared access to files and thus doesn't work on
  117% Windows.
  118
  119:- if(current_prolog_flag(windows, true)).  120remote_sync(false).
  121:- else.  122remote_sync(true).
  123:- endif.
 gitty_close(+Store) is det
Close resources associated with a store.
  129gitty_close(Store) :-
  130    (   retract(heads_input_stream_cache(Store, In))
  131    ->  close(In)
  132    ;   true
  133    ),
  134    retractall(head(Store,_,_,_)),
  135    retractall(store(Store,_)),
  136    retractall(pack_object(_,_,_,_,Store,_)).
 gitty_file(+Store, ?File, ?Ext, ?Head) is nondet
True when File entry in the gitty store and Head is the HEAD revision.
  144gitty_file(Store, Head, Ext, Hash) :-
  145	gitty_scan(Store),
  146	head(Store, Head, Ext, Hash).
 load_plain_commit(+Store, +Hash, -Meta:dict) is semidet
Load the commit data as a dict. Loaded commits are cached in commit/3. Note that only adding a fact to the cache is synchronized. This means that during a race situation we may load the same object multiple times from disk, but this is harmless while a lock around the whole predicate serializes loading different objects, which is not needed.
  157load_plain_commit(Store, Hash, Meta) :-
  158	must_be(atom, Store),
  159	must_be(atom, Hash),
  160	commit(Store, Hash, Meta), !.
  161load_plain_commit(Store, Hash, Meta) :-
  162	load_object(Store, Hash, String, _, _),
  163	term_string(Meta0, String, []),
  164	with_mutex(gitty_commit_cache,
  165		   assert_cached_commit(Store, Hash, Meta0)),
  166	Meta = Meta0.
  167
  168assert_cached_commit(Store, Hash, Meta) :-
  169	commit(Store, Hash, Meta0), !,
  170	assertion(Meta0 =@= Meta).
  171assert_cached_commit(Store, Hash, Meta) :-
  172	assertz(commit(Store, Hash, Meta)).
 store_object(+Store, +Hash, +Header:string, +Data:string) is det
Store the actual object. The store must associate Hash with the concatenation of Hdr and Data.
  179store_object(Store, Hash, _Hdr, _Data) :-
  180        pack_object(Hash, _Type, _Size, _Offset, Store, _Pack), !.
  181store_object(Store, Hash, Hdr, Data) :-
  182        gitty_object_file(Store, Hash, Path),
  183        with_mutex(gitty_file, exists_or_create(Path, Out0)),
  184	(   var(Out0)
  185	->  true
  186	;   setup_call_cleanup(
  187		zopen(Out0, Out, [format(gzip)]),
  188		format(Out, '~s~s', [Hdr, Data]),
  189		close(Out))
  190	).
  191
  192exists_or_create(Path, _Out) :-
  193	exists_file(Path), !.
  194exists_or_create(Path, Out) :-
  195        file_directory_name(Path, Dir),
  196        make_directory_path(Dir),
  197        open(Path, write, Out, [encoding(utf8), lock(write)]).
 load_object(+Store, +Hash, -Data, -Type, -Size) is det
Load the given object.
  203load_object(_Store, Hash, Data, Type, Size) :-
  204        load_object_from_pack(Hash, Data0, Type0, Size0), !,
  205        f(Data0, Type0, Size0) = f(Data, Type, Size).
  206load_object(Store, Hash, Data, Type, Size) :-
  207	gitty_object_file(Store, Hash, Path),
  208        exists_file(Path),
  209	setup_call_cleanup(
  210	    gzopen(Path, read, In, [encoding(utf8)]),
  211	    read_object(In, Data, Type, Size),
  212	    close(In)).
 load_object_header(+Store, +Hash, -Type, -Size) is det
Load the header of an object
  218load_object_header(Store, Hash, Type, Size) :-
  219	gitty_object_file(Store, Hash, Path),
  220	setup_call_cleanup(
  221	    gzopen(Path, read, In, [encoding(utf8)]),
  222	    read_object_hdr(In, Type, Size),
  223	    close(In)).
  224
  225read_object(In, Data, Type, Size) :-
  226	read_object_hdr(In, Type, Size),
  227	read_string(In, _, Data).
  228
  229read_object_hdr(In, Type, Size) :-
  230	get_code(In, C0),
  231	read_hdr(C0, In, Hdr),
  232	phrase((nonblanks(TypeChars), " ", integer(Size)), Hdr),
  233	atom_codes(Type, TypeChars).
  234
  235read_hdr(C, In, [C|T]) :-
  236	C > 0, !,
  237	get_code(In, C1),
  238	read_hdr(C1, In, T).
  239read_hdr(_, _, []).
 gitty_rescan(?Store) is det
Update our view of the shared storage for all stores matching Store.
  246gitty_rescan(Store) :-
  247	retractall(store(Store, _)).
 gitty_scan(+Store) is det
Scan gitty store for files (entries), filling head/3. This is performed lazily at first access to the store.

@tdb Possibly we need to maintain a cached version of this index to avoid having to open all objects of the gitty store.

  258gitty_scan(Store) :-
  259	store(Store, _), !,
  260	remote_updates(Store).
  261gitty_scan(Store) :-
  262	with_mutex(gitty, gitty_scan_sync(Store)).
  263
  264:- thread_local
  265	latest/3.  266
  267gitty_scan_sync(Store) :-
  268	store(Store, _), !.
  269gitty_scan_sync(Store) :-
  270	remote_sync(true), !,
  271        gitty_attach_packs(Store),
  272	restore_heads_from_remote(Store).
  273gitty_scan_sync(Store) :-
  274        gitty_attach_packs(Store),
  275	read_heads_from_objects(Store).
 read_heads_from_objects(+Store) is det
Establish the head(Store,File,Ext,Hash) relation by reading all objects and adding a fact for the most recent commit.
  282read_heads_from_objects(Store) :-
  283	gitty_scan_latest(Store),
  284	forall(retract(latest(Name, Hash, _Time)),
  285	       assert_head(Store, Name, Hash)),
  286	get_time(Now),
  287	assertz(store(Store, Now)).
  288
  289assert_head(Store, Name, Hash) :-
  290	file_name_extension(_, Ext, Name),
  291        assertz(head(Store, Name, Ext, Hash)).
 gitty_scan_latest(+Store)
Scans the gitty store, extracting the latest version of each named entry.
  299gitty_scan_latest(Store) :-
  300	retractall(head(Store, _, _, _)),
  301	retractall(latest(_, _, _)),
  302	(   gitty_hash(Store, Hash),
  303	    load_object(Store, Hash, Data, commit, _Size),
  304	    term_string(Meta, Data, []),
  305	    _{name:Name, time:Time} :< Meta,
  306	    (	latest(Name, _, OldTime),
  307		OldTime > Time
  308	    ->	true
  309	    ;	retractall(latest(Name, _, _)),
  310		assertz(latest(Name, Hash, Time))
  311	    ),
  312	    fail
  313	;   true
  314	).
 gitty_hash(+Store, ?Hash) is nondet
True when Hash is an object in the store.
  321gitty_hash(Store, Hash) :-
  322	var(Hash), !,
  323        (   gitty_attach_packs(Store),
  324            pack_object(Hash, _Type, _Size, _Offset, Store, _Pack)
  325        ;   gitty_file_object(Store, Hash)
  326        ).
  327gitty_hash(Store, Hash) :-
  328        (   gitty_attach_packs(Store),
  329            pack_object(Hash, _Type, _Size, _Offset, Store, _Pack)
  330        ->  true
  331        ;   gitty_object_file(Store, Hash, File),
  332            exists_file(File)
  333        ).
  334
  335gitty_file_object(Store, Hash) :-
  336	access_file(Store, exist),
  337	directory_files(Store, Level0),
  338	member(E0, Level0),
  339	E0 \== '..',
  340	atom_length(E0, 2),
  341	directory_file_path(Store, E0, Dir0),
  342	directory_files(Dir0, Level1),
  343	member(E1, Level1),
  344	E1 \== '..',
  345	atom_length(E1, 2),
  346	directory_file_path(Dir0, E1, Dir),
  347	directory_files(Dir, Files),
  348	member(File, Files),
  349	atom_length(File, 36),
  350	atomic_list_concat([E0,E1,File], Hash).
 delete_object(+Store, +Hash)
Delete an existing object
  356delete_object(Store, Hash) :-
  357	gitty_object_file(Store, Hash, File),
  358	delete_file(File).
 gitty_object_file(+Store, +Hash, -Path) is det
True when Path is the file at which the object with Hash is stored.
  365gitty_object_file(Store, Hash, Path) :-
  366	sub_string(Hash, 0, 2, _, Dir0),
  367	sub_string(Hash, 2, 2, _, Dir1),
  368	sub_string(Hash, 4, _, 0, File),
  369	atomic_list_concat([Store, Dir0, Dir1, File], /, Path).
  370
  371
  372		 /*******************************
  373		 *	      SYNCING		*
  374		 *******************************/
 gitty_update_head(+Store, +Name, +OldCommit, +NewCommit) is det
Update the head of a gitty store for Name. OldCommit is the current head and NewCommit is the new head. If Name is created, and thus there is no head, OldCommit must be -.

This operation can fail because another writer has updated the head. This can both be in-process or another process.

  385gitty_update_head(Store, Name, OldCommit, NewCommit) :-
  386	with_mutex(gitty,
  387		   gitty_update_head_sync(Store, Name, OldCommit, NewCommit)).
  388
  389gitty_update_head_sync(Store, Name, OldCommit, NewCommit) :-
  390	remote_sync(true), !,
  391	setup_call_cleanup(
  392	    heads_output_stream(Store, HeadsOut),
  393	    gitty_update_head_sync(Store, Name, OldCommit, NewCommit, HeadsOut),
  394	    close(HeadsOut)).
  395gitty_update_head_sync(Store, Name, OldCommit, NewCommit) :-
  396	gitty_update_head_sync2(Store, Name, OldCommit, NewCommit).
  397
  398gitty_update_head_sync(Store, Name, OldCommit, NewCommit, HeadsOut) :-
  399	gitty_update_head_sync2(Store, Name, OldCommit, NewCommit),
  400	format(HeadsOut, '~q.~n', [head(Name, OldCommit, NewCommit)]).
  401
  402gitty_update_head_sync2(Store, Name, OldCommit, NewCommit) :-
  403	gitty_scan(Store),		% fetch remote changes
  404	(   OldCommit == (-)
  405	->  (   head(Store, Name, _, _)
  406	    ->	throw(error(gitty(file_exists(Name),_)))
  407	    ;	assert_head(Store, Name, NewCommit)
  408	    )
  409	;   (   retract(head(Store, Name, _, OldCommit))
  410	    ->	assert_head(Store, Name, NewCommit)
  411	    ;	throw(error(gitty(not_at_head(Name, OldCommit)), _))
  412	    )
  413	).
 remote_updates(+Store)
Watch for remote updates to the store. We only do this if we did not do so the last second.
  420:- dynamic
  421	last_remote_sync/2.  422
  423remote_updates(_) :-
  424	remote_sync(false), !.
  425remote_updates(Store) :-
  426	remote_up_to_data(Store), !.
  427remote_updates(Store) :-
  428	with_mutex(gitty, remote_updates_sync(Store)).
  429
  430remote_updates_sync(Store) :-
  431	remote_up_to_data(Store), !.
  432remote_updates_sync(Store) :-
  433	retractall(last_remote_sync(Store, _)),
  434	get_time(Now),
  435	asserta(last_remote_sync(Store, Now)),
  436	remote_update(Store).
  437
  438remote_up_to_data(Store) :-
  439	last_remote_sync(Store, Last),
  440	get_time(Now),
  441	Now-Last < 1.
  442
  443remote_update(Store) :-
  444	remote_updates(Store, List),
  445	maplist(update_head(Store), List).
  446
  447update_head(Store, head(Name, OldCommit, NewCommit)) :-
  448	(   OldCommit == (-)
  449	->  \+ head(Store, Name, _, _)
  450	;   retract(head(Store, Name, _, OldCommit))
  451	), !,
  452	assert_head(Store, Name, NewCommit).
  453update_head(_, _).
 remote_updates(+Store, -List) is det
Find updates from other gitties on the same filesystem. Note that we have to push/pop the input context to avoid creating a notion of an input context which possibly relate messages incorrectly to the sync file.
  462remote_updates(Store, List) :-
  463	heads_input_stream(Store, Stream),
  464	setup_call_cleanup(
  465	    '$push_input_context'(gitty_sync),
  466	    read_new_terms(Stream, List),
  467	    '$pop_input_context').
  468
  469read_new_terms(Stream, Terms) :-
  470	read(Stream, First),
  471	read_new_terms(First, Stream, Terms).
  472
  473read_new_terms(end_of_file, _, List) :- !,
  474	List = [].
  475read_new_terms(Term, Stream, [Term|More]) :-
  476	read(Stream, Term2),
  477	read_new_terms(Term2, Stream, More).
  478
  479heads_output_stream(Store, Out) :-
  480	heads_file(Store, HeadsFile),
  481	open(HeadsFile, append, Out,
  482	     [ encoding(utf8),
  483	       lock(exclusive)
  484	     ]).
  485
  486heads_input_stream(Store, Stream) :-
  487	heads_input_stream_cache(Store, Stream0), !,
  488	Stream = Stream0.
  489heads_input_stream(Store, Stream) :-
  490	heads_file(Store, File),
  491	between(1, 2, _),
  492	catch(open(File, read, In,
  493		   [ encoding(utf8),
  494		     eof_action(reset)
  495		   ]),
  496	      _,
  497	      create_heads_file(Store)), !,
  498	assert(heads_input_stream_cache(Store, In)),
  499	Stream = In.
  500
  501create_heads_file(Store) :-
  502	call_cleanup(
  503	    heads_output_stream(Store, Out),
  504	    close(Out)),
  505	fail.					% always fail!
  506
  507heads_file(Store, HeadsFile) :-
  508	ensure_directory(Store),
  509	directory_file_path(Store, ref, RefDir),
  510	ensure_directory(RefDir),
  511	directory_file_path(RefDir, head, HeadsFile).
 restore_heads_from_remote(Store)
Restore the known heads by reading the remote sync file.
  517restore_heads_from_remote(Store) :-
  518	heads_file(Store, File),
  519	exists_file(File),
  520	setup_call_cleanup(
  521	    open(File, read, In, [encoding(utf8)]),
  522	    restore_heads(Store, In),
  523	    close(In)), !,
  524	get_time(Now),
  525	assertz(store(Store, Now)).
  526restore_heads_from_remote(Store) :-
  527	read_heads_from_objects(Store),
  528	heads_file(Store, File),
  529	setup_call_cleanup(
  530	    open(File, write, Out, [encoding(utf8)]),
  531	    save_heads(Store, Out),
  532	    close(Out)), !.
  533
  534restore_heads(Store, In) :-
  535	read(In, Term0),
  536	Term0 = epoch(_),
  537	read(In, Term1),
  538	restore_heads(Term1, In, Store).
  539
  540restore_heads(end_of_file, _, _) :- !.
  541restore_heads(head(File, _, Hash), In, Store) :-
  542	retractall(head(Store, File, _, _)),
  543	assert_head(Store, File, Hash),
  544	read(In, Term),
  545	restore_heads(Term, In, Store).
  546
  547save_heads(Store, Out) :-
  548	get_time(Now),
  549	format(Out, 'epoch(~0f).~n~n', [Now]),
  550	forall(head(Store, File, _, Hash),
  551	       format(Out, '~q.~n', [head(File, -, Hash)])).
 delete_head(+Store, +Head) is det
Delete Head from Store. Used by gitty_fsck/1 to remove heads that have no commits. Should we forward this to remotes, or should they do their own thing?
  560delete_head(Store, Head) :-
  561	retractall(head(Store, Head, _, _)).
 set_head(+Store, +File, +Hash) is det
Set the head of the given File to Hash
  567set_head(Store, File, Hash) :-
  568	file_name_extension(_, Ext, File),
  569        (   head(Store, File, _, Hash0)
  570        ->  (   Hash == Hash0
  571            ->  true
  572            ;   asserta(head(Store, File, Ext, Hash)),
  573                retractall(head(Store, File, _, Hash0))
  574            )
  575        ;   asserta(head(Store, File, Ext, Hash))
  576        ).
  577
  578
  579		 /*******************************
  580		 *	      PACKS		*
  581		 *******************************/
  582
  583/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  584
  585<pack file> := <header>
  586               <file>*
  587<header>    := "gitty(Version).\n" <object>* "end_of_header.\n"
  588<object>    := obj(Hash, Type, Size, FileSize)
  589- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  590
  591pack_version(1).
 repack_objects(+Store, +Options) is det
Repack objects of Store for reduced disk usage and enhanced performance. By default this picks up all file objects of the store and all existing small pack files. Options:
small_pack(+Bytes)
Consider all packs with less than Bytes as small and repack them. Default 10Mb
min_files(+Count)
Do not repack if there are less than Count new files. Default 1,000.
  606:- debug(gitty(pack)).  607
  608repack_objects(Store, Options) :-
  609    option(min_files(MinFiles), Options, 1_000),
  610    findall(Object, gitty_file_object(Store, Object), Objects),
  611    length(Objects, NewFiles),
  612    debug(gitty(pack), 'Found ~D file objects', [NewFiles]),
  613    (   NewFiles >= MinFiles
  614    ->  pack_files(Store, ExistingPacks),
  615        option(small_pack(MaxSize), Options, 10_000_000),
  616        include(small_file(MaxSize), ExistingPacks, PackFiles),
  617        (   debugging(gitty(pack))
  618        ->  length(PackFiles, PackCount),
  619            debug(gitty(pack), 'Found ~D small packs', [PackCount])
  620        ;   true
  621        ),
  622        directory_file_path(Store, pack, PackDir),
  623        make_directory_path(PackDir),
  624        pack_objects(Store, Objects, PackFiles, PackDir, _PackFile, Options)
  625    ;   debug(gitty(pack), 'Nothing to do', [])
  626    ).
  627
  628small_file(MaxSize, File) :-
  629    size_file(File, Size),
  630    Size < MaxSize.
 pack_objects(+Store, +Objects, +Packs, +PackDir, -PackFile, +Options) is det
Pack the given objects and pack files into a new pack.
  637pack_objects(Store, Objects, Packs, PackDir, PackFile, Options) :-
  638    with_mutex(gitty_pack,
  639	       pack_objects_sync(Store, Objects, Packs, PackDir,
  640                                 PackFile, Options)).
  641
  642pack_objects_sync(_Store, [], [Pack], _, [Pack], _) :-
  643    !.
  644pack_objects_sync(Store, Objects, Packs, PackDir, PackFilePath, Options) :-
  645    length(Objects, ObjCount),
  646    length(Packs, PackCount),
  647    debug(gitty(pack), 'Repacking ~D objects and ~D packs',
  648          [ObjCount, PackCount]),
  649    maplist(object_info(Store), Objects, FileInfo),
  650    maplist(pack_info(Store), Packs, PackInfo),
  651    append([FileInfo|PackInfo], Info0),
  652    sort(1, @<, Info0, Info),           % remove possible duplicates
  653    (   debugging(gitty(pack))
  654    ->  (   PackCount > 0
  655        ->  length(Info, FinalObjCount),
  656            debug(gitty(pack), 'Total ~D objects', [FinalObjCount])
  657        ;   true
  658        )
  659    ;   true
  660    ),
  661    directory_file_path(PackDir, 'pack-create', TmpPack),
  662    setup_call_cleanup(
  663	(   open(TmpPack, write, Out0, [type(binary), lock(write)]),
  664	    open_hash_stream(Out0, Out, [algorithm(sha1)])
  665	),
  666        (   write_signature(Out),
  667            maplist(write_header(Out), Info),
  668            format(Out, 'end_of_header.~n', []),
  669            maplist(add_file(Out, Store), Info),
  670	    stream_hash(Out, SHA1)
  671        ),
  672        close(Out)),
  673    format(atom(PackFile), 'pack-~w.pack', [SHA1]),
  674    directory_file_path(PackDir, PackFile, PackFilePath),
  675    rename_file(TmpPack, PackFilePath),
  676    debug(gitty(pack), 'Attaching ~p', [PackFilePath]),
  677    attach_pack(Store, PackFilePath),
  678    remove_objects_after_pack(Store, Objects, Options),
  679    delete(Packs, PackFilePath, RmPacks),
  680    remove_repacked_packs(Store, RmPacks, Options),
  681    debug(gitty(pack), 'Packing completed', []).
  682
  683object_info(Store, Object, obj(Object, Type, Size, FileSize)) :-
  684    gitty_object_file(Store, Object, File),
  685    load_object_header(Store, Object, Type, Size),
  686    size_file(File, FileSize).
  687
  688pack_info(Store, PackFile, Objects) :-
  689    attach_pack(Store, PackFile),
  690    pack_read_header(PackFile, _Version, _DataOffset, Objects).
  691
  692write_signature(Out) :-
  693    pack_version(Version),
  694    format(Out, "gitty(~d).~n", [Version]).
  695
  696write_header(Out, obj(Object, Type, Size, FileSize)) :-
  697    format(Out, 'obj(~q,~q,~d,~d).~n', [Object, Type, Size, FileSize]).
 add_file(+Out, +Store, +Object) is det
Add Object from Store to the pack stream Out.
  703add_file(Out, Store, obj(Object, _Type, _Size, _FileSize)) :-
  704    gitty_object_file(Store, Object, File),
  705    exists_file(File),
  706    !,
  707    setup_call_cleanup(
  708        open(File, read, In, [type(binary)]),
  709        copy_stream_data(In, Out),
  710        close(In)).
  711add_file(Out, Store, obj(Object, Type, Size, FileSize)) :-
  712    pack_object(Object, Type, Size, Offset, Store, PackFile),
  713    setup_call_cleanup(
  714        open(PackFile, read, In, [type(binary)]),
  715        (   seek(In, Offset, bof, Offset),
  716            copy_stream_data(In, Out, FileSize)
  717        ),
  718        close(In)).
 gitty_fsck(+Store) is det
Validate all packs associated with Store
  725gitty_fsck(Store) :-
  726    pack_files(Store, PackFiles),
  727    maplist(fsck_pack, PackFiles).
 fsck_pack(+File) is det
Validate the integrity of the pack file File.
  733fsck_pack(File) :-
  734    debug(gitty(pack), 'fsck ~p', [File]),
  735    check_pack_hash(File),
  736    debug(gitty(pack), 'fsck ~p: checking objects', [File]),
  737    check_pack_objects(File),
  738    debug(gitty(pack), 'fsck ~p: done', [File]).
  739
  740check_pack_hash(File) :-
  741    file_base_name(File, Base),
  742    file_name_extension(Plain, Ext, Base),
  743    must_be(oneof([pack]), Ext),
  744    atom_concat('pack-', Hash, Plain),
  745    setup_call_cleanup(
  746        (   open(File, read, In0, [type(binary)]),
  747            open_hash_stream(In0, In, [algorithm(sha1)])
  748        ),
  749        (   setup_call_cleanup(
  750                open_null_stream(Null),
  751                copy_stream_data(In, Null),
  752                close(Null)),
  753            stream_hash(In, SHA1)
  754        ),
  755        close(In)),
  756    assertion(Hash == SHA1).
  757
  758check_pack_objects(PackFile) :-
  759    setup_call_cleanup(
  760        open(PackFile, read, In, [type(binary)]),
  761        (  read_header(In, Version, DataOffset, Objects),
  762           set_stream(In, encoding(utf8)),
  763           foldl(check_object(In, PackFile, Version), Objects, DataOffset, _)
  764        ),
  765        close(In)).
  766
  767check_object(In, PackFile, _Version,
  768             obj(Object, Type, Size, FileSize),
  769             Offset0, Offset) :-
  770    Offset is Offset0+FileSize,
  771    byte_count(In, Here),
  772    (   Here == Offset0
  773    ->  true
  774    ;   print_message(warning, pack(reposition(Here, Offset0))),
  775        seek(In, Offset0, bof, Offset0)
  776    ),
  777    (   setup_call_cleanup(
  778            zopen(In, In2, [multi_part(false), close_parent(false)]),
  779            catch(read_object(In2, Data, _0RType, _0RSize), E,
  780                  ( print_message(error,
  781                                  gitty(PackFile, fsck(read_object(Object, E)))),
  782                    fail)),
  783            close(In2))
  784    ->  byte_count(In, End),
  785        (   End == Offset
  786        ->  true
  787        ;   print_message(error,
  788                          gitty(PackFile, fsck(object_end(Object, End,
  789                                                          Offset0, Offset,
  790                                                          Data))))
  791        ),
  792        assertion(Type == _0RType),
  793        assertion(Size == _0RSize),
  794        gitty:check_object(Object, Data, Type, Size)
  795    ;   true
  796    ).
 gitty_attach_packs(+Store) is det
Attach all packs for Store
  803gitty_attach_packs(Store) :-
  804    attached_packs(Store),
  805    !.
  806gitty_attach_packs(Store) :-
  807    with_mutex(gitty_attach_packs,
  808               gitty_attach_packs_sync(Store)).
  809
  810gitty_attach_packs_sync(Store) :-
  811    attached_packs(Store),
  812    !.
  813gitty_attach_packs_sync(Store) :-
  814    pack_files(Store, PackFiles),
  815    maplist(attach_pack(Store), PackFiles),
  816    asserta(attached_packs(Store)).
  817
  818pack_files(Store, Packs) :-
  819    directory_file_path(Store, pack, PackDir),
  820    exists_directory(PackDir),
  821    !,
  822    directory_files(PackDir, Files),
  823    convlist(is_pack(PackDir), Files, Packs).
  824pack_files(_, []).
  825
  826is_pack(PackDir, File, Path) :-
  827    file_name_extension(_, pack, File),
  828    directory_file_path(PackDir, File, Path).
 attach_pack(+Store, +PackFile)
Load the index of Pack into memory.
  834attach_pack(Store, PackFile) :-
  835    attached_pack(Store, PackFile),
  836    !.
  837attach_pack(Store, PackFile) :-
  838    retractall(pack_object(_,_,_,_,_,PackFile)),
  839    pack_read_header(PackFile, Version, DataOffset, Objects),
  840    foldl(assert_object(Store, PackFile, Version), Objects, DataOffset, _),
  841    assertz(attached_pack(Store, PackFile)).
  842
  843pack_read_header(PackFile, Version, DataOffset, Objects) :-
  844    setup_call_cleanup(
  845        open(PackFile, read, In, [type(binary)]),
  846        read_header(In, Version, DataOffset, Objects),
  847        close(In)).
  848
  849read_header(In, Version, DataOffset, Objects) :-
  850    read(In, Signature),
  851    (   Signature = gitty(Version)
  852    ->  true
  853    ;   domain_error(gitty_pack_file, Objects)
  854    ),
  855    read(In, Term),
  856    read_index(Term, In, Objects),
  857    get_code(In, Code),
  858    assertion(Code == 0'\n),
  859    byte_count(In, DataOffset).
  860
  861read_index(end_of_header, _, []) :-
  862    !.
  863read_index(Object, In, [Object|T]) :-
  864    read(In, Term2),
  865    read_index(Term2, In, T).
  866
  867assert_object(Store, Pack, _Version,
  868              obj(Object, Type, Size, FileSize),
  869              Offset0, Offset) :-
  870    Offset is Offset0+FileSize,
  871    assertz(pack_object(Object, Type, Size, Offset0, Store, Pack)).
 detach_pack(+Store, +Pack) is det
Remove a pack file from the memory index.
  877detach_pack(Store, Pack) :-
  878    retractall(pack_object(_, _, _, _, Store, Pack)),
  879    retractall(attached_pack(Store, Pack)).
 load_object_from_pack(+Hash, -Data, -Type, -Size) is semidet
True when Hash is in a pack and can be loaded.
  885load_object_from_pack(Hash, Data, Type, Size) :-
  886    pack_object(Hash, Type, Size, Offset, _Store, Pack),
  887    setup_call_cleanup(
  888        open(Pack, read, In, [type(binary)]),
  889        read_object_at(In, Offset, Data, Type, Size),
  890        close(In)).
  891
  892read_object_at(In, Offset, Data, Type, Size) :-
  893    seek(In, Offset, bof, Offset),
  894    read_object_here(In, Data, Type, Size).
  895
  896read_object_here(In, Data, Type, Size) :-
  897    stream_property(In, encoding(Enc)),
  898    setup_call_cleanup(
  899        ( set_stream(In, encoding(utf8)),
  900          zopen(In, In2, [multi_part(false), close_parent(false)])
  901        ),
  902        read_object(In2, Data, Type, Size),
  903        ( close(In2),
  904          set_stream(In, encoding(Enc))
  905        )).
 unpack_packs(+Store) is det
Unpack all packs.
  911unpack_packs(Store) :-
  912    absolute_file_name(Store, AbsStore, [file_type(directory),
  913                                         access(read)]),
  914    pack_files(AbsStore, Packs),
  915    maplist(unpack_pack(AbsStore), Packs).
 unpack_pack(+Store, +Pack) is det
Turn a pack back into a plain object files
  921unpack_pack(Store, PackFile) :-
  922    pack_read_header(PackFile, _Version, DataOffset, Objects),
  923    setup_call_cleanup(
  924        open(PackFile, read, In, [type(binary)]),
  925        foldl(create_file(Store, In), Objects, DataOffset, _),
  926        close(In)),
  927    detach_pack(Store, PackFile),
  928    delete_file(PackFile).
  929
  930create_file(Store, In, obj(Object, _Type, _Size, FileSize), Offset0, Offset) :-
  931    Offset is Offset0+FileSize,
  932    gitty_object_file(Store, Object, Path),
  933    with_mutex(gitty_file, exists_or_recreate(Path, Out)),
  934	(   var(Out)
  935	->  true
  936	;   setup_call_cleanup(
  937                seek(In, Offset0, bof, Offset0),
  938                copy_stream_data(In, Out, FileSize),
  939                close(Out))
  940	).
  941
  942exists_or_recreate(Path, _Out) :-
  943	exists_file(Path), !.
  944exists_or_recreate(Path, Out) :-
  945        file_directory_name(Path, Dir),
  946        make_directory_path(Dir),
  947        open(Path, write, Out, [type(binary), lock(write)]).
 remove_objects_after_pack(+Store, +Objects, +Options) is det
Remove the indicated (file) objects from Store.
  954remove_objects_after_pack(Store, Objects, Options) :-
  955    debug(gitty(pack), 'Deleting plain files', []),
  956    maplist(delete_object(Store), Objects),
  957    (   option(prune_empty_directories(true), Options, true)
  958    ->  debug(gitty(pack), 'Pruning empty directories', []),
  959        prune_empty_directories(Store)
  960    ;   true
  961    ).
 remove_repacked_packs(+Store, +Packs, +Options)
Remove packs that have been repacked.
  967remove_repacked_packs(Store, Packs, Options) :-
  968    maplist(remove_pack(Store, Options), Packs).
  969
  970remove_pack(Store, _Options, Pack) :-
  971    detach_pack(Store, Pack),
  972    delete_file(Pack).
 prune_empty_directories(+Dir) is det
Prune directories that are empty below Dir. Dir itself is not removed, even if it is empty.
  979prune_empty_directories(Dir) :-
  980    prune_empty_directories(Dir, 0).
  981
  982prune_empty_directories(Dir, Level) :-
  983    directory_files(Dir, AllFiles),
  984    exclude(hidden, AllFiles, Files),
  985    (   Files == [],
  986        Level > 0
  987    ->  delete_directory_async(Dir)
  988    ;   convlist(prune_empty_directories(Dir, Level), Files, Left),
  989        (   Left == [],
  990            Level > 0
  991        ->  delete_directory_async(Dir)
  992        ;   true
  993        )
  994    ).
  995
  996hidden(.).
  997hidden(..).
  998
  999prune_empty_directories(Parent, Level0, File, _) :-
 1000    directory_file_path(Parent, File, Path),
 1001    exists_directory(Path),
 1002    !,
 1003    Level is Level0 + 1,
 1004    prune_empty_directories(Path, Level),
 1005    fail.
 1006prune_empty_directories(_, _, File, File).
 1007
 1008delete_directory_async(Dir) :-
 1009    with_mutex(gitty_file, delete_directory_async2(Dir)).
 1010
 1011delete_directory_async2(Dir) :-
 1012    catch(delete_directory(Dir), E,
 1013          (   \+ exists_directory(Dir)
 1014          ->  true
 1015          ;   \+ empty_directory(Dir)
 1016          ->  true
 1017          ;   throw(E)
 1018          )).
 1019
 1020empty_directory(Dir) :-
 1021    directory_files(Dir, AllFiles),
 1022    exclude(hidden, AllFiles, [])