#!/usr/bin/python3
#
# depfinder-python - finds the python modules that a package needs.
#
# Part of depfinder. Licensed under the GPL v3.
#
# usage: depfinder-python <package-root> <python-file-list>
#
# Reads the python files listed in <python-file-list> (one per line,
# relative to <package-root>, where the package's files are), finds
# which modules they import and which python distributions the package
# declares in its metadata (*.dist-info/METADATA, *.egg-info/requires.txt)
# that are not in the package itself, and prints the path of the file on
# the system that provides each of them, one per line. Modules and
# distributions that can't be found are reported on stderr.
#
# Files in a pythonX.Y directory for another python version than the
# one running this (e.g. python2.7/site-packages) are skipped, with a
# warning, and so is their metadata.
#
# Test files (in test/ or tests/ directories, test_*.py, *_test.py and
# conftest.py) are skipped, since their imports are only needed to run
# the tests, and so is documentation (usr/doc, usr/share/doc), such as
# examples.
#
# Optional imports (only inside try blocks that catch ImportError, so
# the code works without them) are not dependencies: they are only
# listed on stderr, for the packager to consider as suggestions. The
# imports in their except blocks are fallbacks, only needed if what the
# try block imports can't be found.
#
# Nothing in the package is run: the files are only parsed (with ast),
# and modules are looked up the way python itself finds them (with
# importlib's PathFinder), which doesn't import them either.

import ast
import operator
import os
import platform
import re
import sys
import sysconfig
from importlib.machinery import PathFinder, EXTENSION_SUFFIXES

# Exceptions that make an import in a try block optional
OPTIONAL_EXCEPTIONS = {"ImportError", "ModuleNotFoundError", "Exception",
		       "BaseException"}


# Modules of python's standard library on other platforms (e.g. msvcrt on
# Windows), which are never installed here. Python 3.10 and later list
# the standard library for all platforms; for older ones, these are the
# ones of python 3.9 that only exist on Windows or macOS.
STDLIB_NAMES = getattr(sys, "stdlib_module_names", None) or \
	{"_msi", "_overlapped", "_scproxy", "_winapi", "msilib", "msvcrt", "nt",
	 "winreg", "winsound"}


def warn(msg):
	print("WARNING: " + msg, file=sys.stderr)


#
# Finding the imports in python files
#

def catches_import_errors(handler):
	"""Whether an except clause catches ImportError (or anything that
	includes it)."""
	if handler.type is None:
		return True
	types = handler.type.elts \
		if isinstance(handler.type, ast.Tuple) else [handler.type]
	return any(attr_name(t) in OPTIONAL_EXCEPTIONS for t in types)


def handles_import_errors(node):
	"""Whether a try statement catches ImportError, so the imports in its
	body are optional."""
	return any(catches_import_errors(h) for h in node.handlers)


def import_names(nodes):
	"""The absolute imports anywhere in some statements, as dotted names."""
	names = set()
	for top in nodes:
		# (ast.walk isn't recursive)
		for node in ast.walk(top):
			if isinstance(node, ast.Import):
				names |= {alias.name for alias in node.names}
			elif isinstance(node, ast.ImportFrom) and node.level == 0 \
			     and node.module:
				names.add(node.module)
	return frozenset(names)


