-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacuni.py
209 lines (178 loc) · 7.25 KB
/
pacuni.py
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
#!/usr/bin/env python3
"""
A configuration python script to unify installation (depends on 'dotbot').
How to use:
1. Add the configuration in file, e.g. `~/.pacuni_conf.yaml`:
Ubuntu 24.04:
```yaml
- apt-get:
- jq
- npm:
- pnpm
- pipx:
- pytest
- cargo:
```
Arch Linux:
```yaml
- pacman
- jq
- npm:
- pnpm
- pipx:
- pytest
- cargo:
```
2. run: `${DOTBOT_BIN} -p {CURRENT_SCRIPT} -c {CONFIG}`, e.g.:
```bash
~/.dotfiles/dotbot/bin/dotbot -p pacuni.py -c ~/.pacuni_conf.yaml
```
Note: you can place all the configurations in one file, and run specific config(s) with '--only' or '--except' flag, e.g.:
```bash
~/.dotfiles/dotbot/bin/dotbot -p pacuni.py -c ~/.pacuni_conf.yaml --except apt-get
~/.dotfiles/dotbot/bin/dotbot -p pacuni.py -c ~/.pacuni_conf.yaml --except pacman apt-get
```
```bash
~/.dotfiles/dotbot/bin/dotbot -p pacuni.py -c ~/.pacuni_conf.yaml --only apt-get
~/.dotfiles/dotbot/bin/dotbot -p pacuni.py -c ~/.pacuni_conf.yaml --only npm pipx
```
"""
__author__ = "Shangjin Tang"
__email__ = "[email protected]"
__copyright__ = "Copyright 2024 Shangjin Tang"
__license__ = "GPL"
__version__ = "0.1.0"
import subprocess
from enum import Enum
from typing import List
import dotbot
class PkgStatus(Enum):
ALREADY_INSTALLED = "Already Installed"
FAILED_TO_INSTALL = "Failed to Install"
SUCCEEDED_TO_INSTALL = "Succeeded to Install"
class PacUni(dotbot.Plugin):
_installers_config = {
"apt-get": {
"depends": {
"cmd": "[[ -f '/etc/os-release' ]] && [[ $(cat /etc/os-release) =~ 'ID=ubuntu' ]]",
"msg_fail": "'apt-get' not available, not Ubuntu distro",
},
"check_installed": "dpkg -l | grep '^ii ' | cut -d ' ' -f 3 | cut -d ':' -f 1 | grep -qw",
"try_install": "sudo apt-get install -y",
},
"pacman": {
"depends": {
"cmd": "[[ -f '/etc/os-release' ]] && [[ $(cat /etc/os-release) =~ 'ID=arch' ]]",
"msg_fail": "'pacman' not available, not ArchLinux distro",
},
"check_installed": "pacman -Qi | grep -qw",
"try_install": "sudo pacman --noconfirm -S",
},
"cargo": {
"depends": {
"cmd": "command -v cargo &> /dev/null",
"msg_fail": "'cargo' not available. To install it, see: https://rustup.rs/",
},
"check_installed": "cargo install --list | grep -qw",
"try_install": "cargo install",
},
"npm": {
"depends": {
"cmd": "command -v npm &> /dev/null",
"msg_fail": "'npm' not available. To install it, see: https://nodejs.org/en/download/package-manager",
},
"check_installed": "npm list -g | grep -qw",
"try_install": "npm install -g",
},
"pipx": {
"depends": {
"cmd": "command -v pipx &> /dev/null",
"msg_fail": "'pipx' not available",
},
"check_installed": "pipx list --short | grep -qwi",
"try_install": "pipx install",
},
"pip": {
"depends": {
"cmd": "command -v python &> /dev/null",
"msg_fail": "'pip' not available as 'python' not found",
},
"check_installed": "python -m pip list | tail -n +3 | grep -qwi",
"try_install": "python -m pip install",
},
}
def __init__(self, context: str) -> None:
super(PacUni, self).__init__(self)
self._context = context
def can_handle(self, directive: str) -> bool:
return directive in self._installers_config.keys()
def handle(self, directive: str, data: List[str]) -> bool:
if not self.can_handle(directive):
raise RuntimeError(f"PacUni cannot handle directive {directive}")
if not data:
return True
non_installed_pkgs = [
pkg for pkg in data if not self._is_installed(directive, pkg)
]
if non_installed_pkgs:
self._log.info(f"{directive}: packages to install: {non_installed_pkgs}")
return self._process_packages(directive, data)
def _check_depends(self, directive: str) -> bool:
if "depends" in self._installers_config[directive]:
depends = self._installers_config[directive]["depends"]
if depends and "cmd" in depends:
result = subprocess.call(
f"bash -c '{depends["cmd"]}' > /dev/null", shell=True
)
if result != 0:
if "msg_fail" in depends:
self._log.error(f"Error: {depends['msg_fail']}")
else:
self._log.error(f"Error: failed to process '{directive}'")
return False
return True
def _is_installed(self, directive: str, pkg: str) -> bool:
check_installed_cmd = self._installers_config[directive]["check_installed"]
return subprocess.call(f"{check_installed_cmd} {pkg}", shell=True) == 0
def _install_package(self, directive: str, pkg: str) -> None:
try_install_cmd = self._installers_config[directive]["try_install"]
cmd_to_run = f"{try_install_cmd} {pkg}".strip()
self._log.lowinfo(f" {cmd_to_run}")
result = subprocess.call(f"{cmd_to_run} > /dev/null", shell=True)
if result != 0:
self._log.error(f" {cmd_to_run}")
else:
self._log.info(f" {cmd_to_run}")
def _process_packages(self, directive: str, packages: List[str]) -> bool:
if not self._check_depends(directive):
return False
results = {
PkgStatus.ALREADY_INSTALLED: [],
PkgStatus.SUCCEEDED_TO_INSTALL: [],
PkgStatus.FAILED_TO_INSTALL: [],
}
successful = [PkgStatus.ALREADY_INSTALLED, PkgStatus.SUCCEEDED_TO_INSTALL]
for pkg in packages:
if self._is_installed(directive, pkg):
results[PkgStatus.ALREADY_INSTALLED].append(pkg)
else:
self._install_package(directive, pkg)
if not self._is_installed(directive, pkg):
results[PkgStatus.FAILED_TO_INSTALL].append(pkg)
else:
results[PkgStatus.SUCCEEDED_TO_INSTALL].append(pkg)
results_stripped = {k: v for k, v in results.items() if v}
if all(result in successful for result in results_stripped.keys()):
self._log.info(f"{directive}: all packages installed successfully")
success = True
else:
success = False
for status, pkgs in results_stripped.items():
log_func = self._log.lowinfo
if status == PkgStatus.SUCCEEDED_TO_INSTALL:
log_func = self._log.info
elif status == PkgStatus.FAILED_TO_INSTALL:
log_func = self._log.error
log_func(f"{directive}:\t{status.value}:\t{pkgs}")
self._log.lowinfo("-" * 70)
return success