-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsetup_moonraker.py
More file actions
229 lines (180 loc) · 7.83 KB
/
Copy pathsetup_moonraker.py
File metadata and controls
229 lines (180 loc) · 7.83 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
#!/usr/bin/env python3
"""Add/update the KlipperFleet update_manager section in moonraker.conf.
Usage:
python3 setup_moonraker.py <moonraker.conf path> <KlipperFleet repo path>
python3 setup_moonraker.py --add-persistent-file <section> <filename> <moonraker.conf path>
python3 setup_moonraker.py --remove-persistent-file <section> <filename> <moonraker.conf path>
Idempotent: creates the section if missing, migrates deprecated options if
the section already exists (e.g. install_script -> system_dependencies).
"""
import os
import re
import sys
# The three declarative dependency lines Moonraker needs to handle updates.
# - virtualenv + requirements: pip deps installed into venv on every update
# - system_dependencies: apt packages installed on every update
MANAGED_DEPS = """\
virtualenv: {kf_path}/venv
requirements: backend/requirements.txt
system_dependencies: install_scripts/system-dependencies.json"""
def _extract_section(content: str, section_name: str):
"""Return (start, end) char offsets of a named section.
Works for any [update_manager <name>] section header.
"""
pattern = rf"^\[update_manager {re.escape(section_name)}\]"
m = re.search(pattern, content, re.MULTILINE)
if not m:
return None, None
start = m.start()
# Section ends at the next [section] header or EOF
next_section = re.search(r"^\[", content[m.end():], re.MULTILINE)
end = m.end() + next_section.start() if next_section else len(content)
return start, end
def _extract_klipperfleet_section(content: str):
"""Return (start, end) char offsets of the [update_manager klipperfleet] section."""
return _extract_section(content, "klipperfleet")
def migrate_moonraker_conf(conf_path: str, kf_path: str) -> bool:
"""Migrate an existing moonraker.conf in-place.
Returns True if the file was changed, False otherwise.
This is also used by main.py's startup self-heal.
"""
if not os.path.isfile(conf_path):
return False
with open(conf_path, "r", encoding="utf-8") as f:
content = f.read()
start, end = _extract_klipperfleet_section(content)
if start is None:
return False # No klipperfleet section
section = content[start:end]
deps = MANAGED_DEPS.format(kf_path=kf_path)
changed = False
# Remove deprecated install_script line
if "install_script:" in section:
section = re.sub(r"\n?install_script:.*", "", section)
changed = True
# Add missing dependency lines
for line in deps.splitlines():
key = line.split(":")[0].strip()
if key + ":" not in section:
# Insert before is_system_service or at end of section
m_sys = re.search(r"^is_system_service:.*$", section, re.MULTILINE)
if m_sys:
section = section[:m_sys.start()] + line + "\n" + section[m_sys.start():]
else:
section = section.rstrip() + "\n" + line + "\n"
changed = True
if changed:
content = content[:start] + section + content[end:]
with open(conf_path, "w", encoding="utf-8") as f:
f.write(content)
return True
return False
def add_persistent_file(conf_path: str, section_name: str, filename: str) -> bool:
"""Add a filename to persistent_files in an [update_manager <section>] block.
Idempotent: does nothing if already present.
Creates the persistent_files option if it doesn't exist.
"""
if not os.path.isfile(conf_path):
print(f"KlipperFleet: WARNING: {conf_path} not found.", file=sys.stderr)
return False
with open(conf_path, "r", encoding="utf-8") as f:
content = f.read()
start, end = _extract_section(content, section_name)
if start is None:
print(f"KlipperFleet: WARNING: [update_manager {section_name}] not found in {conf_path}.",
file=sys.stderr)
return False
section = content[start:end]
# Check if filename is already listed
if re.search(rf"^\s+{re.escape(filename)}\s*$", section, re.MULTILINE):
print(f"KlipperFleet: {filename} already in {section_name} persistent_files.")
return False
if "persistent_files:" in section:
# Append to existing persistent_files list
section = re.sub(
r"(persistent_files:\s*\n(?:\s+\S+\n)*)",
rf"\g<1> {filename}\n",
section
)
else:
# Add persistent_files before the next option or at end of section
section = section.rstrip() + f"\npersistent_files:\n {filename}\n"
content = content[:start] + section + content[end:]
with open(conf_path, "w", encoding="utf-8") as f:
f.write(content)
print(f"KlipperFleet: Added {filename} to {section_name} persistent_files.")
return True
def remove_persistent_file(conf_path: str, section_name: str, filename: str) -> bool:
"""Remove a filename from persistent_files in an [update_manager <section>] block."""
if not os.path.isfile(conf_path):
return False
with open(conf_path, "r", encoding="utf-8") as f:
content = f.read()
start, end = _extract_section(content, section_name)
if start is None:
return False
section = content[start:end]
# Remove the specific file entry
new_section = re.sub(rf"\n\s+{re.escape(filename)}\s*(?=\n)", "", section)
if new_section == section:
return False # Not found
# If persistent_files is now empty, remove the key entirely
new_section = re.sub(r"\npersistent_files:\s*\n(?=\S|\Z)", "\n", new_section)
content = content[:start] + new_section + content[end:]
with open(conf_path, "w", encoding="utf-8") as f:
f.write(content)
print(f"KlipperFleet: Removed {filename} from {section_name} persistent_files.")
return True
def main():
# Handle --add-persistent-file / --remove-persistent-file mode
if len(sys.argv) >= 2 and sys.argv[1] in ("--add-persistent-file", "--remove-persistent-file"):
if len(sys.argv) < 5:
print(f"Usage: setup_moonraker.py {sys.argv[1]} <section> <filename> <moonraker.conf>",
file=sys.stderr)
sys.exit(1)
section_name = sys.argv[2]
filename = sys.argv[3]
conf_path = sys.argv[4]
if sys.argv[1] == "--add-persistent-file":
add_persistent_file(conf_path, section_name, filename)
else:
remove_persistent_file(conf_path, section_name, filename)
sys.exit(0)
if len(sys.argv) < 3:
print("Usage: setup_moonraker.py <moonraker_conf_path> <kf_repo_path>", file=sys.stderr)
sys.exit(1)
conf_path = sys.argv[1]
kf_path = sys.argv[2]
SECTION_MARKER = "[update_manager klipperfleet]"
deps = MANAGED_DEPS.format(kf_path=kf_path)
SECTION_BLOCK = f"""
[update_manager klipperfleet]
type: git_repo
path: {kf_path}
origin: https://github.com/JohnBaumb/KlipperFleet.git
primary_branch: main
managed_services: klipperfleet
{deps}
is_system_service: False
"""
if not os.path.isfile(conf_path):
print(
f"KlipperFleet: WARNING: moonraker.conf not found at {conf_path}; "
"skipping update_manager integration.",
file=sys.stderr,
)
sys.exit(0)
with open(conf_path, "r", encoding="utf-8") as f:
content = f.read()
if SECTION_MARKER in content:
if migrate_moonraker_conf(conf_path, kf_path):
print("KlipperFleet: Migrated moonraker.conf (added virtualenv/requirements/system_dependencies).")
else:
print("KlipperFleet: update_manager section already up to date in moonraker.conf.")
sys.exit(0)
# Append the section, ensuring a leading newline for clean separation.
with open(conf_path, "a", encoding="utf-8") as f:
f.write(SECTION_BLOCK)
print("KlipperFleet: Added update_manager section to moonraker.conf.")
if __name__ == "__main__":
main()