def collect_imports(tree):
	"""The absolute imports in a parsed module, as a set of (dotted name,
	optional, fallback for) tuples. Optional imports are inside a try
	block that catches ImportError, so the code works without them.
	Imports in such an except block are fallbacks, only run when an
	import in the try block fails (e.g. "import Queue" after "try:
	import queue"): fallback for is a tuple with a set of names for each
	try block, and the import is only needed if one name in each set
	can't be found.

	The tree is walked with a list rather than recursively, since
	generated code can be nested much deeper than python's recursion
	limit (e.g. a long chain of "+")."""
	found = set()
	# (node, inside an optional block?, fallback for)
	todo = [(tree, False, ())]
	while todo:
		node, opt, conds = todo.pop()

		def add(name):
			if name:
				found.add((name, opt, conds))

		if isinstance(node, ast.Import):
			for alias in node.names:
				add(alias.name)
			continue
		if isinstance(node, ast.ImportFrom):
			# relative imports (from . import x) are always in the
			# package
			# (each name can be a module, e.g. two in "from nspkg import
			# two", which matters for namespace packages; for other
			# names the module itself is found)
			if node.level == 0 and node.module:
				for alias in node.names:
					add(node.module if alias.name == "*"
					    else node.module + "." + alias.name)
			continue
		if isinstance(node, ast.Call):
			# __import__("name") and importlib.import_module("name"),
			# when the name is given as a string
			arg = node.args[0] if node.args else None
			if attr_name(node.func) in ("__import__", "import_module") and \
			   isinstance(arg, ast.Constant) and isinstance(arg.value, str) \
			   and not arg.value.startswith("."):
				add(arg.value)
		elif isinstance(node, ast.Try):
			body_opt = opt or handles_import_errors(node)
			todo += [(n, body_opt, conds) for n in node.body]
			tried = import_names(node.body)
			for handler in node.handlers:
				if tried and catches_import_errors(handler):
					todo.append((handler, opt, conds + (tried,)))
				else:
					todo.append((handler, opt, conds))
			todo += [(n, opt, conds) for n in node.orelse + node.finalbody]
			continue
		elif isinstance(node, ast.If):
			# Only the branch that runs, if that can be told: "if
			# TYPE_CHECKING:" imports are only for type checkers, and
			# imports for other python versions aren't needed.
			try:
				known = static_condition(node.test)
			except RecursionError:
				known = None
			todo.append((node.test, opt, conds))
			if known is not False:
				todo += [(n, opt, conds) for n in node.body]
			if known is not True:
				todo += [(n, opt, conds) for n in node.orelse]
			continue
		todo += [(n, opt, conds) for n in ast.iter_child_nodes(node)]
	return found


def attr_name(node):
	"""The name of a Name or Attribute node (e.g. "PY2" for six.PY2)."""
	return node.id if isinstance(node, ast.Name) else \
		node.attr if isinstance(node, ast.Attribute) else None


def is_sys(node, name, module="sys"):
	"""Whether node is sys.<name> (or <module>.<name>)."""
	return isinstance(node, ast.Attribute) and node.attr == name and \
	       isinstance(node.value, ast.Name) and node.value.id == module


def static_value(node):
	"""The value of an expression that is known without running the
	code: constants, tuples of constants, and the python version
	(sys.version_info, sys.version_info[0], sys.version_info[:2],
	sys.version_info.major and .minor, sys.hexversion), the one python
	3 runs with, and the platform (sys.platform, os.name,
	platform.system()). Raises ValueError for anything else."""
	if isinstance(node, ast.Constant) and \
	   isinstance(node.value, (int, str)):
		return node.value
	if isinstance(node, ast.Tuple):
		return tuple(static_value(e) for e in node.elts)
	if is_sys(node, "version_info"):
		return tuple(sys.version_info)
	if is_sys(node, "hexversion"):
		return sys.hexversion
	if is_sys(node, "platform"):
		return sys.platform
	if is_sys(node, "name", "os"):
		return os.name
	if isinstance(node, ast.Call) and not node.args and not node.keywords \
	   and is_sys(node.func, "system", "platform"):
		return platform.system()
	if isinstance(node, ast.Attribute) and is_sys(node.value, "version_info") \
	   and node.attr in ("major", "minor", "micro"):
		return getattr(sys.version_info, node.attr)
	if isinstance(node, ast.Subscript) and is_sys(node.value, "version_info"):
		index = node.slice
		if isinstance(index, ast.Index):	# python < 3.9
			index = index.value
		if isinstance(index, ast.Slice):
			if index.step is not None:
				raise ValueError
			lower = static_value(index.lower) if index.lower else None
			upper = static_value(index.upper) if index.upper else None
			return tuple(sys.version_info)[lower:upper]
		return tuple(sys.version_info)[static_value(index)]
	raise ValueError


COMPARISONS = {ast.Eq: operator.eq, ast.NotEq: operator.ne,
	       ast.Lt: operator.lt, ast.LtE: operator.le,
	       ast.Gt: operator.gt, ast.GtE: operator.ge}


def static_condition(node):
	"""True or False if a condition is known without running the code,
	or None. Known are TYPE_CHECKING (False), PY2 and PY3 (as in six and
	many compatibility modules), comparisons of the python version, and
	comparisons of the platform (also sys.platform.startswith(...)), and
	not/and/or of those."""
	name = attr_name(node)
	if name == "TYPE_CHECKING" or name == "PY2":
		return False
	if name == "PY3":
		return True
	if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
		value = static_condition(node.operand)
		return None if value is None else not value
	if isinstance(node, ast.BoolOp):
		values = [static_condition(v) for v in node.values]
		if isinstance(node.op, ast.And):
			return False if False in values else \
				True if all(v is True for v in values) else None
		return True if True in values else \
			False if all(v is False for v in values) else None
	if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) \
	   and node.func.attr in ("startswith", "endswith") and \
	   len(node.args) == 1 and not node.keywords:
		try:
			value = static_value(node.func.value)
			arg = static_value(node.args[0])
			return getattr(value, node.func.attr)(arg)
		except (ValueError, TypeError, AttributeError):
			return None
	if isinstance(node, ast.Compare) and len(node.ops) == 1 and \
	   type(node.ops[0]) in COMPARISONS:
		try:
			return COMPARISONS[type(node.ops[0])](
				static_value(node.left), static_value(node.comparators[0]))
		except (ValueError, TypeError, IndexError):
			return None
	return None


def find_imports(path):
	"""Returns the imports of a python file (see collect_imports), or
	None if it isn't valid python 3. Raises OSError if it can't be read."""
	try:
		with open(path, "rb") as f:
			tree = ast.parse(f.read(), filename=path)
	except (SyntaxError, ValueError, UnicodeDecodeError, RecursionError,
		MemoryError):
		return None
	return collect_imports(tree)


def other_python_version(path):
	"""The python version of a path in a pythonX.Y directory (e.g.
	usr/lib64/python2.7/site-packages/foo.py), if it isn't the version of
	the python running this, or None."""
	m = re.search(r"(?:^|/)python(\d+\.\d+)/", path)
	if m and not is_this_python(m.group(1)):
		return m.group(1)
	return None


def is_this_python(version):
	"""Whether a python version ("3", "3.9") is the one running this."""
	this = [str(n) for n in sys.version_info[:2]]
	return version.split(".") == this[:len(version.split("."))]


def shebang_python_version(path):
	"""The python version that the #! line of a script runs it with, if
	it isn't the version of the python running this, or None. A plain
	"python" in the system's PATH is python 2 (on Slackware /usr/bin/python
	is python 2); one elsewhere (e.g. a virtualenv's) could be any."""
	try:
		with open(path, "rb") as f:
			line = f.readline(256).decode("utf-8", "replace")
	except OSError:
		return None
	if not line.startswith("#!"):
		return None
	words = line[2:].split()
	# (#!/usr/bin/env [-S] [options] python...)
	env = False
	while words and (os.path.basename(words[0]) == "env" or
			 words[0].startswith("-")):
		env = True
		words = words[1:]
	if not words:
		return None
	m = re.fullmatch(r"python(\d+(?:\.\d+)?)?", os.path.basename(words[0]))
	if not m:
		return None
	version = m.group(1)
	if not version:
		if not env and os.path.dirname(words[0]) not in \
		   ("/usr/bin", "/bin", "/usr/local/bin"):
			return None
		version = "2"
	if is_this_python(version):
		return None
	return version


def is_test_file(path):
	"""Whether a file is part of a test suite shipped in the package
	(e.g. site-packages/foo/tests/test_bar.py), whose imports (pytest,
	mock...) are only needed to run the tests."""
	parts = path.split(os.sep)
	name = parts[-1]
	return any(d in ("test", "tests") for d in parts[:-1]) or \
	       name == "conftest.py" or \
	       (name.startswith("test_") and name.endswith(".py")) or \
	       name.endswith("_test.py")


def is_doc_file(path):
	"""Whether a file is documentation (e.g. an example in
	usr/doc/foo-1.0/examples), which isn't run as part of the package."""
	return path.startswith(("usr/doc/", "usr/share/doc/"))


