Created
September 4, 2020 14:31
-
-
Save FreeCX/bd672d3ddada072dcc79d426e95c3909 to your computer and use it in GitHub Desktop.
Fake Git Repo Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime as dt | |
from hashlib import sha1 | |
import zlib | |
from flask import Flask, Response | |
app = Flask(__name__) | |
def hash(data): | |
x = sha1(data) | |
return x.digest(), x.hexdigest() | |
def generate_commit(tree, author, committer, msg): | |
curr_date = f'{int(dt.now().timestamp())} +0000' | |
data = f'tree {tree}\nauthor {author} {curr_date}\ncommitter {committer} {curr_date}\n\n{msg}\n' | |
commit = f'commit {len(data)}\x00{data}'.encode() | |
_, h = hash(commit) | |
return h, commit | |
def generate_tree(name, permission, file): | |
data = f'{permission} {name}\x00'.encode() + file | |
tree = f'tree {len(data)}\x00'.encode() + data | |
_, h = hash(tree) | |
return h, tree | |
def generate_blob(data): | |
blob = f'blob {len(data)}\x00{data}'.encode() | |
d, h = hash(blob) | |
return d, h, blob | |
head_ref = 'refs/heads/master' | |
blob_d, blob_hash, blob_data = generate_blob('Oh, Hi Mark!') | |
tree_hash, tree_data = generate_tree('README.md', '100644', blob_d) | |
commit_hash, commit_data = generate_commit(tree_hash, 'Your Dog <good-boi>', 'Your Cat <good-cat>', 'Hello there!') | |
data_by_hash = { | |
blob_hash: blob_data, | |
tree_hash: tree_data, | |
commit_hash: commit_data | |
} | |
@app.route('/<path:repo>/<path:folder>/<path:file>', methods=['GET']) | |
def refs(repo, folder, file): | |
if folder == 'info' and file.startswith('refs'): | |
return f'{commit_hash}\t{head_ref}\n', 200 | |
else: | |
return '', 400 | |
@app.route('/<path:repo>/HEAD', methods=['GET']) | |
def head(repo): | |
return f'ref: {head_ref}\n', 200 | |
@app.route('/<path:repo>/<path:folder>/<path:f1>/<path:f2>', methods=['GET']) | |
def objects(repo, folder, f1, f2): | |
data = data_by_hash.get(f1 + f2) | |
if data: | |
return Response(zlib.compress(data), content_type='application/octet-stream') | |
else: | |
return '', 400 | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment