Package: git-history
git-historyTools for analyzing Git history using SQLiteFor background on this project seegit-history: a tool for analyzing scraped data collected using Git and SQLiteInstallationInstall this tool usingpip:$ pip install git-historyDemosgit-history-demos.datasette.iohosts three example databases created using this tool:pge-outagesshows a history of PG&E (the electricity supplier)outages, using data collected insimonw/pge-outagesconverted usingpge-outages.shca-firesshows a history of fires in California reported onfire.ca.gov/incidents, from data insimonw/ca-fires-historyconverted usingca-fires.shsf-bay-511has records of San Francisco Bay Area traffic and transit incident data from511.org, collected indbreunig/511-events-historyconverted usingsf-bay-511.shThe demos are deployed usingDatasetteonGoogle Cloud Runbythis GitHub Actions workflow.UsageThis tool can be run against a Git repository that holds a file that contains JSON, CSV/TSV or some other format and which has multiple versions tracked in the Git history. ReadGit scraping: track changes over time by scraping to a Git repositoryto understand how you might create such a repository.Thefilecommand analyzes the history of an individual file within the repository, and generates a SQLite database table that represents the different versions of that file over time.The file is assumed to contain multiple objects - for example, the results of scraping an electricity outage map or a CSV file full of records.Assuming you have a file calledincidents.jsonthat is a JSON array of objects, with multiple versions of that file recorded in a repository. Each version of that file might look something like this:[{"IncidentID":"abc123","Location":"Corner of 4th and Vermont","Type":"fire"},{"IncidentID":"cde448","Location":"555 West Example Drive","Type":"medical"}]Change directory into the GitHub repository in question and run the following:git-history file incidents.db incidents.jsonThis will create a new SQLite database in theincidents.dbfile with three tables:commitscontaining a row for every commit, with ahashcolumn, thecommit_atdate and a foreign key to anamespace.itemcontaining a row for every item in every version of thefilename.jsonfile - with an extra_commitcolumn that is a foreign key back to thecommittable.namespacescontaining a single row. This allows you to build multiple tables for different files, using the--namespaceoption described below.The database schema for this example will look like this:CREATETABLE[namespaces]([id]INTEGERPRIMARYKEY,[name]TEXT);CREATEUNIQUEINDEX[idx_namespaces_name]ON[namespaces]([name]);CREATETABLE[commits]([id]INTEGERPRIMARYKEY,[namespace]INTEGERREFERENCES[namespaces]([id]),[hash]TEXT,[commit_at]TEXT);CREATEUNIQUEINDEX[idx_commits_namespace_hash]ON[commits]([namespace],[hash]);CREATETABLE[item]([IncidentID]TEXT,[Location]TEXT,[Type]TEXT);If you have 10 historic versions of theincidents.jsonfile and each one contains 30 incidents, you will end up with 10 * 30 = 300 rows in youritemtable.Track the history of individual items using IDsIf your objects have a unique identifier - or multiple columns that together form a unique identifier - you can use the--idoption to de-duplicate and track changes to each of those items over time.This provides a much more interesting way to apply this tool.If there is a unique identifier column calledIncidentIDyou could run the following:git-history file incidents.db incidents.json --id IncidentIDThe database schema used here is very different from the one used without the--idoption.If you have already imported history, the command will skip any commits that it has seen already and just process new ones. This means that even though an initial import could be slow subsequent imports should run a lot faster.This command will create six tables -commits,item,item_version,columns,item_changedandnamespaces.Here's the full schema:CREATETABLE[namespaces]([id]INTEGERPRIMARYKEY,[name]TEXT);CREATEUNIQUEINDEX[idx_namespaces_name]ON[namespaces]([name]);CREATETABLE[commits]([id]INTEGERPRIMARYKEY,[namespace]INTEGERREFERENCES[namespaces]([id]),[hash]TEXT,[commit_at]TEXT);CREATEUNIQUEINDEX[idx_commits_namespace_hash]ON[commits]([namespace],[hash]);CREATETABLE[item]([_id]INTEGERPRIMARYKEY,[_item_id]TEXT,[IncidentID]TEXT,[Location]TEXT,[Type]TEXT,[_commit]INTEGER);CREATEUNIQUEINDEX[idx_item__item_id]ON[item]([_item_id]);CREATETABLE[item_version]([_id]INTEGERPRIMARYKEY,[_item]INTEGERREFERENCES[item]([_id]),[_version]INTEGER,[_commit]INTEGERREFERENCES[commits]([id]),[IncidentID]TEXT,[Location]TEXT,[Type]TEXT,[_item_full_hash]TEXT);CREATETABLE[columns]([id]INTEGERPRIMARYKEY,[namespace]INTEGERREFERENCES[namespaces]([id]),[name]TEXT);CREATEUNIQUEINDEX[idx_columns_namespace_name]ON[columns]([namespace],[name]);CREATETABLE[item_changed]([item_version]INTEGERREFERENCES[item_version]([_id]),[column]INTEGERREFERENCES[columns]([id]),PRIMARYKEY([item_version],[column]));CREATEVIEWitem_version_detailASselectcommits.commit_atas_commit_at,commits.hashas_commit_hash,item_version.*,(selectjson_group_array(name)fromcolumnswhereidin(selectcolumnfromitem_changedwhereitem_version=item_version._id))as_changed_columnsfromitem_versionjoincommitsoncommits.id=item_version._commit;CREATEINDEX[idx_item_version__item]ON[item_version]([_item]);item tableTheitemtable will contain the most recent version of each row, de-duplicated by ID, plus the following additional columns:_id- a numeric integer primary key, used as a foreign key from theitem_versiontable._item_id- a hash of the values of the columns specified using the--idoption to the command. This is used for de-duplication when processing new versions._commit- a foreign key to thecommittable, representing the most recent commit to modify this item.item_version tableTheitem_versiontable will contain a row for each captured differing version of that item, plus the following columns:_id- a numeric ID for the item version record._item- a foreign key to theitemtable._version- the numeric version number, starting at 1 and incrementing for each captured version._commit- a foreign key to thecommittable._item_full_hash- a hash of this version of the item. This is used internally by the tool to identify items that have changed between commits.The other columns in this table represent columns in the original data that have changed since the previous version. If the value has not changed, it will be represented by anull.If a value was previously set but has been changed back tonullit will still be represented asnullin theitem_versionrow. You can identify these using theitem_changedmany-to-many table described below.You can use the--full-versionsoption to store full copies of the item at each version, rather than just storing the columns that have changed.item_version_detail viewThis SQL view joinsitem_versionagainstcommitsto add three further columns:_commit_atwith the date of the commit, and_commit_hashwith the Git commit hash.item_changedThis many-to-many table indicates exactly which columns were changed in anitem_version.item_versionis a foreign key to a row in theitem_versiontable.columnis a foreign key to a row in thecolumnstable.This table with have the largest number of rows, which is why it stores just two integers in order to save space.columnsThecolumnstable stores column names. It is referenced byitem_changed.id- an integer ID.name- the name of the column.namespace- a foreign key tonamespaces, for if multiple file histories are sharing the same database.Reserved column namesNote that_id,_item_full_hash,_item,_item_id,_version,_commit,_item_id,_commit_at,_commit_hash,_changed_columns,rowidare considered reserved column names for the purposes of this tool.If your data contains any of these they will be renamed to add a trailing underscore, for example_id_,_item_,_version_, to avoid clashing with the reserved columns.If you have a column with a name such as_commit_it will be renamed too, adding an additional trailing underscore, so_commit_becomes_commit__and_commit__becomes_commit___.Additional options--repo DIRECTORY- the path to the Git repository, if it is not the current working directory.--branch TEXT- the Git branch to analyze - defaults tomain.--id TEXT- as described above: pass one or more columns that uniquely identify a record, so that changes to that record can be calculated over time.--full-versions- instead of recording just the columns that have changed in theitem_versiontable record a full copy of each version of theh item.--ignore TEXT- one or more columns to ignore - they will not be included in the resulting database.--csv- treat the data is CSV or TSV rather than JSON, and attempt to guess the correct dialect--dialect- use a spcific CSV dialect. Options areexcel,excel-tabandunix- seethe Python CSV documentationfor details.--skip TEXT- one or more full Git commit hashes that should be skipped. You can use this if some of the data in your revision history is corrupted in a way that prevents this tool from working.--start-at TEXT- skip commits prior to the specified commit hash.--start-after TEXT- skip commits up to and including the specified commit hash, then start processing from the following commit.--convert TEXT- custom Python code for a conversion, described below.--import TEXT- additional Python modules to import for--convert.--ignore-duplicate-ids- if a single version of a file has the same ID in it more than once, the tool will exit with an error. Use this option to ignore this and instead pick just the first of the two duplicates.--namespace TEXT- use this if you wish to include the history of multiple different files in the same database. The default isitembut you can set it to something else, which will produce tables with names likeyournamespaceandyournamespace_version.--wal- Enable WAL mode on the created database file. Use this if you plan to run queries against the database whilegit-historyis creating it.--silent- don't show the progress bar.CSV and TSV dataIf the data in your repository is a CSV or TSV file you can process it by adding the--csvoption. This will attempt to detect which delimiter is used by the file, so the same option works for both comma- and tab-separated values.git-history file trees.db trees.csv --id TreeIDYou can also specify the CSV dialect using the--dialectoption.Custom conversions using --convertIf your data is not already either CSV/TSV or a flat JSON array, you can reshape it using the--convertoption.The format needed by this tool is an array of dictionaries, as demonstrated by theincidents.jsonexample above.If your data does not fit this shape, you can provide a snippet of Python code to converts the on-disk content of each stored file into a Python list of dictionaries.For example, if your stored files each look like this:{"incidents":[{"id":"552","name":"Hawthorne Fire","engines":3},{"id":"556","name":"Merlin Fire","engines":1}]}You could use the following Python snippet to convert them to the required format:json.loads(content)["incidents"](Thejsonmodule is exposed to your custom function by default.)You would then run the tool like this:git-history file database.db incidents.json \
  --id id \
  --convert 'json.loads(content)["incidents"]'Thecontentvariable is always abytesobject representing the content of the file at a specific moment in the repository's history.You can import additional modules using--import. This example shows how you could read a CSV file that uses;as the delimiter:git-history file trees.db ../sf-tree-history/Street_Tree_List.csv \
  --repo ../sf-tree-history \
  --import csv \
  --import io \
  --convert '
    fp = io.StringIO(content.decode("utf-8"))
    return list(csv.DictReader(fp, delimiter=";"))
    ' \
  --id TreeIDYou can import nested modules such asElementTreeusing--import xml.etree.ElementTree, then refer to them in your function body asxml.etree.ElementTree. For example, if your tracked data was in anitems.xmlfile that looked like this:<items><itemid="1"name="One"/><itemid="2"name="Two"/><itemid="3"name="Three"/></item>You could load it using the following--convertscript:git-history file items.xml --convert '
tree = xml.etree.ElementTree.fromstring(content)
return [el.attrib for el in tree.iter("item")]
' --import xml.etree.ElementTree --id idIf your Python code spans more than one line it needs to include areturnstatement.You can also use Python generators in your--convertcode, for example:git-history file stats.db package-stats/stats.json \
    --repo package-stats \
    --convert '
    data = json.loads(content)
    for key, counts in data.items():
        for date, count in counts.items():
            yield {
                "package": key,
                "date": date,
                "count": count
            }
    ' --id package --id dateThis conversion function expects data that looks like this:{"airtable-export":{"2021-05-18":66,"2021-05-19":60,"2021-05-20":87}}DevelopmentTo contribute to this tool, first checkout the code. Then create a new virtual environment:cd git-history
python -m venv venv
source venv/bin/activateOr if you are usingpipenv:pipenv shellNow install the dependencies and test dependencies:pip install -e '.[test]'To run the tests:pytestTo update the schema examples in this README file:cog -r README.md