#
# Finding modules
#

def find_spec(dotted, paths):
	"""Finds a module the way python does, without importing anything.
	For namespace packages (directories without __init__.py, which can
	be split between packages) it goes down the dotted name as far as
	possible. Returns the spec, or None."""
	parts = dotted.split(".")
	try:
		spec = PathFinder.find_spec(parts[0], paths)
		i = 1
		while spec is not None and spec.origin in (None, "namespace") and \
		      i < len(parts):
			sub = PathFinder.find_spec(".".join(parts[:i + 1]),
				list(spec.submodule_search_locations))
			if sub is None:
				break
			spec = sub
			i += 1
	except (ImportError, ValueError):
		return None
	return spec


def spec_files(spec):
	"""The files (or, for namespace packages, directories, with a
	trailing "/" as in package records) that provide a module."""
	if spec.origin not in (None, "namespace"):
		return [spec.origin]
	return [os.path.join(loc, "") for loc in spec.submodule_search_locations]


def inside(path, root):
	return os.path.realpath(path).startswith(root)


def package_module_names(root):
	"""The names of all top-level modules anywhere in the package: python
	files, packages (directories with __init__.py) and compiled modules.
	Some applications put their modules in their own directory and add
	it to sys.path, so modules there count as included in the package
	too. The modules inside a package don't count (e.g. foo/yaml.py
	isn't the yaml module)."""
	names = set()
	for dirpath, dirnames, filenames in os.walk(root):
		if "__init__.py" in filenames:
			if not os.path.isfile(os.path.join(os.path.dirname(dirpath),
							   "__init__.py")):
				names.add(os.path.basename(dirpath))
			continue
		for f in filenames:
			if f.endswith(".py"):
				names.add(f[:-3])
			else:
				for suffix in EXTENSION_SUFFIXES:
					if f.endswith(suffix):
						names.add(f[:-len(suffix)])
						break
	return names


#
# Python metadata (declared requirements)
#

def normalize(name):
	return re.sub(r"[-_.]+", "-", name).lower()


def dist_name(entry):
	"""The distribution name in the name of a metadata directory or
	file: name-version.dist-info, name-version-py3.9.egg-info, or
	name.egg-info without a version."""
	for ext in (".dist-info", ".egg-info"):
		if entry.endswith(ext):
			entry = entry[:-len(ext)]
	return entry.split("-", 1)[0]


def marker_env():
	impl = sys.implementation
	iv = impl.version
	implver = "%d.%d.%d" % (iv.major, iv.minor, iv.micro)
	if iv.releaselevel != "final":
		implver += iv.releaselevel[0] + str(iv.serial)
	return {
		"implementation_name": impl.name,
		"implementation_version": implver,
		"os_name": os.name,
		"platform_machine": platform.machine(),
		"platform_python_implementation": platform.python_implementation(),
		"platform_release": platform.release(),
		"platform_system": platform.system(),
		"platform_version": platform.version(),
		"python_full_version": platform.python_version(),
		"python_version": "%d.%d" % sys.version_info[:2],
		"sys_platform": sys.platform,
		# requirements for extras are optional
		"extra": "",
	}


MARKER_TOKEN = re.compile(r"""\s*(?:
	(?P<str>'[^']*'|"[^"]*") |
	(?P<op><=|>=|==|!=|~=|===|<|>|not\s+in\b|in\b|\(|\)|and\b|or\b) |
	(?P<var>[A-Za-z_][A-Za-z0-9_.]*))""", re.X)


def version_key(v):
	return [int(x) if x.isdigit() else x for x in re.split(r"[.]", v)]


def compare(left, op, right):
	if op in ("in", "not in"):
		result = left in right
		return result if op == "in" else not result
	if op == "===":
		return left == right
	if re.match(r"^\d+(\.\d+)*$", left) and re.match(r"^\d+(\.\d+)*(\.\*)?$", right):
		lk = version_key(left)
		if right.endswith(".*"):
			rk = version_key(right[:-2])
			eq = lk[:len(rk)] == rk
			if op == "==":
				return eq
			if op == "!=":
				return not eq
		rk = version_key(right)
		if op == "~=":
			return lk >= rk and lk[:len(rk) - 1] == rk[:len(rk) - 1]
		lk += [0] * (len(rk) - len(lk))
		rk += [0] * (len(lk) - len(rk))
		left, right = lk, rk
	return {"<": left < right, "<=": left <= right, "==": left == right,
		"!=": left != right, ">=": left >= right, ">": left > right,
		"~=": left >= right}[op]


