|
#!/usr/bin/env python |
|
|
|
import argparse |
|
import sys |
|
import hashlib |
|
import warnings |
|
|
|
from pathlib import Path |
|
|
|
import htsget |
|
import git |
|
import ptvsd |
|
|
|
from ruamel.yaml import YAML |
|
|
|
yaml = YAML() |
|
|
|
info_string = """ |
|
Reading from {url} with: |
|
reference_name: {reference_name} |
|
start: {start} |
|
end: {end} |
|
""" |
|
|
|
|
|
def smudge(filename): |
|
"""Convert description to bytes on disk via htsget.""" |
|
buffer = sys.stdin.buffer.read() |
|
try: |
|
data = yaml.load(buffer.decode()) |
|
except UnicodeDecodeError: |
|
sys.stdout.buffer.write(buffer) |
|
return |
|
sys.stderr.write(info_string.format(**data)) |
|
sys.stderr.flush() |
|
data.insert(1, "output", sys.stdout.buffer) |
|
|
|
htsget.get(**data) |
|
|
|
|
|
def clean(filename): |
|
"""Replace the file with a pointer.""" |
|
blob = sys.stdin.buffer.read() |
|
sys.stdin.close() |
|
hash = compute_git_hash(blob) |
|
spec = Path(".renku/htsget") / hash |
|
try: |
|
with spec.open("r") as f: |
|
sys.stdout.write(f.read()) |
|
except Exception: |
|
warnings.warn("No corresponding metadata found for hash {}".format(hash[:16])) |
|
sys.stdout.buffer.write(blob) |
|
|
|
|
|
def compute_git_hash(data): |
|
"""Compute the git sha-1.""" |
|
blob_str = b"blob " + str(len(data)).encode() + b"\0" + data |
|
return hashlib.sha1(blob_str).hexdigest() |
|
|
|
|
|
def convert(filename): |
|
"""Convert spec to bytes.""" |
|
with open(filename, "r") as f: |
|
buf = f.read(8) |
|
if buf[2:] == "htsget": |
|
f.seek(0) |
|
data = yaml.load(f.read()) |
|
|
|
with open(filename, "wb") as f: |
|
data.insert(1, "output", f) |
|
htsget.get(**data) |
|
|
|
r = git.Repo() |
|
hash = r.git.hash_object(filename) |
|
|
|
spec = Path(".renku/htsget") / hash |
|
spec.parent.mkdir(exist_ok=True) |
|
|
|
data.pop("output") |
|
with spec.open("w") as f: |
|
yaml.dump(data, f) |
|
|
|
|
|
if __name__ == "__main__": |
|
parser = argparse.ArgumentParser(description="Convert htsget spec.") |
|
parser.add_argument("action", help="Which action to undertake - smudge or clean") |
|
parser.add_argument("filename", help="Name of the file") |
|
parser.add_argument("--debug", action="store_true") |
|
args = parser.parse_args() |
|
|
|
if args.debug: |
|
print("Waiting for debugger attach") |
|
ptvsd.enable_attach(address=("localhost", 5678), redirect_output=True) |
|
ptvsd.wait_for_attach() |
|
breakpoint() |
|
|
|
if args.action == "smudge": |
|
smudge(args.filename) |
|
elif args.action == "clean": |
|
clean(args.filename) |
|
elif args.action == "convert": |
|
convert(args.filename) |