-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackage_manager.py
More file actions
275 lines (240 loc) · 10.4 KB
/
package_manager.py
File metadata and controls
275 lines (240 loc) · 10.4 KB
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import subprocess
import sys
import os
import urllib.request
import json
import shutil
# Configuration
INSTALL_DIR = os.getcwd()
REPO_FILE = os.path.join(INSTALL_DIR, "community_repos.json")
VERSION = "1.5.0"
ARCHIVE_GITHUB_URL = "https://raw.githubusercontent.com/QKing-Official/Lightpack/main/archive"
# Ensure the repository file exists
if not os.path.exists(REPO_FILE):
with open(REPO_FILE, "w") as f:
json.dump({}, f) # Stores repo names linked to URLs
def download_file(url, file_path):
"""Download a file from a URL."""
try:
urllib.request.urlretrieve(url, file_path)
print(f"Downloaded {file_path}")
return True
except Exception as e:
print(f"Error downloading file: {e}")
return False
def load_repos():
"""Load community repositories from JSON."""
with open(REPO_FILE, "r") as f:
return json.load(f)
def save_repos(repos):
"""Save updated repository data."""
with open(REPO_FILE, "w") as f:
json.dump(repos, f, indent=4)
print(f"Repositories saved: {repos}") # Debugging line
def add_repo(url):
"""Add a new community repository and fetch repo.json."""
if "github.com" in url and not url.endswith(".json"):
url = url.rstrip("/") # Remove trailing slash
url = url.replace("github.com", "raw.githubusercontent.com") + "/main/repo.json"
config_path = os.path.join(INSTALL_DIR, "temp_repo.json")
if not download_file(url, config_path):
print("Failed to fetch repository repo.json. Ensure the URL is correct.")
return
try:
with open(config_path, "r") as f:
config = json.load(f)
repo_name = config["name"]
repo_url = config["url"] # Ensure URL is in the JSON
repos = load_repos()
if repo_name in repos:
print(f"Repository '{repo_name}' already exists.")
else:
repos[repo_name] = repo_url
save_repos(repos)
print(f"Added repository: {repo_name} ({repo_url})")
except json.JSONDecodeError:
print("Error: Invalid repo.json format.")
finally:
os.remove(config_path) # Clean up
def remove_repo(repo_name):
"""Remove a repository by name."""
repos = load_repos()
print(f"Loaded repositories: {repos}") # Debugging line
if repo_name in repos:
del repos[repo_name]
save_repos(repos)
print(f"Removed repository: {repo_name}")
else:
print("Repository not found.")
def list_repos():
"""List all community repositories."""
repos = load_repos()
if repos:
print("\nCommunity Repositories:")
for name, url in repos.items():
print(f"- {name}: {url}")
else:
print("No community repositories added.")
def install_package(package_name, repo_name=None):
"""Install a package from a LightPack or community repository."""
repos = load_repos()
if repo_name:
if repo_name not in repos:
print(f"Error: Repository '{repo_name}' not found.")
return
repo_url = repos[repo_name]
print(f"Warning: Installing from '{repo_name}', an unverified repository.")
else:
repo_url = "https://raw.githubusercontent.com/QKing-Official/LightPack/main/packages"
# Clone main file and installer
package_path = os.path.join(INSTALL_DIR, f"{package_name}.py")
url = f"{repo_url}/{package_name}/{package_name}.py"
if not download_file(url, package_path):
return
installer_path = os.path.join(INSTALL_DIR, f"{package_name}_install.py")
url = f"{repo_url}/{package_name}/install.py"
if not download_file(url, installer_path):
return
# Run the installer
try:
print(f"Running installer for {package_name}...")
subprocess.run([sys.executable, f"{package_name}_install.py"], check=True)
print(f"{package_name} installed successfully!")
except subprocess.CalledProcessError as e:
print(f"Error running installer for {package_name}: {e}")
def run_package(package_name):
"""Run an installed package."""
package_path = os.path.join(INSTALL_DIR, f"{package_name}.py")
if os.path.exists(package_path):
print(f"Running {package_name}...")
subprocess.run([sys.executable, package_path])
else:
print(f"Error: {package_name} is not installed.")
def list_packages():
"""List all installed packages."""
print("\nInstalled packages:")
found = False
for file in os.listdir(INSTALL_DIR):
if file.endswith(".py") and not file.endswith("_install.py"):
print(f"- {file[:-3]}") # Remove '.py' extension
found = True
if not found:
print("No packages installed.")
def uninstall_package(package_name):
"""Uninstall a package."""
main_file = os.path.join(INSTALL_DIR, f"{package_name}.py")
install_file = os.path.join(INSTALL_DIR, f"{package_name}_install.py")
if os.path.exists(main_file):
os.remove(main_file)
print(f"Removed {package_name}.py")
if os.path.exists(install_file):
os.remove(install_file)
print(f"Removed {package_name}_install.py")
print(f"{package_name} uninstalled successfully.")
def update_package(package_name):
"""Update a package."""
print(f"Updating {package_name}...")
uninstall_package(package_name)
install_package(package_name)
def clear_console():
"""Clear the terminal screen."""
os.system("cls" if os.name == "nt" else "clear")
def display_help():
"""Display available commands."""
print("\nAvailable commands:")
print(" install <package> - Install a package")
print(" install <package>:<repo> - Install from a specific community repository")
print(" run <package> - Run an installed package")
print(" list - List installed packages")
print(" uninstall <package> - Remove an installed package")
print(" update <package> - Update a package")
print(" update-all - Update all installed packages")
print(" update-lightpack - Update LightPack to the latest version")
print(" addrepo <url> - Add a community repository")
print(" removerepo <repo> - Remove a community repository")
print(" listrepos - List all added repositories")
print(" clear - Clear the terminal")
print(" help - Show this help message")
print(" exit - Exit the package manager")
print(" downgrade <version> - Downgrade LightPack to a previous version")
def downgrade_lightpack(version):
"""Downgrade to an older version from the GitHub archive."""
file_url = f"{ARCHIVE_GITHUB_URL}/{version}/package_manager.py"
package_manager_path = os.path.join(INSTALL_DIR, "package_manager.py")
if download_file(file_url, package_manager_path):
print(f"Successfully downgraded to version {version}!")
else:
print(f"Version {version} not found in the archive.")
def list_version():
"""List the current version of LightPack."""
print(f"Current LightPack version: {VERSION}")
def update_all_packages():
"""Update all installed packages except package_manager.py."""
print("Updating all installed packages...")
try:
for file in os.listdir(INSTALL_DIR):
# Skip updating the package_manager.py itself
if file.endswith(".py") and not file.endswith("_install.py") and file != "package_manager.py":
package_name = file[:-3]
update_package(package_name)
except Exception as e:
print(f"Error updating all packages: {e}")
def update_lightpack():
"""Update LightPack to the latest version."""
print("Upgrading LightPack...")
try:
latest_version_url = "https://raw.githubusercontent.com/QKing-Official/LightPack/main/package_manager.py" # Replace with actual URL to the latest version
package_manager_path = os.path.join(INSTALL_DIR, "package_manager.py")
if download_file(latest_version_url, package_manager_path):
print("LightPack upgraded successfully!")
print("Restart shell/LightPack to use upgraded version!")
else:
print("Failed to update LightPack.")
except Exception as e:
print(f"Error updating LightPack: {e}")
def interactive_shell():
"""Start an interactive shell."""
while True:
current_dir = os.getcwd() # Get the current directory
command = input(f"lightpackshell@{current_dir}> ").strip()
if command == "exit":
break
elif command == "clear":
clear_console()
elif command == "list_version":
clear_console()
elif command == "list":
list_packages()
elif command == "help":
display_help()
elif command.startswith("install "):
parts = command.split(" ", 1)[1]
if ":" in parts:
package_name, repo_name = parts.split(":")
install_package(package_name, repo_name)
else:
install_package(parts)
elif command.startswith("run "):
run_package(command.split(" ", 1)[1])
elif command.startswith("uninstall "):
uninstall_package(command.split(" ", 1)[1])
elif command.startswith("update "):
update_package(command.split(" ", 1)[1])
elif command == "update-all":
update_all_packages()
elif command == "upgrade":
update_lightpack()
elif command.startswith("downgrade "):
version = command.split(" ", 1)[1]
downgrade_lightpack(version)
elif command == "listrepos":
list_repos()
elif command.startswith("addrepo "):
add_repo(command.split(" ", 1)[1])
elif command.startswith("removerepo "):
remove_repo(command.split(" ", 1)[1])
else:
print("Unknown command. Type 'help' for a list of commands.")
if __name__ == "__main__":
print("Welcome to LightPack! Type 'help' for commands.")
interactive_shell()