def evaluate_marker(marker, env):
	"""Evaluates a PEP 508 environment marker. Raises ValueError if it
	can't be parsed."""
	tokens = []
	pos = 0
	marker = marker.strip()
	while pos < len(marker):
		m = MARKER_TOKEN.match(marker, pos)
		if not m or m.end() == pos:
			raise ValueError(marker)
		pos = m.end()
		if m.group("str"):
			tokens.append(("val", m.group("str")[1:-1]))
		elif m.group("op"):
			tokens.append(("op", re.sub(r"\s+", " ", m.group("op"))))
		else:
			if m.group("var") not in env:
				raise ValueError(marker)
			tokens.append(("val", env[m.group("var")]))
	tokens.append(("end", None))
	i = 0

	def expr_or():
		nonlocal i
		result = expr_and()
		while tokens[i] == ("op", "or"):
			i += 1
			result = expr_and() or result
		return result

	def expr_and():
		nonlocal i
		result = expr_atom()
		while tokens[i] == ("op", "and"):
			i += 1
			result = expr_atom() and result
		return result

	def expr_atom():
		nonlocal i
		if tokens[i] == ("op", "("):
			i += 1
			result = expr_or()
			if tokens[i] != ("op", ")"):
				raise ValueError(marker)
			i += 1
			return result
		if tokens[i][0] != "val" or tokens[i + 1][0] != "op" or \
		   tokens[i + 2][0] != "val":
			raise ValueError(marker)
		result = compare(tokens[i][1], tokens[i + 1][1], tokens[i + 2][1])
		i += 3
		return result

	result = expr_or()
	if tokens[i][0] != "end":
		raise ValueError(marker)
	return result


REQUIREMENT_NAME = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)")


def requirement(line, extra_marker, env):
	"""The name in a requirement line, if it applies here (no extra and
	a true marker), or None."""
	line = line.split("#", 1)[0].strip()
	m = REQUIREMENT_NAME.match(line)
	if not m:
		return None
	markers = [extra_marker] if extra_marker else []
	if ";" in line:
		markers.append(line.split(";", 1)[1])
	for marker in markers:
		try:
			if not evaluate_marker(marker, env):
				return None
		except ValueError:
			# can't tell, so it might be needed
			pass
	return m.group(1)


def read_lines(path, root):
	"""The lines of a text file in the package, or none, with a warning,
	if it can't be read."""
	try:
		with open(path, "rb") as f:
			return f.read().decode("utf-8", "replace").splitlines()
	except OSError:
		warn("could not read %s." % os.path.relpath(path, root))
		return []


def declared_requirements(root):
	"""The distributions that the package metadata requires, as
	{normalized name: (name, package distribution)}, and the normalized
	names of the distributions in the package. Metadata for another
	python version (e.g. in usr/lib64/python2.7) is skipped, with a
	warning, since its requirements are for that python."""
	env = marker_env()
	pyver = env["python_version"]
	requires = {}
	own = set()
	for dirpath, dirnames, filenames in sorted(os.walk(root)):
		base = os.path.basename(dirpath)
		other = other_python_version(os.path.relpath(dirpath, root) + "/")
		if other and base.endswith((".dist-info", ".egg-info")):
			warn("not checking the requirements of %s, which is for python %s."
			     % (dist_name(base), other))
			continue
		if base.endswith(".dist-info") and "METADATA" in filenames:
			dist = dist_name(base)
			lines = []
			for line in read_lines(os.path.join(dirpath, "METADATA"), root):
				if not line.strip():
					break
				if line.lower().startswith("requires-dist:"):
					lines.append((line.split(":", 1)[1], None))
		elif base.endswith(".egg-info"):
			dist = dist_name(base)
			lines = []
			if "requires.txt" in filenames:
				section = None
				for line in read_lines(os.path.join(dirpath, "requires.txt"), root):
					if line.strip().startswith("["):
						# [extra], [extra:marker] or [:marker]
						section = line.strip()[1:-1]
						continue
					if section is None:
						lines.append((line, None))
					elif section.startswith(":"):
						lines.append((line, section[1:]))
					# extras are optional
		else:
			continue
		own.add(normalize(dist))
		for line, marker in lines:
			name = requirement(line, marker, env)
			if name:
				requires.setdefault(normalize(name), (name, dist))
	for name in own:
		requires.pop(name, None)
	return requires, own


