Skip to content

Instantly share code, notes, and snippets.

@swinton
Created December 3, 2020 22:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swinton/74f77ef11adcbf98f4a23ed455331000 to your computer and use it in GitHub Desktop.
Save swinton/74f77ef11adcbf98f4a23ed455331000 to your computer and use it in GitHub Desktop.
Using GitHub's Git data API

Using GitHub's Git data API by Example

  1. Create a blob
  2. Create a tree
  3. Create a commit
  4. Create (or update) a ref

Create a blob

#!/bin/bash

set -e

export CONTENTFILE=$( mktemp )
export PAYLOADFILE=$( mktemp )

# Generate some random bytes
dd if=/dev/urandom count=1344 | base64 | jq --raw-input > $CONTENTFILE

# Generate payload
jq --null-input \
  --arg encoding "base64" \
  --argfile content "$CONTENTFILE" \
  '{"content": $content, "encoding": $encoding}' > $PAYLOADFILE

# Create blob
curl --request POST \
  --url https://api.github.com/repos/$GITHUB_REPOSITORY/git/blobs \
  --header "authorization: Bearer $GITHUB_TOKEN" \
  --header 'content-type: application/json' \
  --data @$PAYLOADFILE

Create a tree

#!/bin/bash

set -e

export BLOB_SHA=c81c957df98ce21517f174d1be8a218c28e60979
export BASE_TREE=1f95f517b75f95a8f415820837dc88b96a84bcfa
export PAYLOADFILE=$( mktemp )

# Generate payload
jq --null-input \
  --arg blob_sha "$BLOB_SHA" \
  --arg base_tree "$BASE_TREE" \
  '{"tree": [{"path": "random", "mode": "100644", "type": "blob", "sha": $blob_sha}], "base_tree": $base_tree}' > $PAYLOADFILE

# Create tree
curl --request POST \
  --url https://api.github.com/repos/$GITHUB_REPOSITORY/git/trees \
  --header "authorization: Bearer $GITHUB_TOKEN" \
  --header 'content-type: application/json' \
  --data @$PAYLOADFILE

Create a commit

#!/bin/bash

set -e

export TREE_SHA=42c82a7d910c5019e595eb9aa97c0cdff5ade9a8
export PARENT_SHA=ab25fc3591c5c6472c56f130f72e9d028be974fa
export PAYLOADFILE=$( mktemp )

# Generate payload
jq --null-input \
  --arg tree_sha "$TREE_SHA" \
  --arg parent_sha "$PARENT_SHA" \
  '{"message": "Commit this", "tree": $tree_sha, "parents": [$parent_sha]}' > $PAYLOADFILE

# Create commit
curl --request POST \
  --url https://api.github.com/repos/$GITHUB_REPOSITORY/git/commits \
  --header "authorization: Bearer $GITHUB_TOKEN" \
  --header 'content-type: application/json' \
  --data @$PAYLOADFILE

Create (or update) a ref

#!/bin/bash

set -e

export COMMIT_SHA=72a8ee8c042c44a5ea5ef4026e74101e31640724

# Update ref
gh api --method PATCH /repos/:owner/:repo/git/refs/heads/main \
  --field sha="$COMMIT_SHA"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment