-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitpm.py
More file actions
1726 lines (1527 loc) · 77.4 KB
/
gitpm.py
File metadata and controls
1726 lines (1527 loc) · 77.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
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Git Package Manager - Install and manage applications from git repositories
"""
import os
import sys
import json
import argparse
import subprocess
import re
from pathlib import Path
from urllib.parse import urlparse
from typing import List, Dict, Optional, Tuple
class GitPackageManager:
def __init__(self, system: bool = False):
self.system = system
if system:
self.apps_dir = Path("/opt/apps")
self.config_dir = Path("/etc/gitpm")
self.installed_file = Path("/etc/gitpm/installed.json")
else:
self.apps_dir = Path.home() / ".local/share/apps"
self.config_dir = Path.home() / ".config/gitpm"
self.installed_file = self.config_dir / "installed.json"
# Ensure directories exist
self.apps_dir.mkdir(parents=True, exist_ok=True)
self.config_dir.mkdir(parents=True, exist_ok=True)
# Load installed apps
self.installed = self.load_installed()
# Detect distribution
self.distro = self.detect_distro()
def load_config(self) -> List[Dict[str, str]]:
"""Load git repositories from config file(s)
Scans for all repos*.conf files in:
- System config: /etc/xdg/gitpm/repos*.conf
- User config: ~/.config/gitpm/repos*.conf (or system config if --system flag)
Returns list of dicts with keys: url, branch, name
Format: url,branch,name (branch and name are optional)
"""
import glob
config_files = []
# Load system configs from /etc/xdg/gitpm (always check this)
system_xdg_dir = Path("/etc/xdg/gitpm")
if system_xdg_dir.exists():
system_pattern = str(system_xdg_dir / "repos*.conf")
system_configs = sorted(glob.glob(system_pattern))
config_files.extend(system_configs)
# Also check for default repos.conf
default_system = system_xdg_dir / "repos.conf"
if default_system.exists() and str(default_system) not in config_files:
config_files.append(str(default_system))
# Load user configs (unless system mode)
if not self.system:
user_config_dir = Path.home() / ".config/gitpm"
if user_config_dir.exists():
user_pattern = str(user_config_dir / "repos*.conf")
user_configs = sorted(glob.glob(user_pattern))
config_files.extend(user_configs)
# Also check for default repos.conf
default_user = user_config_dir / "repos.conf"
if default_user.exists() and str(default_user) not in config_files:
config_files.append(str(default_user))
else:
# In system mode, also check /etc/gitpm
system_dir = Path("/etc/gitpm")
if system_dir.exists():
system_pattern = str(system_dir / "repos*.conf")
system_configs = sorted(glob.glob(system_pattern))
config_files.extend(system_configs)
default_system = system_dir / "repos.conf"
if default_system.exists() and str(default_system) not in config_files:
config_files.append(str(default_system))
if not config_files:
print(f"Error: No config files found")
print(f"Please create a config file in one of these locations:")
print(f" - {Path.home() / '.config/gitpm/repos.conf'} (user)")
print(f" - /etc/xdg/gitpm/repos.conf (system)")
print(f"Format: url or url,branch,name")
sys.exit(1)
repos = []
for config_file in config_files:
try:
config_path = Path(config_file)
# Determine if it's a system or user config
is_system = str(config_path).startswith('/etc')
source_label = f"[system]{config_path.name}" if is_system else config_path.name
with open(config_file, 'r') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if line and not line.startswith('#'):
# Parse format: url,branch,name
parts = [p.strip() for p in line.split(',')]
if not parts[0]: # Skip empty URLs
continue
repo_entry = {
'url': parts[0],
'branch': parts[1] if len(parts) > 1 and parts[1] else None,
'name': parts[2] if len(parts) > 2 and parts[2] else None,
'source_file': source_label # Track which file it came from
}
repos.append(repo_entry)
except IOError as e:
print(f"Warning: Could not read config file {config_file}: {e}", file=sys.stderr)
continue
return repos
def parse_repo_url(self, url: str) -> Tuple[str, str, str]:
"""Parse git URL to extract user/org and repo name
Returns: (full_url, user/org, repo_name)
"""
# Handle various git URL formats
url = url.strip()
# Remove .git suffix if present
if url.endswith('.git'):
url = url[:-4]
# Parse URL
if url.startswith('http://') or url.startswith('https://'):
parsed = urlparse(url)
path_parts = parsed.path.strip('/').split('/')
if len(path_parts) >= 2:
user = path_parts[0]
repo = path_parts[1]
full_url = f"{parsed.scheme}://{parsed.netloc}/{user}/{repo}.git"
return (full_url, user, repo)
elif url.startswith('git@'):
# SSH format: git@github.com:user/repo.git
match = re.match(r'git@([^:]+):([^/]+)/([^/]+)', url)
if match:
host, user, repo = match.groups()
full_url = f"git@{host}:{user}/{repo}.git"
return (full_url, user, repo)
elif '/' in url and not url.startswith('http'):
# Short format: user/repo
parts = url.split('/')
if len(parts) == 2:
user, repo = parts
full_url = f"https://github.com/{user}/{repo}.git"
return (full_url, user, repo)
# Fallback: assume it's a valid git URL
# Try to extract repo name from URL
repo_name = url.split('/')[-1].replace('.git', '')
return (url, 'unknown', repo_name)
def find_repos_by_name(self, name: str) -> List[Dict[str, str]]:
"""Find all repos with matching name from config
Matches by custom name if provided, otherwise by repo name
"""
repos = self.load_config()
matches = []
for repo_entry in repos:
repo_url = repo_entry['url']
_, user, repo_name = self.parse_repo_url(repo_url)
# Use custom name if provided, otherwise use repo name
display_name = repo_entry['name'] if repo_entry['name'] else repo_name
if display_name.lower() == name.lower():
matches.append({
'url': repo_url,
'user': user,
'name': display_name,
'repo_name': repo_name,
'branch': repo_entry['branch']
})
return matches
def prompt_selection(self, options: List[Dict[str, str]], prompt_text: str) -> Optional[Dict[str, str]]:
"""Prompt user to select from a list of options"""
if len(options) == 0:
return None
if len(options) == 1:
return options[0]
print(f"\n{prompt_text}")
print("-" * 80)
for i, option in enumerate(options, 1):
branch_info = f" [branch: {option.get('branch', 'default')}]" if option.get('branch') else ""
print(f"{i}. {option['user']}/{option['name']}{branch_info}")
print(f" {option['url']}")
print("-" * 80)
while True:
try:
choice = input(f"Select (1-{len(options)}): ").strip()
idx = int(choice) - 1
if 0 <= idx < len(options):
return options[idx]
else:
print(f"Please enter a number between 1 and {len(options)}")
except (ValueError, KeyboardInterrupt):
print("\nCancelled.")
return None
def check_scripts(self, repo_path: Path) -> Dict[str, Optional[Path]]:
"""Check for setup, removal, and update scripts in repo
Checks for user/system-specific scripts first, then falls back to generic ones
"""
scripts = {
'setup': None,
'remove': None,
'uninstall': None,
'update': None,
'check': None
}
# Determine script prefix based on install type
prefix = 'system' if self.system else 'user'
# Script names: check specific ones first, then generic
script_names = {
'setup': [
# User/system specific
f'setup-{prefix}.sh', f'install-{prefix}.sh',
f'setup-{prefix}.py', f'install-{prefix}.py',
# Generic
'setup.sh', 'install.sh', 'setup.py', 'install.py'
],
'remove': [
# User/system specific
f'remove-{prefix}.sh', f'uninstall-{prefix}.sh',
f'remove-{prefix}.py', f'uninstall-{prefix}.py',
# Generic
'remove.sh', 'uninstall.sh', 'remove.py', 'uninstall.py'
],
'update': [
# User/system specific
f'update-{prefix}.sh', f'upgrade-{prefix}.sh',
f'update-{prefix}.py', f'upgrade-{prefix}.py',
# Generic
'update.sh', 'upgrade.sh', 'update.py', 'upgrade.py'
],
'check': [
# User/system specific
f'check-{prefix}.sh', f'check-updates-{prefix}.sh',
f'check-{prefix}.py', f'check-updates-{prefix}.py',
# Generic
'check.sh', 'check-updates.sh', 'check.py', 'check-updates.py'
]
}
for script_type, names in script_names.items():
for name in names:
script_path = repo_path / name
if script_path.exists() and script_path.is_file():
# Make script executable if it's a shell script
if script_path.suffix in ['.sh', '']:
try:
os.chmod(script_path, 0o755)
except Exception:
pass # Ignore permission errors
# Check if executable or if it's a Python script
if script_path.suffix == '.py' or os.access(script_path, os.X_OK):
scripts[script_type] = script_path
break
return scripts
def run_script(self, script_path: Path, repo_path: Path, return_exit_code: bool = False):
"""Run a setup or removal script
If return_exit_code is True, returns the exit code (int) instead of bool
Returns: bool (success/failure) or int (exit code) if return_exit_code=True
"""
try:
# Ensure script is executable (for shell scripts)
if script_path.suffix in ['.sh', '']:
try:
os.chmod(script_path, 0o755)
except Exception:
pass # Ignore permission errors, will use bash to run it
if script_path.suffix == '.py':
cmd = [sys.executable, str(script_path)]
else:
cmd = ['bash', str(script_path)]
result = subprocess.run(
cmd,
cwd=repo_path,
check=False, # Don't raise on non-zero exit
capture_output=True,
text=True
)
if result.stdout:
print(result.stdout)
if result.stderr and result.returncode != 0:
print(result.stderr, file=sys.stderr)
if return_exit_code:
return result.returncode
# For regular scripts, only 0 is success
return result.returncode == 0
except Exception as e:
print(f"Error running script {script_path}: {e}", file=sys.stderr)
if return_exit_code:
return 255 # Error code
return False
def load_installed(self) -> Dict[str, Dict]:
"""Load installed apps registry"""
if not self.installed_file.exists():
return {}
try:
with open(self.installed_file, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
return {}
def save_installed(self):
"""Save installed apps registry"""
with open(self.installed_file, 'w') as f:
json.dump(self.installed, f, indent=2)
def detect_distro(self) -> str:
"""Detect base Linux distribution (Arch, Fedora, Debian, etc.)
Checks ID_LIKE first to get the base distro, then falls back to ID
This ensures Arch-based distros (Garuda, Catchy, etc.) are detected as "Arch"
"""
try:
# Check /etc/os-release first (most reliable)
if Path('/etc/os-release').exists():
distro_id = None
distro_id_like = None
with open('/etc/os-release', 'r') as f:
for line in f:
if line.startswith('ID_LIKE='):
# ID_LIKE contains the base distribution(s)
# e.g., "arch" for Garuda, "debian" for Linux Mint
distro_id_like = line.split('=', 1)[1].strip().strip('"').strip("'")
# ID_LIKE can be space-separated, take the first one
if ' ' in distro_id_like:
distro_id_like = distro_id_like.split()[0]
elif line.startswith('ID='):
distro_id = line.split('=', 1)[1].strip().strip('"').strip("'")
# Prefer ID_LIKE (base distro) over ID (specific OS)
# This ensures Garuda/Catchy -> Arch, Linux Mint -> Debian, etc.
distro_to_check = distro_id_like if distro_id_like else distro_id
if distro_to_check:
# Normalize common distribution names
distro_map = {
'arch': 'Arch',
'archlinux': 'Arch',
'debian': 'Debian',
'ubuntu': 'Ubuntu',
'fedora': 'Fedora',
'rhel': 'RHEL',
'centos': 'CentOS',
'opensuse': 'openSUSE',
'sles': 'SLES',
'suse': 'openSUSE'
}
return distro_map.get(distro_to_check.lower(), distro_to_check.capitalize())
# Fallback: check for distro-specific files
if Path('/etc/arch-release').exists():
return 'Arch'
elif Path('/etc/debian_version').exists():
return 'Debian'
elif Path('/etc/fedora-release').exists():
return 'Fedora'
elif Path('/etc/redhat-release').exists():
return 'RHEL'
elif Path('/etc/SuSE-release').exists():
return 'openSUSE'
return 'Unknown'
except Exception:
return 'Unknown'
def load_gitpm_json(self, repo_path: Path) -> Tuple[Optional[Dict], Optional[str]]:
"""Load gitpm.json from repository
Returns: (json_data, error_message)
If JSON is invalid, returns (None, error_message)
"""
marker_files = ['gitpm.json', '.gitpm.json']
for marker_file in marker_files:
json_path = repo_path / marker_file
if json_path.exists() and json_path.is_file():
try:
with open(json_path, 'r') as f:
return json.load(f), None
except json.JSONDecodeError as e:
error_msg = f"Invalid JSON in {marker_file}: {e}"
return None, error_msg
except Exception as e:
error_msg = f"Error reading {marker_file}: {e}"
return None, error_msg
return None, None
def check_system_package(self, package: str) -> bool:
"""Check if a system package/command is installed using -v flag"""
try:
# Try running the command with -v flag
result = subprocess.run(
[package, '-v'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=5
)
# If it returns 0, the command exists
# If it returns non-zero but has output, it might still exist (some commands use -v differently)
if result.returncode == 0:
return True
# Some commands output version to stderr
if result.stderr and (b'version' in result.stderr.lower() or b'Version' in result.stderr):
return True
# Check if command exists in PATH
which_result = subprocess.run(
['which', package],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=2
)
return which_result.returncode == 0
except (subprocess.TimeoutExpired, FileNotFoundError):
# Check if command exists in PATH
try:
which_result = subprocess.run(
['which', package],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=2
)
return which_result.returncode == 0
except Exception:
return False
except Exception:
return False
def check_package_alternatives(self, alternatives: List[str]) -> Tuple[bool, Optional[str]]:
"""Check if any of the alternative packages are installed
Returns: (is_installed, installed_package_name)
"""
for package in alternatives:
if self.check_system_package(package):
return True, package
return False, None
def check_system_dependencies(self, dependencies: Dict) -> Tuple[bool, List[str], str]:
"""Check system package dependencies
Returns: (all_satisfied, missing_packages, install_method)
"""
missing = []
install_method = ''
# Get install method (can be global or per-distro)
if 'method' in dependencies:
install_method = dependencies['method']
elif f'{self.distro}_method' in dependencies:
install_method = dependencies[f'{self.distro}_method']
# Check if using new format with check_commands
check_commands = dependencies.get('check_commands', [])
distro_packages = dependencies.get(self.distro, {})
if check_commands and isinstance(check_commands, list) and isinstance(distro_packages, dict):
# New format: check_commands is a list of commands to check
# Can be strings or arrays of alternatives (e.g., ["docker"] or [["docker", "podman"]])
# distro_packages maps command names to package names for this distro
for command_entry in check_commands:
if isinstance(command_entry, list):
# Array of alternative commands (e.g., ["docker", "podman"])
# Check if any of these commands exist
is_installed, installed_cmd = self.check_package_alternatives(command_entry)
if not is_installed:
# None of the alternative commands exist, need to install
# Use first command to look up package in distro section
primary_command = command_entry[0]
if primary_command in distro_packages:
pkg_entry = distro_packages[primary_command]
if isinstance(pkg_entry, list):
missing.append(pkg_entry[0])
elif isinstance(pkg_entry, str):
missing.append(pkg_entry)
else:
missing.append(str(pkg_entry))
else:
# No package mapping, use first command as package name
missing.append(primary_command)
elif isinstance(command_entry, str):
# Single command to check
command_found = self.check_system_package(command_entry)
if not command_found:
# Command not found, look up package in distro section
if command_entry in distro_packages:
pkg_entry = distro_packages[command_entry]
if isinstance(pkg_entry, list):
missing.append(pkg_entry[0])
elif isinstance(pkg_entry, str):
missing.append(pkg_entry)
else:
missing.append(str(pkg_entry))
else:
# Command in check list but no package mapping for this distro
missing.append(command_entry)
elif check_commands and isinstance(check_commands, dict):
# Legacy format: check_commands as dict (backward compatibility)
for command, package_names in check_commands.items():
# Check if command exists
if not self.check_system_package(command):
# Command not found, need to install one of the packages
if isinstance(package_names, list):
# Multiple packages can provide this command
# Check which package name to use for this distro
distro_pkg = None
for pkg_name in package_names:
if pkg_name in distro_packages:
distro_pkg = distro_packages[pkg_name]
break
if distro_pkg:
missing.append(distro_pkg)
else:
# Fallback: use first package name
missing.append(package_names[0])
else:
# Single package provides this command
if package_names in distro_packages:
missing.append(distro_packages[package_names])
else:
missing.append(package_names)
elif self.distro in dependencies:
# Old format: list of packages
distro_deps = dependencies[self.distro]
if isinstance(distro_deps, list):
for dep_entry in distro_deps:
if isinstance(dep_entry, str):
# Simple package name
if not self.check_system_package(dep_entry):
missing.append(dep_entry)
elif isinstance(dep_entry, list):
# Alternative packages (e.g., [docker, podman])
is_installed, installed_pkg = self.check_package_alternatives(dep_entry)
if not is_installed:
missing.append(f"({' or '.join(dep_entry)})")
elif isinstance(distro_deps, dict):
# Dict format but no check_commands - check each package directly
for pkg_name, pkg_value in distro_deps.items():
if isinstance(pkg_value, str):
if not self.check_system_package(pkg_value):
missing.append(pkg_value)
# Check if we can install packages
has_sudo = False
if missing:
# Check if user has sudo access
sudo_check = subprocess.run(
['sudo', '-n', 'true'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=2
)
has_sudo = sudo_check.returncode == 0 or os.geteuid() == 0
return len(missing) == 0, missing, install_method
def check_gitpm_dependencies(self, gitpm_deps: List) -> Tuple[bool, List[str], List[Dict], List[str]]:
"""Check gitpm package dependencies
Supports alternatives: can be a list of strings (alternatives) or a single string
Returns: (all_satisfied, missing_packages, dependency_info, system_only_deps)
"""
missing = []
dep_info = []
system_only_deps = []
for dep_entry in gitpm_deps:
if isinstance(dep_entry, list):
# Array of alternatives - check if any are installed
found_alternative = False
for dep in dep_entry:
# Parse dependency (can be in repos.conf format: url,branch,name)
parts = [p.strip() for p in dep.split(',')]
if len(parts) > 2 and parts[2]:
dep_name = parts[2]
else:
# Extract name from URL
_, _, repo_name = self.parse_repo_url(parts[0])
dep_name = repo_name
# Check if this alternative is installed
if dep_name in self.installed:
found_alternative = True
# Check if dependency requires system but we're doing user install
if not self.system:
dep_path = Path(self.installed[dep_name]['path'])
dep_json, _ = self.load_gitpm_json(dep_path)
if dep_json and dep_json.get('system_only', False):
system_only_deps.append(dep_name)
break
if not found_alternative:
# None of the alternatives are installed
# Use first alternative as the one to install
primary_dep = dep_entry[0]
parts = [p.strip() for p in primary_dep.split(',')]
if len(parts) > 2 and parts[2]:
dep_name = parts[2]
dep_url = parts[0]
dep_branch = parts[1] if len(parts) > 1 and parts[1] else None
else:
_, _, repo_name = self.parse_repo_url(parts[0])
dep_name = repo_name
dep_url = parts[0]
dep_branch = parts[1] if len(parts) > 1 and parts[1] else None
missing.append(dep_name)
dep_info.append({
'name': dep_name,
'url': dep_url,
'branch': dep_branch,
'alternatives': dep_entry
})
elif isinstance(dep_entry, str):
# Single dependency
# Parse dependency (can be in repos.conf format: url,branch,name)
parts = [p.strip() for p in dep_entry.split(',')]
if len(parts) > 2 and parts[2]:
dep_name = parts[2]
dep_url = parts[0]
dep_branch = parts[1] if len(parts) > 1 and parts[1] else None
else:
# Extract name from URL
_, _, repo_name = self.parse_repo_url(parts[0])
dep_name = repo_name
dep_url = parts[0]
dep_branch = parts[1] if len(parts) > 1 and parts[1] else None
# Check if dependency is installed
if dep_name not in self.installed:
missing.append(dep_name)
dep_info.append({
'name': dep_name,
'url': dep_url,
'branch': dep_branch
})
# Check if dependency requires system install
# We need to check the dependency's gitpm.json to see if it's system_only
# For now, we'll check this when we try to install it
else:
# Dependency is installed, check if it requires system but we're doing user install
if not self.system:
# Check the installed dependency's gitpm.json
dep_path = Path(self.installed[dep_name]['path'])
dep_json, _ = self.load_gitpm_json(dep_path)
if dep_json and dep_json.get('system_only', False):
system_only_deps.append(dep_name)
return len(missing) == 0, missing, dep_info, system_only_deps
def check_dependencies(self, repo_path: Path) -> Tuple[bool, List[str], List[str], bool, List[Dict], Optional[str]]:
"""Check all dependencies for a repository
Returns: (all_satisfied, missing_system, missing_gitpm, can_install_system, gitpm_dep_info, json_error)
"""
gitpm_json, json_error = self.load_gitpm_json(repo_path)
if json_error:
# Invalid JSON - return error
return False, [], [], False, [], json_error
if not gitpm_json:
# No dependencies defined
return True, [], [], False, [], None
missing_system = []
missing_gitpm = []
can_install_system = False
gitpm_dep_info = []
# Check if dependencies section exists
if 'dependencies' not in gitpm_json:
# No dependencies section
return True, [], [], False, [], None
# Check system dependencies
install_method = ''
if 'system' in gitpm_json['dependencies']:
all_satisfied, missing, method = self.check_system_dependencies(
gitpm_json['dependencies']['system']
)
missing_system = missing
install_method = method
# Check if we can install system packages
if missing_system and self.system:
can_install_system = True # System installs can always install deps
elif missing_system and not self.system:
# Check if user has sudo
sudo_check = subprocess.run(
['sudo', '-n', 'true'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=2
)
can_install_system = sudo_check.returncode == 0 or os.geteuid() == 0
# Check gitpm dependencies (only if 'gitpm' key exists)
# Check both at dependencies level and inside system (for backwards compatibility)
system_only_deps = []
gitpm_deps = None
if 'gitpm' in gitpm_json['dependencies']:
gitpm_deps = gitpm_json['dependencies']['gitpm']
elif 'system' in gitpm_json['dependencies'] and 'gitpm' in gitpm_json['dependencies']['system']:
# Handle case where gitpm is incorrectly nested inside system
gitpm_deps = gitpm_json['dependencies']['system']['gitpm']
print("Warning: 'gitpm' dependencies should be at 'dependencies.gitpm', not 'dependencies.system.gitpm'", file=sys.stderr)
if gitpm_deps:
all_satisfied_gitpm, missing, dep_info, system_only = self.check_gitpm_dependencies(gitpm_deps)
missing_gitpm = missing
gitpm_dep_info = dep_info
system_only_deps = system_only
# Check if current package requires system install
if gitpm_json.get('system_only', False) and not self.system:
return False, [], [], False, [], "This package requires system-wide installation (use --system flag)"
# Check if any installed dependencies require system install but we're doing user install
if system_only_deps and not self.system:
deps_list = ', '.join(system_only_deps)
return False, [], [], False, [], f"Installed dependencies require system install: {deps_list}. This package must be installed with --system flag."
all_satisfied = len(missing_system) == 0 and len(missing_gitpm) == 0
return all_satisfied, missing_system, missing_gitpm, can_install_system, gitpm_dep_info, None
def install_system_packages(self, missing: List[str], dependencies: Dict, install_method: str) -> bool:
"""Install missing system packages"""
try:
# missing already contains the package names to install
# Remove duplicates and clean up
packages_to_install = list(set([pkg.strip('()') for pkg in missing if pkg.strip()]))
if not packages_to_install:
return True # Nothing to install
# Parse install method (e.g., "sudo pacman -S --noconfirm")
install_cmd = install_method.split()
# Append package names to the install command
install_cmd.extend(packages_to_install)
print(f"Running: {' '.join(install_cmd)}")
result = subprocess.run(
install_cmd,
check=True,
timeout=300 # 5 minute timeout
)
return result.returncode == 0
except subprocess.CalledProcessError as e:
print(f"Error installing packages: {e}", file=sys.stderr)
return False
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
return False
def verify_repo(self, repo_url: str, branch: Optional[str] = None) -> Tuple[bool, str]:
"""Verify that a repository exists and is accessible
If branch is specified, also verify that branch exists
Returns: (is_valid, error_message)
"""
try:
# Use git ls-remote to check if repository exists and is accessible
result = subprocess.run(
['git', 'ls-remote', '--heads', '--tags', repo_url],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=10
)
if result.returncode != 0:
error_msg = result.stderr.strip() if result.stderr else "Unknown error"
if "not found" in error_msg.lower() or "does not exist" in error_msg.lower():
return False, f"Repository not found or not accessible: {error_msg}"
elif "permission denied" in error_msg.lower() or "authentication" in error_msg.lower():
return False, f"Permission denied or authentication required: {error_msg}"
else:
return False, f"Error accessing repository: {error_msg}"
# If branch is specified, verify it exists
if branch:
# Check if branch exists in the remote
# ls-remote output format: <commit_hash>\trefs/heads/<branch_name>
remote_refs = result.stdout
# Look for exact branch match (handles branches with slashes)
branch_refs = []
for line in remote_refs.split('\n'):
if not line.strip():
continue
# Extract the ref part (after the tab)
parts = line.split('\t')
if len(parts) >= 2:
ref = parts[1]
# Check for exact branch match
if ref == f'refs/heads/{branch}':
branch_refs.append(line)
if not branch_refs:
# Also check for tags in case branch name matches a tag
tag_refs = []
for line in remote_refs.split('\n'):
if not line.strip():
continue
parts = line.split('\t')
if len(parts) >= 2:
ref = parts[1]
if ref == f'refs/tags/{branch}':
tag_refs.append(line)
if not tag_refs:
return False, f"Branch '{branch}' not found in repository"
else:
return False, f"'{branch}' exists as a tag, not a branch. Please use a branch name."
return True, ""
except subprocess.TimeoutExpired:
return False, "Timeout while checking repository (network may be slow or repository unreachable)"
except FileNotFoundError:
return False, "Git is not installed or not in PATH"
except Exception as e:
return False, f"Unexpected error while verifying repository: {str(e)}"
def check_repo_compatibility(self, repo_url: str, branch: Optional[str] = None) -> Tuple[bool, str]:
"""Check if repository is compatible with gitpm
Looks for a marker file (.gitpm, gitpm.json, or .gitpm.json) in the repository root
Uses a shallow clone to a temp directory to check for the marker file
Returns: (is_compatible, error_message)
"""
import tempfile
import shutil
# Marker files that indicate gitpm compatibility
marker_files = ['.gitpm', 'gitpm.json', '.gitpm.json']
temp_dir = None
try:
# Create a temporary directory for shallow clone
temp_dir = tempfile.mkdtemp(prefix='gitpm_check_')
temp_repo_path = Path(temp_dir) / "repo"
# Do a shallow clone (depth=1) to check files
clone_cmd = ['git', 'clone', '--depth', '1', '--no-checkout', repo_url, str(temp_repo_path)]
if branch:
clone_cmd.extend(['--branch', branch])
clone_result = subprocess.run(
clone_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=30
)
if clone_result.returncode != 0:
# If shallow clone fails, try without branch specification
if branch:
clone_cmd = ['git', 'clone', '--depth', '1', '--no-checkout', repo_url, str(temp_repo_path)]
clone_result = subprocess.run(
clone_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=30
)
if clone_result.returncode != 0:
return False, f"Could not check compatibility: {clone_result.stderr[:100]}"
# Checkout just the files we need to inspect
checkout_result = subprocess.run(
['git', 'checkout', 'HEAD', '--'],
cwd=temp_repo_path,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=10
)
# Check for marker file in root directory
if temp_repo_path.exists():
for marker in marker_files:
marker_path = temp_repo_path / marker
if marker_path.exists() and marker_path.is_file():
return True, ""
# No marker file found
marker_list = ', '.join(marker_files)
return False, f"Repository is not marked as gitpm-compatible (missing marker file: {marker_list})"
except subprocess.TimeoutExpired:
return False, "Timeout while checking repository compatibility"
except Exception as e:
return False, f"Error checking compatibility: {str(e)}"
finally:
# Clean up temporary directory
if temp_dir and Path(temp_dir).exists():
try:
shutil.rmtree(temp_dir)
except Exception:
pass # Ignore cleanup errors
def install_from_url(self, repo_url: str, install_name: str, branch: Optional[str] = None,
skip_compatibility_check: bool = False, skip_dependency_check: bool = False,
skip_reinstall_prompt: bool = False) -> bool:
"""Install a package directly from a URL
This is used for installing gitpm dependencies that may not be in the config file
"""
_, user, repo_name = self.parse_repo_url(repo_url)
repo_path = self.apps_dir / install_name
# Check if already installed
if install_name in self.installed:
if skip_reinstall_prompt:
# For dependencies, silently skip if already installed
print(f"'{install_name}' is already installed, skipping...")
return True
print(f"'{install_name}' is already installed at {self.installed[install_name]['path']}")
response = input("Reinstall? (y/N): ").strip().lower()
if response != 'y':
return False
# Remove existing installation
self.remove(install_name, skip_uninstall=True)
# Verify repository before cloning
print(f"Verifying repository {repo_url}...")
is_valid, error_msg = self.verify_repo(repo_url, branch)
if not is_valid:
print(f"Error: {error_msg}", file=sys.stderr)
return False
branch_info = f" (branch: {branch})" if branch else ""
print(f"Repository verified{branch_info}")
# Check repository compatibility
if not skip_compatibility_check:
print(f"Checking repository compatibility...")
is_compatible, compat_msg = self.check_repo_compatibility(repo_url, branch)
if not is_compatible:
print(f"Error: {compat_msg}", file=sys.stderr)
print(f"\nTo make a repository compatible with gitpm, add one of these marker files to the root:", file=sys.stderr)
print(f" - .gitpm", file=sys.stderr)
print(f" - gitpm.json", file=sys.stderr)
print(f" - .gitpm.json", file=sys.stderr)
print(f"\nUse --force flag to skip compatibility check and install anyway.", file=sys.stderr)
return False
print("Repository is compatible with gitpm")
# Clone repository
print(f"Cloning {repo_url} to {repo_path}...")
cloned = False
try:
# Clone the repository
clone_cmd = ['git', 'clone', repo_url, str(repo_path)]
subprocess.run(
clone_cmd,
check=True,
capture_output=True
)
cloned = True
# Checkout specific branch if provided
if branch:
print(f"Checking out branch '{branch}'...")
try:
# Fetch all branches first to get remote branch info
subprocess.run(
['git', 'fetch', 'origin'],
cwd=repo_path,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)