#!/usr/bin/env python3

import json
from sys import argv
import os
import re
import pdb

# When run with no arguments, enumerate the dependencies in
# ./requirements.txt; given an argument, enumerate the dependencies listed in
# the requirements.txt in that directory

path = 'requirements.txt'
if len(argv) > 1:
    path = os.path.join(argv[1], 'requirements.txt')

from pip._internal.network.session import PipSession
from pip._internal.req import parse_requirements
deps = parse_requirements(path, session=PipSession())

dependencies = {}

for dependency in deps:
    dep = str(dependency.requirement)
    result = re.search(r"(\w+)([=<>~]+.*)", dep)
    lib = dep if result is None else result.group(1)
    version = "" if result is None else result.group(2)
    dependencies[lib] = version

print(json.dumps(dependencies))
