Page MenuHomeDevCentral

bin/resolve-hash

Authored By
dereckson
Mar 5 2022, 14:52
Size
2 KB
Referenced Files
None
Subscribers
None

bin/resolve-hash

#!/usr/bin/env python3
# -------------------------------------------------------------
# Resolve a hash
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Project: Nasqueron
# Author: Sébastien Santoro aka Dereckson
# Description: Query sources like Phabricator to find a known
# hash and return if found an URL representation.
# This is intended to resolve Git hash.
# License: BSD-2-Clause
# -------------------------------------------------------------
import json
import os
import requests
import sys
# -------------------------------------------------------------
# Phabricator
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def call_phabricator_api(api_url, token, method, parameters):
parameters["api.token"] = token
r = requests.post(api_url + method, data=parameters)
if r.status_code != 200:
return None
result = r.json()["result"]
if result is None:
return None
return result["data"]
def query_phabricator_instance(api_url, token, commit_hash):
result = call_phabricator_api(
api_url,
token,
"diffusion.commit.search",
{"constraints[identifiers][0]": commit_hash}
)
if result is None:
return None
try:
commit = result[0]
except IndexError:
# Query works but didn't found anything
return None
return resolve_phabricator_commit_url(
api_url, token, commit_hash, commit["fields"]["repositoryPHID"]
)
def resolve_phabricator_commit_url(api_url, token, commit_hash, repositoryPhid):
callsign = query_get_repository_callsign(api_url, token, repositoryPhid)
return api_url.replace("api/", "") + callsign + commit_hash
def query_get_repository_callsign(api_url, token, repositoryPhid):
result = call_phabricator_api(
api_url,
token,
"diffusion.repository.search",
{"constraints[phids][0]": repositoryPhid}
)
return "r" + result[0]["fields"]["callsign"]
def query_phabricator_instances(hash):
with open(os.environ["HOME"] + "/.arcrc", "r") as fd:
instances = json.load(fd)
for api_url, args in instances["hosts"].items():
url = query_phabricator_instance(api_url, args["token"], hash)
if url is not None:
return url
return None
# -------------------------------------------------------------
# Application entry point
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def run(hash):
# Strategy I. Query Phabricator diffusion.commit.search
result = query_phabricator_instances(hash)
if result is not None:
print(result)
sys.exit(0)
# Nothing found
sys.exit(1)
if __name__ == "__main__":
argc = len(sys.argv)
if argc < 2:
print(f"Usage: {sys.argv[0]} <hash>", file=sys.stderr)
sys.exit(1)
run(sys.argv[1])

File Metadata

Mime Type
text/plain; charset=utf-8
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
960003
Default Alt Text
bin/resolve-hash (2 KB)

Event Timeline