-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasks.py
225 lines (196 loc) · 6.87 KB
/
tasks.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
from pathlib import Path
from invoke import task # pylint: disable=E0401
GIT_ROOT = Path(__file__).resolve().parent
ENV_FILE = Path(GIT_ROOT / ".env")
ONAIR_SH = Path.home() / "onair"
OFFAIR_SH = Path.home() / "offair"
BASH_PROFILE = Path.home() / ".bash_profile"
START_ONAIR_BLOCK = "### START ON AIR ###"
END_ONAIR_BLOCK = "### END ON AIR ###"
PRINT_LN = "-------------------"
# @task
# def say_hello(context):
# context.run("echo 'Welcome to on-air!'")
@task
def app_install(context):
"""
Installs application scripts and shortcuts.
"""
print(PRINT_LN)
print("💾 Installing ON AIR...")
app_scripts_deploy(context)
app_bash_aliases(context)
print("✅ ON AIR installed successfully!")
print(PRINT_LN)
print("🌽 Don't forget to add your cronjob!")
print(PRINT_LN)
@task
def app_uninstall(context):
"""
Removes application scripts and shortcuts.
"""
while True:
confirm = input("🎙️ 🚨 Are you sure you wish to uninstall ON AIR? (y/n) ")
first_letter_lowercase = confirm[0].lower()
if confirm == "" or first_letter_lowercase not in ["y", "n"]:
print("Please answer with yes or no!")
else:
break
print(f"\n{PRINT_LN}")
if first_letter_lowercase == "y":
print("🗑️ Uninstalling ON AIR...")
# remove scripts
ONAIR_SH.unlink(missing_ok=True)
OFFAIR_SH.unlink(missing_ok=True)
# remove bash aliases
context.run(
f"sed -i.uninstall.onair.bak '/{START_ONAIR_BLOCK}/,/{END_ONAIR_BLOCK}/d' { BASH_PROFILE }"
)
# clean up python etc.
print("🔥 ON AIR uninstalled successfully!")
print(PRINT_LN)
print("🌽 Don't forget to remove your cronjob!")
if first_letter_lowercase == "n":
print("❌ Uninstall cancelled.")
print(PRINT_LN)
def app_ensure_dot_env(context):
"""
Ensures that .env exists.
"""
print(PRINT_LN)
print("👀 Checking '.env'...")
if ENV_FILE.exists():
print("⏭️ '.env' already exists, skipping.")
else:
print("✨ Creating '.env'...")
context.run(f"cp {GIT_ROOT / '.env.example'} {ENV_FILE}")
print("✅ '.env' created!")
print(PRINT_LN)
def app_bash_aliases(context):
"""
Writes onair/offair bash aliases
"""
print(PRINT_LN)
print(f"👀 Checking '{BASH_PROFILE}' for project aliases...")
with open(BASH_PROFILE, "r", encoding="utf-8") as profile:
content = profile.read()
if START_ONAIR_BLOCK in content:
print("⏭️ Project aliases already exist, skipping.")
else:
print(f"🏷️ Writing project aliases to '{BASH_PROFILE}'...")
context.run(f"cp {BASH_PROFILE} {BASH_PROFILE}.install.onair.bak")
context.run(
f"""cat <<EOT >> { BASH_PROFILE }
{START_ONAIR_BLOCK}
alias onair="$HOME/onair"
alias offair="$HOME/offair"
{END_ONAIR_BLOCK}
EOT"""
)
print(f"✅ Project aliases written to '{BASH_PROFILE}' successfully!")
print(PRINT_LN)
def app_scripts_deploy(context):
"""
Deploys onair/offair scripts at the user's home dir.
"""
print(PRINT_LN)
print(f"👀 Checking '{ Path.home() }' for convenence scripts...")
if not ONAIR_SH.exists() and not OFFAIR_SH.exists():
print("📜 Writing convenence scripts...")
with open(ONAIR_SH, "w", encoding="utf-8") as on_file:
onair_content = [
"#!/bin/bash\n\n",
f"cd {GIT_ROOT} || exit;\n\n",
"./run-on-air.sh\n",
]
on_file.writelines(onair_content)
context.run(f"chmod +x {ONAIR_SH}")
with open(OFFAIR_SH, "w", encoding="utf-8") as off_file:
offair_content = [
"#!/bin/bash\n\n",
f"cd {GIT_ROOT} || exit;\n\n",
"./run-off-air.sh\n",
]
off_file.writelines(offair_content)
context.run(f"chmod +x {OFFAIR_SH}")
print("✅ Conveneince scripts written successfully!")
else:
print("⏭️ Conveneince scripts already installed, skipping.")
@task
def project_setup(context):
"""
Perform a 'poetry install' to install python packages
"""
context.run("poetry install")
app_ensure_dot_env(context)
@task
def project_update(context):
"""
Perform a 'poetry update' to update python packages
"""
context.run("poetry update")
@task
def discover_process_names(context, query=None):
"""
List running processes on the host; query optional.
"""
with context.cd(GIT_ROOT):
if query:
context.run(
f"poetry run python host/discover_processes.py | grep -i {query}"
)
else:
context.run("poetry run python host/discover_processes.py")
@task
def manage_cron(
context,
action: str = None,
interval_min: int = 0,
start_hour: int = 0,
end_hour: int = 0,
line_num: int = 0,
):
# pylint: disable=[R0913,R0912,R1705]
"""
Manages the crontab; requires an 'action'
"""
with context.cd(GIT_ROOT / "scripts"):
if action == "add":
# TODO: check if onair has already been written to crontab.
# ensure all options are set
if not all([interval_min, start_hour, end_hour]):
print(
"❌ Error: Must provide 'interval-min', 'start-hour', and 'end-hour' with '--action add'"
)
return
else:
# run checks on hour values
if start_hour > end_hour:
print(
f"❌ Error: 'start-hour' ({start_hour}) cannot be greater than 'end-hour' ({end_hour}).\n Ensure you are using 24H time."
)
return
elif start_hour == end_hour:
cron_hours = end_hour
else:
cron_hours = f"{start_hour}-{end_hour}"
# run checks on minute values
if interval_min == 0:
cron_min = "*"
else:
cron_min = f"*/{interval_min}"
# run the script
context.run(
f"./cron-mgmt.sh add '{cron_min} {cron_hours} * * 1-5 {GIT_ROOT}/run-app-status-light.sh > /dev/null 2>&1'"
)
print("🎙️ ON AIR entry written to crontab")
elif action == "list":
context.run("./cron-mgmt.sh list")
elif action == "remove":
if not line_num:
print("❌ Error: Must provide 'line-num' with '--action remove'")
else:
context.run(f"./cron-mgmt.sh remove {line_num}")
print(f"✅ line {line_num} removed from crontab.")
else:
print("❌ Error: Must provide an 'action'")