def find_distribution(name, paths):
	"""The metadata file of an installed distribution, or None."""
	for path in paths:
		try:
			entries = os.listdir(path)
		except OSError:
			continue
		for entry in sorted(entries):
			for ext, meta in ((".dist-info", "METADATA"),
					  (".egg-info", "PKG-INFO")):
				if not entry.endswith(ext):
					continue
				if normalize(dist_name(entry)) == name:
					full = os.path.join(path, entry)
					if os.path.isdir(full):
						full = os.path.join(full, meta)
					if os.path.exists(full):
						return full
	return None


#
# Main
#

def main():
	if len(sys.argv) != 3:
		print("usage: depfinder-python <package-root> <python-file-list>",
		      file=sys.stderr)
		return 1
	# (file names that aren't valid UTF-8 are passed through as they are)
	sys.stdout.reconfigure(errors="surrogateescape")
	sys.stderr.reconfigure(errors="surrogateescape")
	root = os.path.join(os.path.realpath(sys.argv[1]), "")
	with open(sys.argv[2], "rb") as f:
		files = [l for l in f.read().decode("utf-8", "surrogateescape").split("\n") if l]

	# Where python looks for modules on this system (without this
	# script's own directory). depfinder runs this with python3 -E, so
	# PYTHONPATH isn't used; the tests put their fake installed modules
	# in DEPFINDERPYTHONPATH instead.
	extra = os.environ.get("DEPFINDERPYTHONPATH")
	if extra:
		sys.path[1:1] = extra.split(os.pathsep)
	here = os.path.dirname(os.path.realpath(__file__))
	syspaths = [p for p in sys.path
		    if p and os.path.realpath(p) != here and os.path.isdir(p)]
	# The same directories in the package, and any other
	# site-packages directories in it (e.g. for another python version)
	pkgpaths = [os.path.join(root, p.lstrip("/")) for p in syspaths]
	for dirpath, dirnames, filenames in os.walk(root):
		if os.path.basename(dirpath) in ("site-packages", "dist-packages"):
			pkgpaths.append(dirpath)
			dirnames[:] = []
	pkgpaths = [p for p in pkgpaths if os.path.isdir(p)]

	# Collect the imports of each file, with the directory of the file,
	# where python looks first for the modules a script imports (but
	# not for the modules inside a package, e.g. foo/yaml.py importing
	# yaml)
	uses = []		# (dotted name, optional, fallback for, dirs)
	other_versions = {}	# python version -> number of files skipped
	checked = False		# any python 3 file checked?
	for f in files:
		path = os.path.join(root, f)
		if is_test_file(os.path.relpath(path, root)) or \
		   is_doc_file(os.path.relpath(path, root)):
			continue
		# Files for another python version (e.g. in python2.7/) would
		# be checked against the wrong python
		# (and scripts that their #! line runs with another python; the
		# #! line of a .py module doesn't count, many python 3 modules
		# still have an old "#!/usr/bin/env python" line, and they are
		# imported, not run)
		other = other_python_version(os.path.relpath(path, root))
		if not other and not path.endswith(".py"):
			other = shebang_python_version(path)
		if other:
			other_versions[other] = other_versions.get(other, 0) + 1
			continue
		try:
			found = find_imports(path)
		except OSError:
			warn("could not read %s." % os.path.relpath(path, root))
			continue
		if found is None:
			warn("could not parse %s as python 3." % os.path.relpath(path, root))
			continue
		checked = True
		d = os.path.dirname(path)
		dirs = () if os.path.isfile(os.path.join(d, "__init__.py")) else (d,)
		uses += [(name, opt, conds, dirs) for name, opt, conds in found]

	for version in sorted(other_versions):
		count = other_versions[version]
		warn("not checking %d python file%s, which %s for python %s."
		     % (count, "s" if count > 1 else "", "are" if count > 1 else "is",
			version))

	builtin = set(sys.builtin_module_names)
	inpkg_names = package_module_names(root)
	needed = set()
	missing = set()
	optional_modules = set()
	# python's standard library (site-packages is inside it)
	stdlib = {os.path.join(os.path.realpath(sysconfig.get_paths()[k]), "")
		  for k in ("stdlib", "platstdlib")}

	def in_stdlib(path):
		return any(inside(path, d) for d in stdlib) and \
		       "/site-packages/" not in path and "/dist-packages/" not in path

	# On the system, the package's directories are searched too, so
	# that namespace packages split between the package and the system
	# are found
	paths = []
	for s, p in zip(syspaths, [os.path.join(root, s.lstrip("/")) for s in syspaths]):
		paths += [p, s]
	cache = {}

	def lookup(name, dirs):
		"""Where a module is: "builtin", "package" (in the package),
		"system", "other" (python's standard library on another
		platform, e.g. msvcrt) or None (not found), and its spec on
		the system."""
		if (name, dirs) not in cache:
			top = name.split(".")[0]
			spec = None
			if top in builtin or top in ("__future__", "__main__"):
				where = "builtin"
			elif top in inpkg_names or \
			     (spec_in_pkg(name, list(dirs) + pkgpaths)):
				where = "package"
			else:
				spec = find_spec(name, paths)
				where = "system" if spec is not None else \
					"other" if top in STDLIB_NAMES else None
			cache[name, dirs] = (where, spec)
		return cache[name, dirs]

	def spec_in_pkg(name, dirs):
		spec = find_spec(name, dirs)
		return spec is not None and spec.origin not in (None, "namespace")

	# Fallback imports are only needed if one of the imports they are a
	# fallback for can't be found (in each try block)
	imports = {}		# dotted name -> (optional?, set of script dirs)
	for name, opt, conds, dirs in uses:
		if not all(any(lookup(t, dirs)[0] in (None, "other") for t in tried)
			   for tried in conds):
			continue
		old = imports.get(name, (True, set()))
		imports[name] = (old[0] and opt, old[1] | set(dirs))

	for name in sorted(imports):
		optional, dirs = imports[name]
		top = name.split(".")[0]
		where, spec = lookup(name, tuple(sorted(dirs)))
		if where in ("builtin", "package", "other"):
			continue
		# Optional imports aren't dependencies. They are listed, except
		# the ones from python's standard library.
		if optional:
			if spec is None or not all(in_stdlib(f) for f in spec_files(spec)):
				optional_modules.add(top)
			continue
		if spec is None:
			missing.add(top)
			continue
		for path in spec_files(spec):
			if not inside(path, root):
				needed.add(path)

	for top in sorted(missing):
		warn("python module %s not found." % top)
	# (a module imported both ways, e.g. import a.b and an optional
	# import a.c, is needed anyway)
	required_tops = {n.split(".")[0] for n, (opt, d) in imports.items() if not opt}
	optional_modules -= required_tops
	if optional_modules:
		print("NOTE: optional python modules, not added as dependencies: %s"
		      % ", ".join(sorted(optional_modules)), file=sys.stderr)

	# The distributions the package declares in its metadata
	requires, own = declared_requirements(root)
	for name in sorted(requires):
		meta = find_distribution(name, syspaths)
		if meta is None:
			warn("python package %s, required by %s, not found." % requires[name])
		else:
			needed.add(meta)

	# The python that runs the files: this one for python 3 files
	# (python3), and python 2.7 (python2) for the python 2 ones, which
	# aren't checked
	if checked and sys.executable:
		needed.add(os.path.realpath(sys.executable))
	if any(v.split(".")[0] == "2" for v in other_versions):
		needed.add("/usr/bin/python2.7")

	for path in sorted(needed):
		print(path)
	return 0


if __name__ == "__main__":
	sys.exit(main())
