Skip to content

Instantly share code, notes, and snippets.

@adnelson
Created May 19, 2016 18:43
Show Gist options
  • Save adnelson/f02c49bcba782fd81c504d7b3a549f00 to your computer and use it in GitHub Desktop.
Save adnelson/f02c49bcba782fd81c504d7b3a549f00 to your computer and use it in GitHub Desktop.
import sys
import json
import requests
import re
def get_license(package_name):
"""Find the license of an NPM package, come hell or high water."""
url = "https://registry.npmjs.org/{}".format(package_name)
resp = requests.get(url).json()
def read_license(license_):
if isinstance(license_, basestring):
return license_
elif isinstance(license_, list):
return read_license(license_[0])
else:
return license_["type"]
if "license" in resp:
return read_license(resp["license"])
elif "licenses" in resp:
return read_license(resp["licenses"][0])
else:
for version, info in resp["versions"].items():
if "license" in info:
return read_license(info["license"])
elif "licenses" in info:
return read_license(info["licenses"][0])
if "repository" in resp:
repo_url = resp["repository"]["url"]
if "github.com" in repo_url:
if repo_url.endswith(".git"):
repo_url = repo_url[:-4]
_url = repo_url\
.replace("git+ssh://", "https://")\
.replace("git://", "https://")\
.replace("git@", "")\
.replace("github.com", "raw.githubusercontent.com") \
.replace(".com:", ".com/")\
+ "/master/package.json"
if not _url.startswith("http"):
_url = "https://" + _url
pkg_json = json.loads(requests.get(_url).content)
if "license" in pkg_json:
return read_license(pkg_json["license"])
elif "licenses" in pkg_json:
return read_license(pkg_json["licenses"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment