-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
648 lines (559 loc) · 24.5 KB
/
main.cpp
File metadata and controls
648 lines (559 loc) · 24.5 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
/**
* pyp - C++ Virtual Environment Manager
* A lightweight, high-performance alternative to Python-based venv managers
* Built with only C++ standard libraries - no external dependencies
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <filesystem>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <chrono>
#include <thread>
#include <iomanip>
namespace fs = std::filesystem;
// Configuration file path
const std::string CONFIG_FILENAME = ".pyp_config.json";
// ANSI color codes for beautiful output
const std::string COLOR_RESET = "\033[0m";
const std::string COLOR_BOLD = "\033[1m";
const std::string COLOR_GREEN = "\033[32m";
const std::string COLOR_BLUE = "\033[34m";
const std::string COLOR_YELLOW = "\033[33m";
const std::string COLOR_RED = "\033[31m";
const std::string COLOR_CYAN = "\033[36m";
class PypManager {
private:
fs::path configPath;
std::map<std::string, std::map<std::string, std::string>> environments;
// Detect current shell
std::string detectShell() {
const char* shell = std::getenv("SHELL");
if (shell) {
std::string shellPath(shell);
if (shellPath.find("zsh") != std::string::npos) return "zsh";
if (shellPath.find("bash") != std::string::npos) return "bash";
if (shellPath.find("fish") != std::string::npos) return "fish";
}
// Check for PowerShell on Windows
const char* psModulePath = std::getenv("PSModulePath");
if (psModulePath) return "powershell";
return "bash"; // Default to bash
}
// Detect OS
std::string detectOS() {
#ifdef _WIN32
return "windows";
#elif __APPLE__
return "macos";
#elif __linux__
return "linux";
#else
return "unknown";
#endif
}
// Read JSON config file
void loadConfig() {
environments.clear();
if (!fs::exists(configPath)) {
return;
}
std::ifstream file(configPath);
if (!file.is_open()) {
std::cerr << COLOR_RED << "Warning: Could not open config file" << COLOR_RESET << std::endl;
return;
}
std::stringstream buffer;
buffer << file.rdbuf();
std::string content = buffer.str();
// Simple JSON parsing
size_t pos = 0;
while ((pos = content.find("\"", pos)) != std::string::npos) {
size_t end = content.find("\"", pos + 1);
if (end == std::string::npos) break;
std::string key = content.substr(pos + 1, end - pos - 1);
pos = end + 1;
if (content.find(":", pos) == std::string::npos) continue;
pos = content.find(":", pos) + 1;
// Skip whitespace
while (pos < content.size() && (content[pos] == ' ' || content[pos] == '\n' || content[pos] == '\t')) pos++;
if (content.substr(pos, 2) == "{}") {
environments[key] = {};
pos += 2;
}
}
}
// Save JSON config file
void saveConfig() {
std::ofstream file(configPath);
if (!file.is_open()) {
std::cerr << COLOR_RED << "Error: Could not save config file" << COLOR_RESET << std::endl;
return;
}
file << "{\n";
int count = 0;
for (const auto& env : environments) {
file << " \"" << env.first << "\": {";
int innerCount = 0;
for (const auto& prop : env.second) {
if (innerCount > 0) file << ", ";
file << "\"" << prop.first << "\": \"" << prop.second << "\"";
innerCount++;
}
file << "}";
if (++count < environments.size()) file << ",";
file << "\n";
}
file << "}\n";
file.close();
}
// Execute system command
bool executeCommand(const std::string& command, bool captureOutput = false) {
if (captureOutput) {
FILE* pipe = popen(command.c_str(), "r");
if (!pipe) {
return false;
}
pclose(pipe);
return true;
}
return std::system(command.c_str()) == 0;
}
// Execute command and capture output
std::string executeCommandOutput(const std::string& command) {
char buffer[1024];
std::string result;
FILE* pipe = popen(command.c_str(), "r");
if (!pipe) {
return "";
}
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
result += buffer;
}
pclose(pipe);
// Remove trailing newline
if (!result.empty() && result.back() == '\n') {
result.pop_back();
}
return result;
}
// Get Python executable path
std::string getPythonExecutable(const std::string& version) {
if (!version.empty()) {
// Try specific version
std::string pyExec = "python" + version;
std::string result = executeCommandOutput("which " + pyExec);
if (!result.empty()) {
return result;
}
}
// Try python3 first, then python
std::string result = executeCommandOutput("which python3");
if (!result.empty()) {
return result;
}
result = executeCommandOutput("which python");
if (!result.empty()) {
return result;
}
return ""; // Not found
}
// Get current directory
fs::path getCurrentDirectory() {
return fs::current_path();
}
public:
PypManager() {
const char* home = std::getenv("HOME");
if (home) {
configPath = fs::path(home) / CONFIG_FILENAME;
} else {
configPath = fs::path("/tmp") / CONFIG_FILENAME;
}
loadConfig();
}
// Display help information
void showHelp() {
std::cout << COLOR_BOLD << COLOR_CYAN << "\n pyp - Python Virtual Environment Manager" << COLOR_RESET << std::endl;
std::cout << COLOR_CYAN << " ==========================================\n" << COLOR_RESET << std::endl;
std::cout << COLOR_GREEN << " Usage: pyp [options] [arguments]\n" << COLOR_RESET << std::endl;
std::cout << COLOR_YELLOW << " Commands:" << COLOR_RESET << std::endl;
std::cout << " -b, --build <name> Create a new virtual environment" << std::endl;
std::cout << " -a, --activate <name> Activate a virtual environment" << std::endl;
std::cout << " -d, --deactivate Deactivate current environment" << std::endl;
std::cout << " -l, --list List all environments" << std::endl;
std::cout << " -i, --info <name> Show environment information" << std::endl;
std::cout << " --set-default <name> Set default environment" << std::endl;
std::cout << " --remove <name> Remove an environment" << std::endl;
std::cout << " --help, -h Show this help message" << std::endl;
std::cout << " --version Show version information\n" << COLOR_RESET << std::endl;
std::cout << COLOR_YELLOW << " Options:" << COLOR_RESET << std::endl;
std::cout << " --python VERSION Python version (e.g., 3.11)" << std::endl;
std::cout << " --system-site-packages Include system site-packages" << std::endl;
std::cout << " --upgrade Upgrade pip and setuptools\n" << COLOR_RESET << std::endl;
}
// Show version
void showVersion() {
std::cout << COLOR_BOLD << COLOR_GREEN << "pyp v2.0.0" << COLOR_RESET << std::endl;
std::cout << "C++ Virtual Environment Manager" << std::endl;
std::cout << "Built with only standard libraries" << std::endl;
}
// Build/Create virtual environment
void buildEnvironment(const std::string& name, const std::string& pythonVersion = "",
bool systemSitePackages = false, bool upgrade = false) {
std::cout << COLOR_BOLD << "\n Building virtual environment: " << COLOR_RESET << COLOR_GREEN << name << COLOR_RESET << std::endl;
// Check if environment already exists in current directory
fs::path envPath = getCurrentDirectory() / name;
if (fs::exists(envPath)) {
std::cerr << COLOR_RED << "Error: Environment '" << name << "' already exists in current directory" << COLOR_RESET << std::endl;
return;
}
// Get Python executable
std::string pythonExec = getPythonExecutable(pythonVersion);
if (pythonExec.empty()) {
std::cerr << COLOR_RED << "Error: Python executable not found" << COLOR_RESET << std::endl;
std::cerr << COLOR_YELLOW << "Please ensure Python is installed and in your PATH" << COLOR_RESET << std::endl;
return;
}
std::cout << COLOR_BLUE << " Using Python: " << COLOR_RESET << pythonExec << std::endl;
// Build command
std::string command = "\"" + pythonExec + "\" -m venv";
if (systemSitePackages) {
command += " --system-site-packages";
}
command += " \"" + envPath.string() + "\"";
std::cout << COLOR_BLUE << " Creating venv at: " << COLOR_RESET << envPath << std::endl;
// Execute venv creation
int result = std::system(command.c_str());
if (result != 0) {
std::cerr << COLOR_RED << "Error: Failed to create virtual environment" << COLOR_RESET << std::endl;
return;
}
std::cout << COLOR_GREEN << " ✓ Virtual environment created successfully!" << COLOR_RESET << std::endl;
// Upgrade pip and setuptools if requested
if (upgrade) {
std::cout << COLOR_BLUE << " Upgrading pip and setuptools..." << COLOR_RESET << std::endl;
std::string upgradeCmd = "\"" + envPath.string() + "/bin/pip\" install --upgrade pip setuptools wheel";
int upgradeResult = std::system(upgradeCmd.c_str());
if (upgradeResult == 0) {
std::cout << COLOR_GREEN << " ✓ Upgraded successfully!" << COLOR_RESET << std::endl;
}
}
// Store in config
std::map<std::string, std::string> envInfo;
envInfo["path"] = envPath.string();
envInfo["python"] = pythonExec;
envInfo["created"] = getCurrentTimestamp();
environments[name] = envInfo;
saveConfig();
}
// Activate virtual environment
void activateEnvironment(const std::string& name) {
fs::path envPath;
if (name.empty()) {
// Try to find default environment
auto it = environments.find("default");
if (it != environments.end()) {
envPath = it->second["path"];
} else {
std::cerr << COLOR_RED << "Error: No environment specified and no default set" << COLOR_RESET << std::endl;
return;
}
} else {
// Check in current directory first
envPath = getCurrentDirectory() / name;
if (!fs::exists(envPath)) {
// Check in config
auto it = environments.find(name);
if (it != environments.end()) {
envPath = it->second["path"];
} else {
std::cerr << COLOR_RED << "Error: Environment '" << name << "' not found" << COLOR_RESET << std::endl;
return;
}
}
}
std::string shell = detectShell();
std::string activateCommand;
std::cout << COLOR_BOLD << "\n Activating: " << COLOR_RESET << COLOR_GREEN << name << COLOR_RESET << std::endl;
std::cout << COLOR_BLUE << " Shell: " << COLOR_RESET << shell << std::endl;
if (shell == "zsh" || shell == "bash") {
activateCommand = "source \"" + envPath.string() + "/bin/activate\"";
std::cout << COLOR_YELLOW << "\n Run the following command to activate:" << COLOR_RESET << std::endl;
std::cout << " " << COLOR_GREEN << activateCommand << COLOR_RESET << std::endl;
} else if (shell == "fish") {
activateCommand = "source \"" + envPath.string() + "/bin/activate.fish\"";
std::cout << COLOR_YELLOW << "\n Run the following command to activate:" << COLOR_RESET << std::endl;
std::cout << " " << COLOR_GREEN << activateCommand << COLOR_RESET << std::endl;
} else if (shell == "powershell") {
activateCommand = "\"" + envPath.string() + "/Scripts/Activate.ps1\"";
std::cout << COLOR_YELLOW << "\n Run the following command to activate:" << COLOR_RESET << std::endl;
std::cout << " " << COLOR_GREEN << activateCommand << COLOR_RESET << std::endl;
} else {
// Windows CMD
activateCommand = "\"" + envPath.string() + "/Scripts/activate.bat\"";
std::cout << COLOR_YELLOW << "\n Run the following command to activate:" << COLOR_RESET << std::endl;
std::cout << " " << COLOR_GREEN << activateCommand << COLOR_RESET << std::endl;
}
}
// Deactivate current environment
void deactivateEnvironment() {
std::cout << COLOR_BOLD << COLOR_GREEN << "\n Deactivating virtual environment..." << COLOR_RESET << std::endl;
std::cout << COLOR_YELLOW << "\n Run the following command:" << COLOR_RESET << std::endl;
std::cout << " " << COLOR_GREEN << "deactivate" << COLOR_RESET << std::endl;
}
// List all environments
void listEnvironments() {
std::cout << COLOR_BOLD << COLOR_CYAN << "\n Virtual Environments" << COLOR_RESET << std::endl;
std::cout << COLOR_CYAN << " ===================\n" << COLOR_RESET << std::endl;
if (environments.empty()) {
std::cout << COLOR_YELLOW << " No environments found. Create one with: pyp -b <name>" << COLOR_RESET << std::endl;
return;
}
// Also check current directory for venvs
std::vector<std::string> localEnvs;
try {
for (const auto& entry : fs::directory_iterator(getCurrentDirectory())) {
if (entry.is_directory()) {
fs::path activateScript = entry.path() / "bin" / "activate";
if (fs::exists(activateScript)) {
localEnvs.push_back(entry.path().filename().string());
}
}
}
} catch (...) {
// Ignore directory access errors
}
std::cout << std::left << std::setw(25) << "Name" << std::setw(40) << "Path" << std::setw(15) << "Python" << std::endl;
std::cout << std::string(80, '-') << std::endl;
for (const auto& env : environments) {
std::string path = env.second.count("path") ? env.second.at("path") : "Unknown";
std::string python = env.second.count("python") ? env.second.at("python") : "Unknown";
std::cout << std::left << std::setw(25) << env.first
<< std::setw(40) << path
<< std::setw(15) << python << std::endl;
}
if (!localEnvs.empty()) {
std::cout << COLOR_YELLOW << "\n Local environments (current directory):" << COLOR_RESET << std::endl;
for (const auto& env : localEnvs) {
std::cout << " - " << env << std::endl;
}
}
std::cout << std::endl;
}
// Show environment information
void showEnvironmentInfo(const std::string& name) {
fs::path envPath = getCurrentDirectory() / name;
auto it = environments.find(name);
if (it == environments.end()) {
// Check if it exists locally
if (!fs::exists(envPath)) {
std::cerr << COLOR_RED << "Error: Environment '" << name << "' not found" << COLOR_RESET << std::endl;
return;
}
}
std::cout << COLOR_BOLD << COLOR_CYAN << "\n Environment: " << COLOR_RESET << COLOR_GREEN << name << COLOR_RESET << std::endl;
std::cout << COLOR_CYAN << " =============\n" << COLOR_RESET << std::endl;
if (it != environments.end()) {
std::cout << " " << COLOR_YELLOW << "Path:" << COLOR_RESET << " " << it->second.at("path") << std::endl;
std::cout << " " << COLOR_YELLOW << "Python:" << COLOR_RESET << " " << it->second.at("python") << std::endl;
if (it->second.count("created")) {
std::cout << " " << COLOR_YELLOW << "Created:" << COLOR_RESET << " " << it->second.at("created") << std::endl;
}
} else {
std::cout << " " << COLOR_YELLOW << "Path:" << COLOR_RESET << " " << envPath << std::endl;
}
// Check if venv structure exists
fs::path activateScript = envPath / "bin" / "activate";
if (fs::exists(activateScript)) {
std::cout << COLOR_GREEN << " ✓ Valid virtual environment" << COLOR_RESET << std::endl;
} else {
std::cout << COLOR_RED << " ✗ Invalid virtual environment structure" << COLOR_RESET << std::endl;
}
std::cout << std::endl;
}
// Set default environment
void setDefaultEnvironment(const std::string& name) {
auto it = environments.find(name);
if (it == environments.end()) {
// Check locally
fs::path envPath = getCurrentDirectory() / name;
if (!fs::exists(envPath)) {
std::cerr << COLOR_RED << "Error: Environment '" << name << "' not found" << COLOR_RESET << std::endl;
return;
}
}
environments["default"] = environments[name];
saveConfig();
std::cout << COLOR_GREEN << "✓ Default environment set to: " << COLOR_RESET << name << std::endl;
}
// Remove environment
void removeEnvironment(const std::string& name, bool force = false) {
fs::path envPath;
// First check in current directory
fs::path localPath = getCurrentDirectory() / name;
if (fs::exists(localPath)) {
envPath = localPath;
} else {
// Check in config
auto it = environments.find(name);
if (it == environments.end()) {
std::cerr << COLOR_RED << "Error: Environment '" << name << "' not found" << COLOR_RESET << std::endl;
return;
}
envPath = it->second["path"];
}
if (!force) {
std::cout << COLOR_YELLOW << "Are you sure you want to remove '" << name << "'? [y/N] " << COLOR_RESET;
std::string response;
std::getline(std::cin, response);
if (response != "y" && response != "Y") {
std::cout << "Cancelled." << std::endl;
return;
}
}
try {
fs::remove_all(envPath);
std::cout << COLOR_GREEN << "✓ Removed environment: " << COLOR_RESET << name << std::endl;
// Remove from config if tracked
auto it = environments.find(name);
if (it != environments.end()) {
environments.erase(it);
saveConfig();
}
// Remove from default if it was default
auto defaultIt = environments.find("default");
if (defaultIt != environments.end() &&
defaultIt->second.count("path") &&
defaultIt->second["path"] == envPath.string()) {
environments.erase(defaultIt);
saveConfig();
}
} catch (const fs::filesystem_error& e) {
std::cerr << COLOR_RED << "Error removing environment: " << COLOR_RESET << e.what() << std::endl;
}
}
// Get current timestamp
std::string getCurrentTimestamp() {
auto now = std::chrono::system_clock::now();
auto time = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss << std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S");
return ss.str();
}
};
// Parse command line arguments
struct Args {
std::string command;
std::string envName;
std::string pythonVersion;
bool systemSitePackages = false;
bool upgrade = false;
bool force = false;
};
Args parseArgs(int argc, char* argv[]) {
Args args;
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg == "--help" || arg == "-h") {
args.command = "help";
} else if (arg == "--version") {
args.command = "version";
} else if (arg == "--build" || arg == "-b") {
args.command = "build";
if (i + 1 < argc) {
args.envName = argv[++i];
}
} else if (arg == "--activate" || arg == "-a") {
args.command = "activate";
if (i + 1 < argc) {
args.envName = argv[++i];
}
} else if (arg == "--deactivate" || arg == "-d") {
args.command = "deactivate";
} else if (arg == "--list" || arg == "-l") {
args.command = "list";
} else if (arg == "--info" || arg == "-i") {
args.command = "info";
if (i + 1 < argc) {
args.envName = argv[++i];
}
} else if (arg == "--set-default") {
args.command = "set-default";
if (i + 1 < argc) {
args.envName = argv[++i];
}
} else if (arg == "--remove") {
args.command = "remove";
if (i + 1 < argc) {
args.envName = argv[++i];
}
} else if (arg == "--python") {
if (i + 1 < argc) {
args.pythonVersion = argv[++i];
}
} else if (arg == "--system-site-packages") {
args.systemSitePackages = true;
} else if (arg == "--upgrade") {
args.upgrade = true;
} else if (arg == "--force" || arg == "-f") {
args.force = true;
}
}
return args;
}
int main(int argc, char* argv[]) {
PypManager manager;
Args args = parseArgs(argc, argv);
if (argc == 1 || args.command == "help") {
manager.showHelp();
return 0;
}
if (args.command == "version") {
manager.showVersion();
return 0;
}
if (args.command == "build") {
if (args.envName.empty()) {
std::cerr << COLOR_RED << "Error: Environment name required for --build" << COLOR_RESET << std::endl;
std::cerr << "Usage: pyp --build <environment_name>" << std::endl;
return 1;
}
manager.buildEnvironment(args.envName, args.pythonVersion, args.systemSitePackages, args.upgrade);
} else if (args.command == "activate") {
manager.activateEnvironment(args.envName);
} else if (args.command == "deactivate") {
manager.deactivateEnvironment();
} else if (args.command == "list") {
manager.listEnvironments();
} else if (args.command == "info") {
if (args.envName.empty()) {
std::cerr << COLOR_RED << "Error: Environment name required for --info" << COLOR_RESET << std::endl;
std::cerr << "Usage: pyp --info <environment_name>" << std::endl;
return 1;
}
manager.showEnvironmentInfo(args.envName);
} else if (args.command == "set-default") {
if (args.envName.empty()) {
std::cerr << COLOR_RED << "Error: Environment name required for --set-default" << COLOR_RESET << std::endl;
return 1;
}
manager.setDefaultEnvironment(args.envName);
} else if (args.command == "remove") {
if (args.envName.empty()) {
std::cerr << COLOR_RED << "Error: Environment name required for --remove" << COLOR_RESET << std::endl;
return 1;
}
manager.removeEnvironment(args.envName, args.force);
} else {
std::cerr << COLOR_RED << "Unknown command: " << args.command << COLOR_RESET << std::endl;
std::cout << "Run 'pyp --help' for usage information" << std::endl;
return 1;
}
return 0;
}