-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkip
executable file
·144 lines (126 loc) · 6.2 KB
/
kip
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python3
import os
import sys
import re
import subprocess
import requests
import time
from typing import Set, Tuple, List, Dict
# List of Python built-in modules
BUILTIN_MODULES = {
'abc', 'aifc', 'argparse', 'array', 'ast', 'asynchat', 'asyncio', 'asyncore', 'atexit',
'audioop', 'base64', 'bdb', 'binascii', 'binhex', 'bisect', 'builtins', 'bz2', 'calendar',
'cgi', 'cgitb', 'chunk', 'cmath', 'cmd', 'code', 'codecs', 'codeop', 'collections', 'colorsys',
'compileall', 'concurrent', 'configparser', 'contextlib', 'copy', 'copyreg', 'crypt', 'csv',
'ctypes', 'curses', 'dataclasses', 'datetime', 'dbm', 'decimal', 'difflib', 'dis', 'distutils',
'doctest', 'dummy_threading', 'email', 'encodings', 'ensurepip', 'enum', 'errno', 'faulthandler',
'fcntl', 'filecmp', 'fileinput', 'fnmatch', 'formatter', 'fractions', 'ftplib', 'functools',
'gc', 'getopt', 'getpass', 'gettext', 'glob', 'gzip', 'hashlib', 'heapq', 'hmac', 'html', 'http',
'imaplib', 'imghdr', 'imp', 'importlib', 'inspect', 'io', 'ipaddress', 'itertools', 'json',
'keyword', 'lib2to3', 'linecache', 'locale', 'logging', 'lzma', 'mailbox', 'mailcap', 'marshal',
'math', 'mimetypes', 'modulefinder', 'multiprocessing', 'netrc', 'nntplib', 'numbers', 'operator',
'optparse', 'os', 'ossaudiodev', 'parser', 'pathlib', 'pdb', 'pickle', 'pickletools', 'pipes',
'pkgutil', 'platform', 'plistlib', 'poplib', 'posix', 'pprint', 'profile', 'pstats', 'pty',
'pwd', 'py_compile', 'pyclbr', 'pydoc', 'queue', 'quopri', 'random', 're', 'readline',
'reprlib', 'resource', 'rlcompleter', 'runpy', 'sched', 'secrets', 'select', 'selectors', 'shelve',
'shlex', 'shutil', 'signal', 'site', 'smtpd', 'smtplib', 'sndhdr', 'socket', 'socketserver',
'spwd', 'sqlite3', 'ssl', 'stat', 'statistics', 'string', 'stringprep', 'struct', 'subprocess',
'sunau', 'symtable', 'sys', 'sysconfig', 'syslog', 'tabnanny', 'tarfile', 'telnetlib', 'tempfile',
'termios', 'test', 'textwrap', 'threading', 'time', 'timeit', 'token', 'tokenize', 'trace',
'traceback', 'tracemalloc', 'tty', 'turtle', 'types', 'typing', 'unicodedata', 'unittest',
'urllib', 'uu', 'uuid', 'venv', 'warnings', 'wave', 'weakref', 'webbrowser', 'xdrlib', 'xml',
'xmlrpc', 'zipapp', 'zipfile', 'zipimport', 'zlib'
}
# Known corrections for PyPI package names
KNOWN_CORRECTIONS = {
'dateutil': 'python-dateutil',
'dotenv': 'python-dotenv',
'docx': 'python-docx',
'tesseract': 'pytesseract',
'magic': 'python-magic',
'multipart': 'python-multipart',
'newspaper': 'newspaper3k',
'srtm': 'elevation',
'yaml': 'pyyaml',
'zoneinfo': 'backports.zoneinfo'
}
# List of generic names to exclude
EXCLUDED_NAMES = {'models', 'data', 'convert', 'example', 'tests'}
def run_command(command: List[str]) -> Tuple[int, str, str]:
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
return process.returncode, stdout.decode(), stderr.decode()
def is_package_installed(package: str) -> bool:
returncode, stdout, _ = run_command(["mamba", "list"])
if returncode == 0:
if re.search(f"^{package}\\s", stdout, re.MULTILINE):
return True
returncode, stdout, _ = run_command(["pip", "list"])
return re.search(f"^{package}\\s", stdout, re.MULTILINE) is not None
def install_package(package: str):
if is_package_installed(package):
print(f"Package '{package}' is already installed.")
return
print(f"Installing package '{package}'.")
returncode, _, _ = run_command(["mamba", "install", "-y", "-c", "conda-forge", package])
if returncode != 0:
returncode, _, _ = run_command(["pip", "install", package])
if returncode != 0:
print(f"Failed to install package '{package}'.")
else:
print(f"Successfully installed package '{package}'.")
def process_python_file(file_path: str) -> Set[str]:
with open(file_path, 'r') as file:
content = file.read()
imports = set()
for line in content.split('\n'):
line = line.strip()
if line.startswith(('import ', 'from ')) and not line.startswith('#'):
if line.startswith('import '):
modules = line.replace('import ', '').split(',')
for mod in modules:
mod = re.sub(r'\s+as\s+\w+', '', mod).split('.')[0].strip()
if mod and not mod.isupper() and mod not in EXCLUDED_NAMES and mod not in BUILTIN_MODULES:
imports.add(KNOWN_CORRECTIONS.get(mod, mod))
elif line.startswith('from '):
mod = line.split(' ')[1].split('.')[0].strip()
if mod and not mod.isupper() and mod not in EXCLUDED_NAMES and mod not in BUILTIN_MODULES:
imports.add(KNOWN_CORRECTIONS.get(mod, mod))
return imports
def process_requirements_file(file_path: str) -> Set[str]:
with open(file_path, 'r') as file:
return {line.strip() for line in file if line.strip() and not line.startswith('#')}
def main():
if len(sys.argv) < 2:
print("Usage: kip <package1> [<package2> ...] or kip <script.py> or kip -r <requirements.txt>")
sys.exit(1)
packages_to_install = set()
i = 1
while i < len(sys.argv):
arg = sys.argv[i]
if arg == '-r':
if i + 1 < len(sys.argv):
requirements_file = sys.argv[i + 1]
if os.path.isfile(requirements_file):
packages_to_install.update(process_requirements_file(requirements_file))
else:
print(f"Requirements file {requirements_file} not found.")
sys.exit(1)
i += 2
else:
print("Error: -r flag requires a file path.")
sys.exit(1)
elif arg.endswith('.py'):
if os.path.isfile(arg):
packages_to_install.update(process_python_file(arg))
else:
print(f"File {arg} not found.")
sys.exit(1)
i += 1
else:
packages_to_install.add(arg)
i += 1
for package in packages_to_install:
install_package(package)
if __name__ == "__main__":
main()