Compare commits

..
91 Commits
Author SHA1 Message Date
dw-0 a78a6c76f5 test(extensions): add unit tests for base extension 2026-07-11 17:49:51 +02:00
dw-0 b6a08ce4e5 test(instance_manager): add unit tests for instance manager 2026-07-11 17:49:51 +02:00
dw-0 a3f9ee1faf test(settings): add unit tests for KiauhSettings 2026-07-11 17:49:51 +02:00
dw-0 477d737489 test(services): add unit tests for backup and message services 2026-07-11 17:49:51 +02:00
dw-0 9b93450d98 feat(cli): add headless command-line interface
Add core.cli with argparse-based install/remove/update commands for Klipper,

Moonraker, Mainsail/Fluidd and client configs.

Wire main.py to dispatch to the CLI and fall back to the TUI when no args

are given. Pass CLI arguments through kiauh.sh and skip the update dialog

for non-interactive runs.
2026-07-11 17:49:51 +02:00
dw-0 adf3e292fb feat(moonraker): support headless install/remove/update
Add interactive parameter to MoonrakerSetupService.install/remove/update and

headless tests for the service.

Add unit tests for moonraker utility functions.
2026-07-11 17:49:45 +02:00
dw-0 58e3eb9f06 feat(klipper): support headless install/remove/update
Add interactive parameter to KlipperSetupService.install/remove/update so the

CLI can run without prompts.

Make check_user_groups honor the interactive flag and add headless tests.
2026-07-11 17:49:45 +02:00
dw-0 09dd8298f7 refactor(webui_client): extract install/remove/update logic into services
Replace monolithic client_setup.py, client_config_setup.py and their

remove counterparts with service classes under components/webui_client/services.

Update menus and core install/update menus to call the new services.

Add unit tests for services, client_utils and menu wiring.
2026-07-11 17:49:39 +02:00
dw-0 93e7bb7212 style: remove blank lines from simple_config_parser test imports 2026-07-11 00:27:42 +02:00
dw-0 e4eb36d72f refactor(utils): delegate subprocess and filesystem calls to shared backends
Route fs_utils and sys_utils subprocess/filesystem operations through

core.backends so tests can substitute a fake runner or filesystem from one place.

Make create_python_venv, update_python_pip and update_system_package_lists

raise RuntimeError on failure so callers decide whether to fail fast or recover.

Catch apt update failures in UpdateMenu to keep the menu usable.
2026-07-11 00:27:35 +02:00
dw-0 8b9d172805 test: suppress logger output globally during tests
Add an autouse fixture in kiauh/conftest.py that patches Logger methods

so tests produce clean, assertion-focused output.
2026-07-11 00:27:03 +02:00
dw-0 6aa170fd68 feat(tests): add pluggable subprocess and filesystem backends
Introduce core.backends with CommandRunner and FilesystemBackend protocols plus

default subprocess/local filesystem implementations.

Add fake backends in tests.helpers.fake_backends for isolated unit tests.
2026-07-11 00:26:59 +02:00
dw-0 861cb2bff4 chore: add pytest-cov and CI workflow
Add GitHub Actions workflow for running tests with coverage on Python 3.8 and 3.11.

Configure pytest-cov, coverage thresholds and expand testpaths in pyproject.toml.

Update .gitignore for .ruff_cache, .mypy_cache, *.egg-info and .coverage.
2026-07-11 00:26:49 +02:00
dw-0 7b5522ac94 feat(tests): add unit tests for shared utilities 2026-07-04 12:58:20 +02:00
Cody D DixonandGitHub a42b730688 fix: catch FileNotFoundError in get_current_branch when component dir is missing (#813)
Error when opening KIUAH fix

get_current_branch only catches CalledProcessError, not FileNotFoundError. When crowsnest isn't installed, the missing dir propagates the exception. Fix
2026-06-29 22:43:10 +02:00
dw-0 77d6c87aa0 refactor(readme): update section titles and improve table formatting 2026-06-29 22:20:55 +02:00
dw-0 b893ff14f7 chore(readme): remove jetbrains as sponsor 2026-06-29 21:36:58 +02:00
dw-0 43b0994ac5 fix(README_zh): correct Fluidd logo image path in documentation 2026-06-29 21:31:55 +02:00
dw-0 040edc1d4f chore: remove AGENTS.md 2026-06-28 12:50:59 +02:00
750dba1dbe feat(extensions): add Moongate for Klipper (#809)
* feat(extensions): add Moongate for Klipper

Adds Moongate for Klipper as extension #15 (next free index after KAMP). Moongate pairs a printer with the Moongate Android app for secure remote access and print monitoring over a Cloudflare quick-tunnel fronted by an EdDSA auth proxy.

The extension is KIAUH-native for the parts KIAUH owns (Moonraker instance discovery, the install/remove confirmation dialogs, moonraker.conf backup, and the repo clone wired into the update manager) and delegates the heavy, security-sensitive install steps (cloudflared, the moongate-authproxy and moongate-tunnel systemd services, the Moonraker host rebind) to Moongate's own idempotent, non-interactive install/update/uninstall scripts so that logic stays maintained upstream in one place.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(metadata): update index for Moongate extension

* refactor(moongate_extension): enhance error handling and update docstring for clarity

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: dw-0 <th33xitus@gmail.com>
2026-06-28 12:49:30 +02:00
6f4b471008 feat(extension): Add DroidKlipp extension (#804)
* Add DroidKlipp extension

* fix(extensions): restart adb_monitor and redeploy monitor on DroidKlipp update

The update flow only ran git_pull_wrapper, which left the running
adb_monitor service executing stale in-memory code. It also never
rebuilt the deployed ~/droidklipp_monitor.py, since that file is
generated by the installer rather than tracked in the repo.

- stop adb_monitor before the pull, start it after (mirrors mobileraker)
- after pulling, re-deploy droidklipp_monitor.py into $HOME so the
  service picks up the updated code
- best-effort restart the service if the update fails

* fix(droidklipp): clean up comments and update website link in metadata

---------

Co-authored-by: Cody Dixon <codydixon71@gmail.com>
Co-authored-by: dw-0 <th33xitus@gmail.com>
2026-06-28 12:07:19 +02:00
5077765fd6 fix: fluidd logo (#811)
* fix: fluid logo

* fix: use correct logo.svg instead of avatar

---------

Co-authored-by: dw-0 <th33xitus@gmail.com>
2026-06-27 12:53:20 +02:00
Patrick GehrsitzandGitHub 9f97ae6c2a refactor(crowsnest): fix crowsnest install status and update for v5 (#799)
fix: fix crowsnest install status and update for v5

Crowsnest v5 introduced multiple breaking changes resulting in a
'Incomplete' install status even after successful installation.
This adds support for the new v5 setup with backwards compatibility for
old versions.

Signed-off-by: Patrick Gehrsitz <github@mryel.de>
2026-05-30 15:36:32 +02:00
_Redstone_c_andGitHub b90a8f13b1 fix(switch_repo): honor use_python_binary when recreating venv (#793)
* fix(switch_repo): honor use_python_binary when recreating venv

* fix(switch_repo): validate name at function entry
2026-04-24 13:34:45 +02:00
ea1b794afd feat(extensions): Klipper-Adaptive-Meshing-Purging (#785)
* feat(instance_manager): add interactive stopping of Klipper instances with user confirmation

* fix(instance_utils): remove unnecessary 'self' parameter from stop_klipper_instances_interactively function

* refactor(tmc_autotune): replace internal stop function with direct call to stop_klipper_instances_interactively

* feat(klipper_adaptive_meshing_purging): add initial implementation of Klipper Adaptive Meshing and Purging extension

* docs(klipper_adaptive_meshing_purging): update warning message with additional documentation note regarding max_extrude_cross_section

* fix(klipper_adaptive_meshing_purging): update warning message formatting for clarity

* fix(klipper_adaptive_meshing_purging): update warning message formatting for clarity

* fix(_install_cfg): update symlink creation to point to Configuration directory

* fix(license): update copyright information to include myself & upstream

* fix(klipper_adaptive_meshing_purging): update moonraker updater name for consistency with upstream

* style: add type annotations

- Correct minor formatting issues in copyright headers.

* fix: update import path for `simple_config_parser`

* refactor: improve logging and configuration handling for KAMP installation and removal

* style: clarify warning message for purge settings in KAMP extension

---------

Co-authored-by: dw-0 <th33xitus@gmail.com>
2026-04-21 18:00:40 +02:00
dw-0 647a7d9400 feat: add initial AGENTS.md 2026-04-20 21:49:46 +02:00
aa0609d143 fix: auto restart of KIAUH after update (#781)
* fixed auto update

* fixed the restarting logic

* testing

* removed test

* fix: colored output and remove subshell usage in kiauh_update_dialog

---------

Co-authored-by: dw-0 <th33xitus@gmail.com>
2026-04-19 20:10:36 +02:00
dw-0 2175bd55f9 refactor: integrate simple_config_parser as internal module 2026-04-19 15:48:06 +02:00
Patrick GehrsitzandGitHub a935e67431 refactor: use correct crowsnest branch for v5 and future releases (#792)
fix: fix crowsnest for v5 and future releases

Signed-off-by: Patrick Gehrsitz <github@mryel.de>
2026-04-19 14:52:16 +02:00
dw-0andGitHub 2f41e52189 fix(core): refresh system package list in update menu after update (#791) 2026-04-19 12:21:17 +02:00
Théo GaillardandGitHub 757344128a fix(extensions_menu): prevent extension index collisions during loading (#783)
* fix(extensions_menu): prevent extension index collisions during loading

* feat(extensions_menu): add GITHUB_ISSUES_URL for reporting extension loading issues
2026-03-22 13:43:20 +01:00
Théo GaillardandGitHub 7ca08f9b30 feat(instance_manager): add interactive stopping of Klipper instances (#784)
* feat(instance_manager): add interactive stopping of Klipper instances with user confirmation

* fix(instance_utils): remove unnecessary 'self' parameter from stop_klipper_instances_interactively function

* refactor(tmc_autotune): replace internal stop function with direct call to stop_klipper_instances_interactively
2026-03-22 12:01:15 +01:00
David RiosandGitHub 308079a821 fix: incorrect Logger.warn (#778)
Fix method name
2026-02-27 22:45:58 +01:00
Théo GaillardandGitHub 09a5d96b63 feat(tmc_autotune): add initial implementation of TMC Autotune extens… (#771)
* feat(tmc_autotune): add initial implementation of TMC Autotune extension with installation and update functionalities

* fix: remove useless comments

* fix: added support for Kalico style plugins directory

* refactor: extract method for moonraker update manager section removal, automatically reloading moonraker upon call
2026-02-03 20:46:24 +01:00
dw-0andGitHub 1f9d4c823a fix(settings_menu): fix regression by checking for the correct condition (#773) 2026-01-31 11:13:37 +01:00
dw-0 c8df9427b3 fix(backup): improve reusability of backup service and enhance file handling
- Refactor `BackupService` instance management for better reuse across methods.
- Avoid redundant file backups by checking for existing files.
- Enhance directory backup logic to handle nested files and directories more efficiently.
- Standardize timestamp initialization for consistent time-based backup operations.
2026-01-31 10:59:53 +01:00
Théo GaillardandGitHub 5414aba299 fix(backup_service): backup methods use proper paths (#769) (#770)
* fix(backup_service): streamline backup methods for proper paths and add docstring

* fix(backup_service): add proper destination_path in verbose output

* fix(backup_service): replaces html headers with { } to avoid rendering

* nitpick(backup_service): correct variable name for backup destination path in logging
2026-01-29 18:52:48 +01:00
Théo GaillardandGitHub 80948edbb4 fix(gcode_shell_cmd): update comment to clarify config directory usage (#767) 2026-01-19 17:04:28 +01:00
Théo GaillardandGitHub a455edba93 docs(fs_utils): add the documentation for create_symlink (#768) 2026-01-19 17:03:04 +01:00
Théo GaillardandGitHub 810ab3a2fa fix(fs-utils): enhance check_file_exist to support symlink resolution (#766) 2026-01-19 17:02:18 +01:00
dw-0 6c9a78496a fix(client_utils): ensure proper type conversion and hints for improved safety
- Standardize `str()` wrapping for color-applied strings in various returns.
- Refine type hints for better code clarity and robustness.
- Add null checks for port inputs to prevent potential errors.
2026-01-18 15:58:25 +01:00
dw-0 123ccde378 fix(core): standardize handling of None values for repo and version fields
- Improve local and remote version comparison by replacing default placeholders with None.
- Update repo and branch logic to handle None values consistently.
- Refactor type hints for better readability and accuracy.
2026-01-18 15:49:48 +01:00
dw-0andGitHub 45fde808d2 fix(update_menu): refresh component status after updates (#764)
fix(update_menu): refresh component status after updates to ensure consistency
2026-01-18 14:53:04 +01:00
dw-0andGitHub 8ba134f574 fix(ui): handle missing or empty local version values and standardize defaults (#763) 2026-01-18 14:18:27 +01:00
Théo GaillardandGitHub f951936b20 fix: navigation fallthrough in 'Get MCU ID' (Advanced Menu) (#762)
* fix: corrected back navigation in advanced menu in reference to #761

* ci: add delay after warning when no MCUs are found
2026-01-18 12:16:45 +01:00
dw-0 657d919378 chore: extend copyright year to 2026 in all headers 2026-01-11 09:37:17 +01:00
StaubgeborenerandGitHub 24c9b9daa9 chore(Klipper-Backup): Update Copyright year to 2026 (#758)
* Update copyright year to 2026

* Update copyright year in klipper_backup_extension.py
2026-01-11 09:29:33 +01:00
Thijs TriemstraandGitHub 4c511017f1 README: Update KlipperScreen link and contributor name (#753)
Update KlipperScreen link and contributor name

update maintainer for klipperscreen
2025-11-30 17:42:36 +01:00
CliffordandGitHub 372bab8847 feat(gcode_shell_command): allowing for expanding env vars (#747)
allowing for expanding env vars
2025-11-23 12:53:52 +01:00
d5062d41de refactor: remove dependency on libatlas-base-dev (#744)
Remove dependency on libatlas-base-dev

Co-authored-by: charlie-lima-bean <ktoaster@pm.me>
2025-11-23 09:25:05 +01:00
dw-0 e9459bd68e fix(backup): correct backup folder path display in menu 2025-11-09 11:58:03 +01:00
dw-0 ee460663c9 fix(spoolman): ensure proper file handling when adding Spoolman entry 2025-10-28 12:12:36 +01:00
dw-0 6f0e0146ef fix(client): improve version retrieval logic and handle JSON errors 2025-10-27 19:00:08 +01:00
dw-0 229f317025 fix(backup): do not create redundant subdirectory on single file backup 2025-10-27 09:47:09 +01:00
dw-0 48c0ae7227 fix(backup): allow reusing existing backup directory and enhance copy options 2025-10-27 09:30:33 +01:00
dw-0andGitHub 9c7b5fcb10 fix: update scp submodule so duplicate sections are preserved while editing configs (#738)
* fix: improve repository parsing logic to handle empty lines and comments more effectively

* fix: update scp submodule so duplicate sections are preserved while editing configs (#735)

* Squashed 'kiauh/core/submodules/simple_config_parser/' changes from f5eee99..5bc9e0a

5bc9e0a docs: update README
394dd7b refactor!: improve parsing and writing for config (#5)

git-subtree-dir: kiauh/core/submodules/simple_config_parser
git-subtree-split: 5bc9e0a50947f1be2f4877a10ab3a632774f82ea

* fix(logging): change warning to error message for config creation failure

* fix(config): improve readability by using descriptive variable names for options

(cherry picked from commit ae0a6b697e)

* Squashed 'kiauh/core/submodules/simple_config_parser/' changes from 5bc9e0a..eef8861

eef8861 refactor: update type hint for fallback parameter to Any
5d04325 Revert "chore: use Optional instead of | and None instead of _UNSET"

git-subtree-dir: kiauh/core/submodules/simple_config_parser
git-subtree-split: eef8861f126ddf84012ac8bed77b467926016d3e

* Squashed 'kiauh/core/submodules/simple_config_parser/' changes from eef8861..9c89612

9c89612 fix: correct assignment of raw value in option handling

git-subtree-dir: kiauh/core/submodules/simple_config_parser
git-subtree-split: 9c896124cf624e25410714649d306001250482f1

* fix: remove unnecessary whitespace in trusted_clients formatting
2025-10-26 22:03:26 +01:00
dw-0andGitHub 191bdd4874 Revert "fix: update scp submodule so duplicate sections are preserved… (#737)
Revert "fix: update scp submodule so duplicate sections are preserved while editing configs (#735)"

This reverts commit ae0a6b697e.
2025-10-26 18:58:33 +01:00
dw-0andGitHub ae0a6b697e fix: update scp submodule so duplicate sections are preserved while editing configs (#735)
* Squashed 'kiauh/core/submodules/simple_config_parser/' changes from f5eee99..5bc9e0a

5bc9e0a docs: update README
394dd7b refactor!: improve parsing and writing for config (#5)

git-subtree-dir: kiauh/core/submodules/simple_config_parser
git-subtree-split: 5bc9e0a50947f1be2f4877a10ab3a632774f82ea

* fix(logging): change warning to error message for config creation failure

* fix(config): improve readability by using descriptive variable names for options
2025-10-26 16:28:33 +01:00
dw-0 b6521fd721 fix(ui): replace top_border and bottom_border functions with inline echo statements for dialogs 2025-10-15 17:05:18 +02:00
dw-0 62b0f4f0f5 chore(deps): replace pyright with mypy in dev requirements 2025-10-13 21:54:35 +02:00
dw-0 fa9a032aad docs(changelog): update changelog for KIAUH v6 release 2025-10-12 20:37:26 +02:00
dw-0 5241d9c21f fix: update README images and paths, add new assets to docs/assets folder 2025-10-12 20:37:19 +02:00
dw-0 31150c98e2 fix: implement custom version parsing for tag sorting 2025-10-11 16:56:02 +02:00
dw-0andGitHub 3317114780 refactor(kiauh): remove legacy scripts, configurations, and assets af… (#729)
refactor(kiauh): remove legacy scripts, configurations, and assets after migration to Python-based KIAUH v6
2025-10-11 16:38:08 +02:00
dw-0 8851bd68f8 feat(ui): update messaging for KIAUH v6 to reflect RC.2 status and encourage migration from v5 2025-10-05 17:20:30 +02:00
dw-0 9168ad88a6 refactor(backup): migrate backup_printer_config_dir to BackupService and update references accordingly 2025-09-30 21:11:48 +02:00
dw-0 03c0d46a2e feat(backup): add fallback to search printer data directories in home directory if no instances found 2025-09-30 20:59:04 +02:00
dw-0 8a8afc60ee feat(backup): integrate backup functionality into multiple extensions and config management 2025-09-30 20:36:42 +02:00
dw-0 5b68710b23 feat(backup): add specific backup methods for Klipper and Moonraker configs 2025-09-29 21:21:55 +02:00
dw-0 6cee0252ee feat(moonraker): sync moonraker changes to SysDepsParser
https://github.com/Arksine/moonraker/commit/206fd4828d34aae5fd6aa95f8dfb31eb1fbb7df1

https://github.com/Arksine/moonraker/commit/72b89d905ee66b621ea3c4c633541e181822b448
2025-09-29 20:29:38 +02:00
dw-0 aff63665de refactor: replace backup_manager with backup_service 2025-09-28 16:14:58 +02:00
dw-0 1ed1e0fc4c chore(dev): replace pyright with mypy and configure mypy rules 2025-09-27 22:44:03 +02:00
dw-0 81ac102644 fix(v5): add back example file for custom Klipper repository management 2025-09-20 15:17:37 +02:00
dw-0andGitHub 89b48168f4 fix: do not drop SAVE_CONFIG block when editing and writing config files (#723)
Squashed 'kiauh/core/submodules/simple_config_parser/' changes from 4a6e5f2..f5eee99

f5eee99 feat: add support for parsing and handling `SAVE_CONFIG` blocks (#4)
8170583 refactor(api)!: `getval` now returns a string, `getvals` returns list of strings

git-subtree-dir: kiauh/core/submodules/simple_config_parser
git-subtree-split: f5eee99b0f04717c6bbf30c1256d70ad019223d5
2025-09-06 13:12:20 +02:00
195b7fa926 fix: add moonraker-hmi and moonraker-telegram-bot to the blacklist (#720)
* Add moonraker-hmi and moonraker-telegram-bot to the blacklist of moonraker service detection function

* fix: add "hmi" to SUFFIX_BLACKLIST to prevent instance name conflicts

Signed-off-by: Dominik Willner <th33xitus@gmail.com>

---------

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
Co-authored-by: dw-0 <th33xitus@gmail.com>
2025-08-31 11:30:16 +02:00
dw-0 12919c7140 feat(extension): add website and repo metadata for extensions, update links formatting in menu
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-08-30 22:02:12 +02:00
dw-0 e590f668e6 fix(common): return default version if no tags exist in get_kiauh_version
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-08-28 18:28:40 +02:00
ToviandGitHub 075f2d384b docs(readme): add chinese readme instructions (#707)
* add chinese readme

* translated raspberry pi to chinese
2025-08-28 17:45:39 +02:00
dw-0andGitHub afdde34721 feat(core): add repository management to settings (#718)
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-08-28 16:22:02 +02:00
dw-0andGitHub 393dd1d5bf feat(extension): add OctoPrint installer (#716)
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-08-28 16:21:42 +02:00
dw-0 8170057434 fix(moonraker): correctly patch trusted_clients options
fixes #711 #709

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-08-03 10:07:13 +02:00
Maksym PyrozhokandGitHub 985b66d41f chore: fix typos (#695)
Fix typo.
2025-07-12 19:36:38 +02:00
dw-0andGitHub f95d2586bf fix(webclient): add config.json to moonraker persistent files (#699)
fixes #694

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-06-28 10:12:28 +02:00
dw-0andGitHub f5141e7eff fix(mainsail): check for json configured as instanceDB (#698)
fix(mainsail): check for json configures as instanceDB

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-06-27 22:37:44 +02:00
dw-0andGitHub 33113e72e9 fix: exception raised on pip warning (#688)
pip seems to write to stderr on warnings, caused by retries. even if the process exits with 0.

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-05-31 17:44:02 +02:00
dw-0andGitHub 6f59fd06aa fix: do not upgrade pip before installing packages (#680)
pip 25 seems to introduce some compatibility issues.

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-05-02 20:08:32 +02:00
dw-0 56ea43ccb6 refactor: improve typesafety KiauhSettings
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-04-14 21:19:38 +02:00
dw-0 25e22c993f chore(scp): update SimpleConfigParser
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-04-14 21:15:12 +02:00
dw-0 ead521b377 refactor: replace mypy with pyright
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-04-14 21:07:56 +02:00
dw-0 3c952ccc12 refactor: use sane fallbacks on missing kiauh config options
for some options a warning is print if the fallback is used

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-04-12 15:12:11 +02:00
dw-0 c8f713c00e fix: no validation of optional_speedups option
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2025-04-12 00:36:34 +02:00
320 changed files with 14345 additions and 14005 deletions
+36
View File
@@ -0,0 +1,36 @@
name: Tests
on:
push:
branches: [develop, master]
pull_request:
branches: [develop, master]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.11"]
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -e ".[dev]"
- name: Run tests with coverage
run: pytest --cov=kiauh --cov-report=xml --cov-report=term
- name: Upload coverage
uses: actions/upload-artifact@v4
with:
name: coverage-${{ matrix.python-version }}
path: coverage.xml
+6
View File
@@ -1,12 +1,18 @@
.idea
.vscode
.pytest_cache
.ruff_cache
.mypy_cache
.jupyter
*.ipynb
*.ipynb_checkpoints
*.tmp
__pycache__
.kiauh-env
.venv
*.code-workspace
*.iml
*.egg-info
.coverage
kiauh.cfg
klipper_repos.txt
-15
View File
@@ -1,15 +0,0 @@
source=scripts
enable=avoid-nullary-conditions
enable=deprecate-which
enable=quote-safe-variables
enable=require-variable-braces
enable=require-double-brackets
# SC2162: `read` without `-r` will mangle backslashes.
# https://github.com/koalaman/shellcheck/wiki/SC2162
disable=SC2162
# SC2164: Use `cd ... || exit` in case `cd` fails
# https://github.com/koalaman/shellcheck/wiki/SC2164
disable=SC2164
+100 -62
View File
@@ -1,8 +1,6 @@
<p align="center">
<a>
<img src="https://raw.githubusercontent.com/dw-0/kiauh/master/resources/screenshots/kiauh.png" alt="KIAUH logo" height="181">
<img src="docs/assets/logo-large.png" alt="KIAUH Logo" height="181">
<h1 align="center">Klipper Installation And Update Helper</h1>
</a>
</p>
<p align="center">
@@ -27,81 +25,106 @@
</h2>
### 📋 Prerequisites
KIAUH is a script that assists you in installing Klipper on a Linux operating system that has
already been flashed to your Raspberry Pi's (or other SBC's) SD card. As a result, you must ensure
that you have a functional Linux system on hand. `Raspberry Pi OS Lite (either 32bit or 64bit)` is a recommended Linux image
if you are using a Raspberry Pi. The [official Raspberry Pi Imager](https://www.raspberrypi.com/software/)
KIAUH is a script that assists you in installing Klipper on a Linux operating
system that has
already been flashed to your Raspberry Pi's (or other SBC's) SD card. As a
result, you must ensure
that you have a functional Linux system on hand.
`Raspberry Pi OS Lite (either 32bit or 64bit)` is a recommended Linux image
if you are using a Raspberry Pi.
The [official Raspberry Pi Imager](https://www.raspberrypi.com/software/)
is the simplest way to flash an image like this to an SD card.
* Once you have downloaded, installed and launched the Raspberry Pi Imager,
select `Choose OS -> Raspberry Pi OS (other)`: \
select `Choose OS -> Raspberry Pi OS (other)`: \
<p align="center">
<img src="https://raw.githubusercontent.com/dw-0/kiauh/master/resources/screenshots/rpi_imager1.png" alt="KIAUH logo" height="350">
<img src="docs/assets/rpi_imager1.png" alt="KIAUH logo" height="350">
</p>
* Then select `Raspberry Pi OS Lite (32bit)` (or 64bit if you want to use that instead):
* Then select `Raspberry Pi OS Lite (32bit)` (or 64bit if you want to use that
instead):
<p align="center">
<img src="https://raw.githubusercontent.com/dw-0/kiauh/master/resources/screenshots/rpi_imager2.png" alt="KIAUH logo" height="350">
<img src="docs/assets/rpi_imager2.png" alt="KIAUH logo" height="350">
</p>
* Back in the Raspberry Pi Imager's main menu, select the corresponding SD card to which
you want to flash the image.
* Back in the Raspberry Pi Imager's main menu, select the corresponding SD card
to which
you want to flash the image.
* Make sure to go into the Advanced Option (the cog icon in the lower left corner of the main menu)
and enable SSH and configure Wi-Fi.
* Make sure to go into the Advanced Option (the cog icon in the lower left
corner of the main menu)
and enable SSH and configure Wi-Fi.
* If you need more help for using the Raspberry Pi Imager, please visit the [official documentation](https://www.raspberrypi.com/documentation/computers/getting-started.html).
* If you need more help for using the Raspberry Pi Imager, please visit
the [official documentation](https://www.raspberrypi.com/documentation/computers/getting-started.html).
These steps **only** apply if you are actually using a Raspberry Pi. In case you want
to use a different SBC (like an Orange Pi or any other Pi derivates), please look up on how to get an appropriate Linux image flashed
to the SD card before proceeding further (usually done with Balena Etcher in those cases). Also make sure that KIAUH will be able to run
and operate on the Linux Distribution you are going to flash. You likely will have the most success with
distributions based on Debian 11 Bullseye. Read the notes further down below in this document.
These steps **only** apply if you are actually using a Raspberry Pi. In case you
want
to use a different SBC (like an Orange Pi or any other Pi derivates), please
look up on how to get an appropriate Linux image flashed
to the SD card before proceeding further (usually done with Balena Etcher in
those cases). Also make sure that KIAUH will be able to run
and operate on the Linux Distribution you are going to flash. You likely will
have the most success with
distributions based on Debian 11 Bullseye. Read the notes further down below in
this document.
### 💾 Download and use KIAUH
**📢 Disclaimer: Usage of this script happens at your own risk!**
* **Step 1:** \
To download this script, it is necessary to have git installed. If you don't have git already installed, or if you are unsure, run the following command:
To download this script, it is necessary to have git installed. If you don't
have git already installed, or if you are unsure, run the following command:
```shell
sudo apt-get update && sudo apt-get install git -y
```
* **Step 2:** \
Once git is installed, use the following command to download KIAUH into your home-directory:
Once git is installed, use the following command to download KIAUH into your
home-directory:
```shell
cd ~ && git clone https://github.com/dw-0/kiauh.git
```
* **Step 3:** \
Finally, start KIAUH by running the next command:
Finally, start KIAUH by running the next command:
```shell
./kiauh/kiauh.sh
```
* **Step 4:** \
You should now find yourself in the main menu of KIAUH. You will see several actions to choose from depending
on what you want to do. To choose an action, simply type the corresponding number into the "Perform action"
prompt and confirm by hitting ENTER.
You should now find yourself in the main menu of KIAUH. You will see several
actions to choose from depending
on what you want to do. To choose an action, simply type the corresponding
number into the "Perform action"
prompt and confirm by hitting ENTER.
<hr>
<h2 align="center">❗ Notes ❗</h2>
### **📋 Please see the [Changelog](docs/changelog.md) for possible important changes!**
### **📋 Please see the [Changelog](docs/changelog.md) for possible important
changes!**
- Mainly tested on Raspberry Pi OS Lite (Debian 10 Buster / Debian 11 Bullseye)
- Other Debian based distributions (like Ubuntu 20 to 22) likely work too
- Reported to work on Armbian as well but not tested in detail
- During the use of this script you will be asked for your sudo password. There are several functions involved which need sudo privileges.
- During the use of this script you will be asked for your sudo password. There
are several functions involved which need sudo privileges.
<hr>
<h2 align="center">🌐 Sources & Further Information</h2>
<h2 align="center">⚙️ Core Components ⚙️</h2>
<table align="center">
<table align="center" style="text-align: center;">
<tr>
<th><h3><a href="https://github.com/Klipper3d/klipper">Klipper</a></h3></th>
<th><h3><a href="https://github.com/Arksine/moonraker">Moonraker</a></h3></th>
@@ -117,67 +140,88 @@ prompt and confirm by hitting ENTER.
<th>by <a href="https://github.com/Arksine">Arksine</a></th>
<th>by <a href="https://github.com/mainsail-crew">mainsail-crew</a></th>
</tr>
<tr>
<th><h3><a href="https://github.com/fluidd-core/fluidd">Fluidd</a></h3></th>
<th><h3><a href="https://github.com/jordanruthe/KlipperScreen">KlipperScreen</a></h3></th>
<th><h3><a href="https://github.com/OctoPrint/OctoPrint">OctoPrint</a></h3></th>
<th><h3><a href="https://github.com/KlipperScreen/KlipperScreen">KlipperScreen</a></h3></th>
<th></th>
</tr>
<tr>
<th><img src="https://raw.githubusercontent.com/fluidd-core/fluidd/master/docs/assets/images/logo.svg" alt="Fluidd Logo" height="64"></th>
<th><img src="https://avatars.githubusercontent.com/u/31575189?v=4" alt="jordanruthe avatar" height="64"></th>
<th><img src="https://raw.githubusercontent.com/OctoPrint/OctoPrint/master/docs/images/octoprint-logo.png" alt="OctoPrint Logo" height="64"></th>
<th><img src="https://raw.githubusercontent.com/fluidd-core/fluidd/master/docs/docs/assets/images/logo.svg" alt="Fluidd Logo" height="64"></th>
<th><img src="https://avatars.githubusercontent.com/KlipperScreen?v=4" alt="KlipperScreen Logo" height="64"></th>
<th></th>
</tr>
<tr>
<th>by <a href="https://github.com/fluidd-core">fluidd-core</a></th>
<th>by <a href="https://github.com/jordanruthe">jordanruthe</a></th>
<th>by <a href="https://github.com/OctoPrint">OctoPrint</a></th>
<th>by <a href="https://github.com/alfrix">alfrix</a></th>
<th></th>
</tr>
</table>
<hr>
<h2 align="center">🧩 Community Extensions 🧩</h2>
<table align="center" style="text-align: center;">
<tr>
<th><h3><a href="https://github.com/OctoPrint/OctoPrint">OctoPrint</a></h3></th>
<th><h3><a href="https://github.com/nlef/moonraker-telegram-bot">Moonraker-Telegram-Bot</a></h3></th>
<th><h3><a href="https://github.com/Kragrathea/pgcode">PrettyGCode for Klipper</a></h3></th>
<th><h3><a href="https://github.com/TheSpaghettiDetective/moonraker-obico">Obico for Klipper</a></h3></th>
</tr>
<tr>
<th><img src="https://avatars.githubusercontent.com/u/52351624?v=4" alt="nlef avatar" height="64"></th>
<th><img src="https://avatars.githubusercontent.com/u/5917231?v=4" alt="Kragrathea avatar" height="64"></th>
<th><img src="https://avatars.githubusercontent.com/u/46323662?s=200&v=4" alt="Obico logo" height="64"></th>
<th><a href="https://github.com/OctoPrint/OctoPrint"><img src="https://raw.githubusercontent.com/OctoPrint/OctoPrint/master/docs/images/octoprint-logo.png" alt="OctoPrint Logo" height="64"></a></th>
<th><a href="https://github.com/nlef/moonraker-telegram-bot"><img src="https://avatars.githubusercontent.com/u/52351624?v=4" alt="nlef avatar" height="64"></a></th>
<th><a href="https://github.com/Kragrathea/pgcode"><img src="https://avatars.githubusercontent.com/u/5917231?v=4" alt="Kragrathea avatar" height="64"></a></th>
</tr>
<tr>
<th>by <a href="https://github.com/OctoPrint">OctoPrint</a></th>
<th>by <a href="https://github.com/nlef">nlef</a></th>
<th>by <a href="https://github.com/Kragrathea">Kragrathea</a></th>
<th>by <a href="https://github.com/TheSpaghettiDetective">Obico</a></th>
</tr>
<tr>
<th><h3><a href="https://github.com/TheSpaghettiDetective/moonraker-obico">Obico for Klipper</a></h3></th>
<th><h3><a href="https://github.com/Clon1998/mobileraker_companion">Mobileraker's Companion</a></h3></th>
<th><h3><a href="https://octoeverywhere.com/?source=kiauh_readme">OctoEverywhere For Klipper</a></h3></th>
<th><h3><a href="https://github.com/crysxd/OctoApp-Plugin">OctoApp For Klipper</a></h3></th>
</tr>
<tr>
<th><a href="https://github.com/TheSpaghettiDetective/moonraker-obico"><img src="https://avatars.githubusercontent.com/u/46323662?s=200&v=4" alt="Obico logo" height="64"></a></th>
<th><a href="https://github.com/Clon1998/mobileraker_companion"><img src="https://raw.githubusercontent.com/Clon1998/mobileraker/master/assets/icon/mr_appicon.png" alt="Mobileraker Logo" height="64"></a></th>
<th><a href="https://octoeverywhere.com/?source=kiauh_readme"><img src="https://octoeverywhere.com/img/logo.svg" alt="OctoEverywhere Logo" height="64"></a></th>
<th><a href="https://octoapp.eu/?source=kiauh_readme"><img src="https://octoapp.eu/octoapp.webp" alt="OctoApp Logo" height="64"></a></th>
</tr>
<tr>
<th>by <a href="https://github.com/TheSpaghettiDetective">Obico</a></th>
<th>by <a href="https://github.com/Clon1998">Patrick Schmidt</a></th>
<th>by <a href="https://github.com/QuinnDamerell">Quinn Damerell</a></th>
<th>by <a href="https://github.com/crysxd">Christian Würthner</a></th>
</tr>
<tr>
<th><h3><a href="https://github.com/crysxd/OctoApp-Plugin">OctoApp For Klipper</a></h3></th>
<th><h3><a href="https://github.com/staubgeborener/klipper-backup">Klipper-Backup</a></h3></th>
<th><h3><a href="https://simplyprint.io/">SimplyPrint for Klipper</a></h3></th>
</tr>
<tr>
<th><a href="https://octoapp.eu/?source=kiauh_readme"><img src="https://octoapp.eu/octoapp.webp" alt="OctoApp Logo" height="64"></a></th>
<th><a href="https://github.com/staubgeborener/klipper-backup"><img src="https://avatars.githubusercontent.com/u/28908603?v=4" alt="Staubgeroner Avatar" height="64"></a></th>
<th><a href="https://github.com/SimplyPrint"><img src="https://avatars.githubusercontent.com/u/64896552?s=200&v=4" alt="" height="64"></a></th>
<th><a href="https://github.com/SimplyPrint"><img src="https://avatars.githubusercontent.com/u/64896552?s=200&v=4" alt="SimplyPrint Logo" height="64"></a></th>
</tr>
<tr>
<th>by <a href="https://github.com/crysxd">Christian Würthner</a></th>
<th>by <a href="https://github.com/Staubgeborener">Staubgeborener</a></th>
<th>by <a href="https://github.com/SimplyPrint">SimplyPrint</a></th>
</tr>
<tr>
<th><h3><a href="https://github.com/CodeMasterCody3D/DroidKlipp">DroidKlipp</a></h3></th>
<th><h3><a href="https://github.com/PEEKYPAUL/Moongate">Moongate</a></h3></th>
<th></th>
</tr>
<tr>
<th><a href="https://github.com/CodeMasterCody3D/DroidKlipp"><img src="https://raw.githubusercontent.com/CodeMasterCody3D/DroidKlipp/main/logo.png" alt="DroidKlipp Logo" height="64"></a></th>
<th><a href="https://github.com/PEEKYPAUL/Moongate"><img src="https://raw.githubusercontent.com/PEEKYPAUL/Moongate/master/docs/moongate-icon.png" alt="Moongate Logo" height="64"></a></th>
<th></th>
</tr>
<tr>
<th>by <a href="https://github.com/CodeMasterCody3D">CodeMasterCody3D</a></th>
<th>by <a href="https://github.com/PEEKYPAUL">PEEKYPAUL</a></th>
<th></th>
</tr>
</table>
<hr>
@@ -200,15 +244,9 @@ prompt and confirm by hitting ENTER.
<h2 align="center">✨ Credits ✨</h2>
* A big thank you to [lixxbox](https://github.com/lixxbox) for that awesome KIAUH-Logo!
* Also, a big thank you to everyone who supported my work with a [Ko-fi](https://ko-fi.com/dw__0) !
* Last but not least: Thank you to all contributors and members of the Klipper Community who like and share this project!
<hr>
<h4 align="center">A special thank you to JetBrains for sponsoring this project with their incredible software!</h4>
<p align="center">
<a href="https://www.jetbrains.com/community/opensource/#support" target="_blank">
<img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo (Main) logo." height="128">
</a>
</p>
* A big thank you to [lixxbox](https://github.com/lixxbox) for that awesome
KIAUH-Logo!
* Also, a big thank you to everyone who supported my work with
a [Ko-fi](https://ko-fi.com/dw__0) !
* Last but not least: Thank you to all contributors and members of the Klipper
Community who like and share this project!
+224
View File
@@ -0,0 +1,224 @@
# KIAUH - Klipper 安装与更新助手
<p align="center">
<a>
<img src="docs/assets/logo-large.png" alt="KIAUH logo" height="181">
<h1 align="center">Klipper Installation And Update Helper</h1>
</a>
</p>
<p align="center">
一个方便的安装脚本,让安装Klipper(以及更多组件)变得轻松!
</p>
<p align="center">
<a><img src="https://img.shields.io/github/license/dw-0/kiauh"></a>
<a><img src="https://img.shields.io/github/stars/dw-0/kiauh"></a>
<a><img src="https://img.shields.io/github/forks/dw-0/kiauh"></a>
<a><img src="https://img.shields.io/github/languages/top/dw-0/kiauh?logo=gnubash&logoColor=white"></a>
<a><img src="https://img.shields.io/github/v/tag/dw-0/kiauh"></a>
<br />
<a><img src="https://img.shields.io/github/last-commit/dw-0/kiauh"></a>
<a><img src="https://img.shields.io/github/contributors/dw-0/kiauh"></a>
</p>
## 📄 使用说明
### 📋 系统要求
KIAUH 是一个帮助您在 Linux 系统上安装 Klipper 的脚本工具,
它需要一个已经写入树莓派(或其他单板计算机)SD 卡的 Linux 系统。
如果您使用树莓派,推荐使用 `Raspberry Pi OS Lite (32位或64位)` 系统镜像。
[官方 Raspberry Pi Imager](https://www.raspberrypi.com/software/) 是将此类镜像写入 SD 卡的最简单方式。
* 下载、安装并启动 Raspberry Pi Imager 后,
选择 `Choose OS -> Raspberry Pi OS (other)`:
<p align="center">
<img src="docs/assets/rpi_imager1.png" alt="KIAUH logo" height="350">
</p>
* 然后选择 `Raspberry Pi OS Lite (32位)` (或如果您想使用64位版本):
<p align="center">
<img src="docs/assets/rpi_imager2.png" alt="KIAUH logo" height="350">
</p>
* 返回 Raspberry Pi Imager 主界面,选择对应的 SD 卡作为写入目标。
* 确保点击左下角的齿轮图标(在主菜单中)
启用 SSH 并配置 Wi-Fi。
* 如果您需要更多关于使用 Raspberry Pi Imager 的帮助,请访问 [官方文档](https://www.raspberrypi.com/documentation/computers/getting-started.html)。
这些步骤**仅适用于**您实际使用树莓派的情况。如果您想使用其他单板计算机(如香橙派或其他 Pi 衍生产品),
请查找如何将合适的 Linux 镜像写入 SD 卡(通常使用 Balena Etcher)。
同时确保 KIAUH 能够在您要安装的 Linux 发行版上运行。
您在使用基于 Debian 11 Bullseye 的系统时可能会获得最佳体验。
请阅读本文档下方的注意事项。
### 💾 下载并使用 KIAUH
**📢 免责声明:使用此脚本的风险由您自行承担!**
* **第一步:**
要下载此脚本,需要先安装 git。
如果您不确定是否已安装 git,请运行以下命令:
```shell
sudo apt-get update && sudo apt-get install git -y
```
* **第二步:**
安装完 git 后,
使用以下命令将 KIAUH 下载到您的主目录:
```shell
cd ~ && git clone https://github.com/dw-0/kiauh.git
```
* **第三步:**
最后,通过运行以下命令启动 KIAUH:
```shell
./kiauh/kiauh.sh
```
* **第四步:**
您现在应该会看到 KIAUH 的主菜单。
根据您的选择,
您会看到几个可选操作。
要选择某个操作,只需在 "Perform action" 提示后输入对应的数字并按回车键确认。
## ❗ 注意事项
### **📋 请查看 [更新日志](docs/changelog.md) 以了解可能的重要更新!**
- 主要在 Raspberry Pi OS Lite (Debian 10 Buster / Debian 11 Bullseye) 上测试
- 其他基于 Debian 的发行版(如 Ubuntu 20 到 22)也可能正常工作
- 据报告在 Armbian 上也可用,但未进行详细测试
- 在使用此脚本的过程中,
您会被要求输入 sudo 密码。
因为有几个功能需要 sudo 权限。
<h2 align="center">⚙️ 核心组件 ⚙️</h2>
<table align="center" style="text-align: center;">
<tr>
<th><h3><a href="https://github.com/Klipper3d/klipper">Klipper</a></h3></th>
<th><h3><a href="https://github.com/Arksine/moonraker">Moonraker</a></h3></th>
<th><h3><a href="https://github.com/mainsail-crew/mainsail">Mainsail</a></h3></th>
</tr>
<tr>
<th><img src="https://raw.githubusercontent.com/Klipper3d/klipper/master/docs/img/klipper-logo.png" alt="Klipper Logo" height="64"></th>
<th><img src="https://avatars.githubusercontent.com/u/9563098?v=4" alt="Arksine avatar" height="64"></th>
<th><img src="https://raw.githubusercontent.com/mainsail-crew/docs/master/assets/img/logo.png" alt="Mainsail Logo" height="64"></th>
</tr>
<tr>
<th>由 <a href="https://github.com/KevinOConnor">KevinOConnor</a></th>
<th>由 <a href="https://github.com/Arksine">Arksine</a></th>
<th>由 <a href="https://github.com/mainsail-crew">mainsail-crew</a></th>
</tr>
<tr>
<th><h3><a href="https://github.com/fluidd-core/fluidd">Fluidd</a></h3></th>
<th><h3><a href="https://github.com/KlipperScreen/KlipperScreen">KlipperScreen</a></h3></th>
<th></th>
</tr>
<tr>
<th><img src="https://raw.githubusercontent.com/fluidd-core/fluidd/master/docs/docs/assets/images/logo.svg" alt="Fluidd Logo" height="64"></th>
<th><img src="https://avatars.githubusercontent.com/KlipperScreen?v=4" alt="KlipperScreen Logo" height="64"></th>
<th></th>
</tr>
<tr>
<th>由 <a href="https://github.com/fluidd-core">fluidd-core</a></th>
<th>由 <a href="https://github.com/alfrix">alfrix</a></th>
<th></th>
</tr>
</table>
<hr>
<h2 align="center">🧩 社区扩展 🧩</h2>
<table align="center" style="text-align: center;">
<tr>
<th><h3><a href="https://github.com/OctoPrint/OctoPrint">OctoPrint</a></h3></th>
<th><h3><a href="https://github.com/nlef/moonraker-telegram-bot">Moonraker-Telegram-Bot</a></h3></th>
<th><h3><a href="https://github.com/Kragrathea/pgcode">PrettyGCode for Klipper</a></h3></th>
</tr>
<tr>
<th><a href="https://github.com/OctoPrint/OctoPrint"><img src="https://raw.githubusercontent.com/OctoPrint/OctoPrint/master/docs/images/octoprint-logo.png" alt="OctoPrint Logo" height="64"></a></th>
<th><a href="https://github.com/nlef/moonraker-telegram-bot"><img src="https://avatars.githubusercontent.com/u/52351624?v=4" alt="nlef avatar" height="64"></a></th>
<th><a href="https://github.com/Kragrathea/pgcode"><img src="https://avatars.githubusercontent.com/u/5917231?v=4" alt="Kragrathea avatar" height="64"></a></th>
</tr>
<tr>
<th>由 <a href="https://github.com/OctoPrint">OctoPrint</a></th>
<th>由 <a href="https://github.com/nlef">nlef</a></th>
<th>由 <a href="https://github.com/Kragrathea">Kragrathea</a></th>
</tr>
<tr>
<th><h3><a href="https://github.com/TheSpaghettiDetective/moonraker-obico">Obico for Klipper</a></h3></th>
<th><h3><a href="https://github.com/Clon1998/mobileraker_companion">Mobileraker's Companion</a></h3></th>
<th><h3><a href="https://octoeverywhere.com/?source=kiauh_readme">OctoEverywhere For Klipper</a></h3></th>
</tr>
<tr>
<th><a href="https://github.com/TheSpaghettiDetective/moonraker-obico"><img src="https://avatars.githubusercontent.com/u/46323662?s=200&v=4" alt="Obico logo" height="64"></a></th>
<th><a href="https://github.com/Clon1998/mobileraker_companion"><img src="https://raw.githubusercontent.com/Clon1998/mobileraker/master/assets/icon/mr_appicon.png" alt="Mobileraker Logo" height="64"></a></th>
<th><a href="https://octoeverywhere.com/?source=kiauh_readme"><img src="https://octoeverywhere.com/img/logo.svg" alt="OctoEverywhere Logo" height="64"></a></th>
</tr>
<tr>
<th>由 <a href="https://github.com/TheSpaghettiDetective">Obico</a></th>
<th>由 <a href="https://github.com/Clon1998">Patrick Schmidt</a></th>
<th>由 <a href="https://github.com/QuinnDamerell">Quinn Damerell</a></th>
</tr>
<tr>
<th><h3><a href="https://github.com/crysxd/OctoApp-Plugin">OctoApp For Klipper</a></h3></th>
<th><h3><a href="https://github.com/staubgeborener/klipper-backup">Klipper-Backup</a></h3></th>
<th><h3><a href="https://simplyprint.io/">SimplyPrint for Klipper</a></h3></th>
</tr>
<tr>
<th><a href="https://octoapp.eu/?source=kiauh_readme"><img src="https://octoapp.eu/octoapp.webp" alt="OctoApp Logo" height="64"></a></th>
<th><a href="https://github.com/staubgeborener/klipper-backup"><img src="https://avatars.githubusercontent.com/u/28908603?v=4" alt="Staubgeroner Avatar" height="64"></a></th>
<th><a href="https://github.com/SimplyPrint"><img src="https://avatars.githubusercontent.com/u/64896552?s=200&v=4" alt="SimplyPrint Logo" height="64"></a></th>
</tr>
<tr>
<th>由 <a href="https://github.com/crysxd">Christian Würthner</a></th>
<th>由 <a href="https://github.com/Staubgeborener">Staubgeborener</a></th>
<th>由 <a href="https://github.com/SimplyPrint">SimplyPrint</a></th>
</tr>
<tr>
<th><h3><a href="https://github.com/CodeMasterCody3D/DroidKlipp">DroidKlipp</a></h3></th>
<th><h3><a href="https://github.com/PEEKYPAUL/Moongate">Moongate</a></h3></th>
<th></th>
</tr>
<tr>
<th><a href="https://github.com/CodeMasterCody3D/DroidKlipp"><img src="https://raw.githubusercontent.com/CodeMasterCody3D/DroidKlipp/main/logo.png" alt="DroidKlipp Logo" height="64"></a></th>
<th><a href="https://github.com/PEEKYPAUL/Moongate"><img src="https://raw.githubusercontent.com/PEEKYPAUL/Moongate/master/docs/moongate-icon.png" alt="Moongate Logo" height="64"></a></th>
<th></th>
</tr>
<tr>
<th>由 <a href="https://github.com/CodeMasterCody3D">CodeMasterCody3D</a></th>
<th>由 <a href="https://github.com/PEEKYPAUL">PEEKYPAUL</a></th>
<th></th>
</tr>
</table>
<hr>
<h2 align="center">🎖️ 贡献者 🎖️</h2>
<div align="center">
<a href="https://github.com/dw-0/kiauh/graphs/contributors">
<img src="https://contrib.rocks/image?repo=dw-0/kiauh" alt=""/>
</a>
</div>
<div align="center">
<img src="https://repobeats.axiom.co/api/embed/a1afbda9190c04a90cf4bd3061e5573bc836cb05.svg" alt="Repobeats analytics image"/>
</div>
<hr>
<h2 align="center">✨ 特别感谢 ✨</h2>
* 非常感谢 [lixxbox](https://github.com/lixxbox) 设计了如此出色的 KIAUH 标志!
* 同时,非常感谢所有通过 [Ko-fi](https://ko-fi.com/dw__0) 支持我的工作的人!
* 最后但同样重要的是:感谢所有为 Klipper 社区做出贡献的成员,以及喜欢和分享这个项目的朋友们!
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 58 KiB

+382 -138
View File
@@ -2,27 +2,64 @@
This document covers possible important changes to KIAUH.
### 2025-10-10 (v6.0.0)
KIAUH has now reached version 6! The majority of the changes mentioned in the
previous changelog are now available in the final version.
Most notible are the following changes:
- The dialog for selecting between v5 and v6 is gone and all v5 code was
removed. V6 is the new default
- You can add/remove alternative repositories for Klipper and Moonraker from
within KIAUH, no need to manually edit any file
- You can store and load firmware configurations for Klipper during the firmware
compilation process
- Spoolman is available as an extension, it does not use the bare-metal
installation anymore, instead it uses the Docker Container approach
- OctoApp is available as an extension
- OctoPrint support was NOT killed. OctoPrint is available as an extension
- I probably forgot to mention some other changes, but the idea is to create
official docs for KIAUH where the new changelog will live in the future and
available features and mechanics are explained in detail
If you really want to use v5, there is a v5 branch available in the repository.
Keep in mind that v5 will not be updated anymore.
### 2024-08-31 (v6.0.0-alpha.1)
Long time no see, but here we are again!
A lot has happened in the background, but now it is time to take it out into the wild.
A lot has happened in the background, but now it is time to take it out into the
wild.
#### KIAUH has now reached version 6! Well, at least in an alpha state...
The project has seen a complete rewrite of the script from scratch in Python.
It requires Python 3.8 or newer to run. Because this update is still in an alpha state, bugs may or will occur.
During startup, you will be asked if you want to start the new version 6 or the old version 5.
As long as version 6 is in a pre-release state, version 5 will still be available. If there are any critical issues
with the new version that were overlooked, you can always switch back to the old version.
It requires Python 3.8 or newer to run. Because this update is still in an alpha
state, bugs may or will occur.
During startup, you will be asked if you want to start the new version 6 or the
old version 5.
As long as version 6 is in a pre-release state, version 5 will still be
available. If there are any critical issues
with the new version that were overlooked, you can always switch back to the old
version.
In case you selected not to get asked about which version to start (option 3 or 4 in the startup dialog) and you want to
revert that decision, you will find a line called `version_to_launch=` within the `.kiauh.ini` file in your home directory.
Just delete that line, save the file and restart KIAUH. KIAUH will then ask you again which version you want to start.
In case you selected not to get asked about which version to start (option 3 or
4 in the startup dialog) and you want to
revert that decision, you will find a line called `version_to_launch=` within
the `.kiauh.ini` file in your home directory.
Just delete that line, save the file and restart KIAUH. KIAUH will then ask you
again which version you want to start.
Here is a list of the most important changes to KIAUH in regard to version 6:
- The majority of features available in KIAUH v5 are still available; they just got migrated from Bash to Python.
- It is now possible to add new/remove instances to/from existing multi-instance installations of Klipper and Moonraker
- KIAUH now has an Extension-System. This allows contributors to add new installers to KIAUH without having to modify the main script.
- You will now find some of the features that were previously available in the Installer-Menu in the Extensions-Menu.
- The majority of features available in KIAUH v5 are still available; they just
got migrated from Bash to Python.
- It is now possible to add new/remove instances to/from existing multi-instance
installations of Klipper and Moonraker
- KIAUH now has an Extension-System. This allows contributors to add new
installers to KIAUH without having to modify the main script.
- You will now find some of the features that were previously available in
the Installer-Menu in the Extensions-Menu.
- The current extensions are:
- G-Code Shell Command (previously found in the Advanced-Menu)
- Mainsail Theme Installer (previously found in the Advanced-Menu)
@@ -37,193 +74,348 @@ Here is a list of the most important changes to KIAUH in regard to version 6:
- The file has some default values for the currently supported options
- There might be more options in the future
- It is located in KIAUH's root directory and is called `default.kiauh.cfg`
- DO NOT EDIT the default file directly, instead make a copy of it and call it `kiauh.cfg`
- Settings changed via the Advanced-Menu will be written to the `kiauh.cfg`
- DO NOT EDIT the default file directly, instead make a copy of it and
call it `kiauh.cfg`
- Settings changed via the Advanced-Menu will be written to the
`kiauh.cfg`
- Support for OctoPrint was removed
Feel free to give version 6 a try and report any bugs or issues you encounter! Every feedback is appreciated.
Feel free to give version 6 a try and report any bugs or issues you encounter!
Every feedback is appreciated.
### 2023-06-17
KIAUH has now added support for installing Mobileraker's companion!
Mobileraker is a free and Open Source Android and iOS App for Klipper, utilizing the Moonraker API, allowing you
to control your printer. Thank you to [Clon1998](https://github.com/Clon1998) for adding this feature!
Mobileraker is a free and Open Source Android and iOS App for Klipper, utilizing
the Moonraker API, allowing you
to control your printer. Thank you to [Clon1998](https://github.com/Clon1998)
for adding this feature!
### 2023-02-03
The installer for MJPG-Streamer got replaced by crowsnest. It is an improved webcam service, utilizing ustreamer.
Please have a look here for additional info about crowsnest and how to configure it: https://github.com/mainsail-crew/crowsnest \
It's unsure if the previous MJPG-Streamer installer will be updated and make its way back into KIAUH.
A big thanks to [KwadFan](https://github.com/KwadFan) for writing the crowsnest implementation.
The installer for MJPG-Streamer got replaced by crowsnest. It is an improved
webcam service, utilizing ustreamer.
Please have a look here for additional info about crowsnest and how to configure
it: https://github.com/mainsail-crew/crowsnest \
It's unsure if the previous MJPG-Streamer installer will be updated and make its
way back into KIAUH.
A big thanks to [KwadFan](https://github.com/KwadFan) for writing the crowsnest
implementation.
### 2022-10-31
Some functions got updated, though not all of them.
The following functions are still currently unavailable:
- Installation of: MJPG-Streamer
- All backup functions and the Log-Upload
### 2022-10-20
KIAUH has now reached major version 5 !
Recently Moonraker introduced some changes which makes it necessary to change the folder structure of printer setups.
If you are interested in the details, check out this PR: https://github.com/Arksine/moonraker/pull/491 \
Although Moonraker has some mechanics available to migrate existing setups to the new file structure with the use of symlinks, fresh and clean installs
Recently Moonraker introduced some changes which makes it necessary to change
the folder structure of printer setups.
If you are interested in the details, check out this
PR: https://github.com/Arksine/moonraker/pull/491 \
Although Moonraker has some mechanics available to migrate existing setups to
the new file structure with the use of symlinks, fresh and clean installs
should be considered.
The version jump of KIAUH to v5 is a breaking change due to those major changes! That means v4 and v5 are not compatible with each other!
This is also the reason why you will currently be greeted by a yellow notification in the main menu of KIAUH leading to this changelog.
I decided to disable a few functions of the script and focus on releasing the required changes to the core components of this script.
I will work on updating the other parts of the script piece by piece during the next days/weeks.
So I am already sorry in advance if one of your desired components you wanted to install or use temporarily cannot be installed or used right now.
The version jump of KIAUH to v5 is a breaking change due to those major changes!
That means v4 and v5 are not compatible with each other!
This is also the reason why you will currently be greeted by a yellow
notification in the main menu of KIAUH leading to this changelog.
I decided to disable a few functions of the script and focus on releasing the
required changes to the core components of this script.
I will work on updating the other parts of the script piece by piece during the
next days/weeks.
So I am already sorry in advance if one of your desired components you wanted to
install or use temporarily cannot be installed or used right now.
The following functions are currently unavailable:
- Installation of: KlipperScreen, Obico, Octoprint, MJPG-Streamer, Telegram Bot and PrettyGCode
- Installation of: KlipperScreen, Obico, Octoprint, MJPG-Streamer, Telegram Bot
and PrettyGCode
- All backup functions and the Log-Upload
**So what is working?**\
Installation of Klipper, Moonraker, Mainsail and Fluidd. Both, single and multi-instance setups work!\
As already said, the rest will follow in the near future. Updating and removal of already installed components should continue to work.
Installation of Klipper, Moonraker, Mainsail and Fluidd. Both, single and
multi-instance setups work!\
As already said, the rest will follow in the near future. Updating and removal
of already installed components should continue to work.
**What was removed?**\
The option to change Klippers configuration directory got removed. From now on it will not be possible anymore to change
the configuration directory from within KIAUH and the new filestructure is enforced.
The option to change Klippers configuration directory got removed. From now on
it will not be possible anymore to change
the configuration directory from within KIAUH and the new filestructure is
enforced.
**What if I don't have an existing Klipper/Moonraker install right now?**\
Nothing important to think about, install Klipper and Moonraker. KIAUH will install both of them with the new filestructure.
Nothing important to think about, install Klipper and Moonraker. KIAUH will
install both of them with the new filestructure.
**What if I have an existing Klipper/Moonraker install?**\
First of all: Backups! Please copy all of your config files and the Moonraker database (it is a hidden folder, usually `~/.moonraker_database`) to a safe location.
After that, uninstall Klipper and Moonraker with KIAUH. You can then proceed and re-install both of them with KIAUH again. It is important that you are on KIAUH v5 for that!
Once everything is installed again, you need to manually copy your configuration files from the old `~/klipper_config` folder to the new `~/printer_data/config` folder.
Previous, by Moonraker created symlinks to folder of the old filestructure will not work anymore, you need to move the files to their new location now!
Do the same with the two files inside of `~/.moonraker_database`. Move/copy them into `~/printer_data/database`. If `~/printer_data/database` is already populated with a `data.mdb` and `lock.mdb`
delete them or simply overwrite them. Nothing should be lost as those should be empty database files. Anyway, you made backups, right?
You can now proceed and restart Moonraker. Either from within Mainsail or Fluidd, or use SSH and execute `sudo systemctl restart moonraker`.
If everything went smooth, you should be good to go again. If you see some Moonraker warnings about deprecated options in the `moonraker.conf`, go ahead and resolve them.
I will not cover them in detail here. A good source is the Moonraker documentation: https://moonraker.readthedocs.io/en/latest/configuration/
First of all: Backups! Please copy all of your config files and the Moonraker
database (it is a hidden folder, usually `~/.moonraker_database`) to a safe
location.
After that, uninstall Klipper and Moonraker with KIAUH. You can then proceed and
re-install both of them with KIAUH again. It is important that you are on KIAUH
v5 for that!
Once everything is installed again, you need to manually copy your configuration
files from the old `~/klipper_config` folder to the new `~/printer_data/config`
folder.
Previous, by Moonraker created symlinks to folder of the old filestructure will
not work anymore, you need to move the files to their new location now!
Do the same with the two files inside of `~/.moonraker_database`. Move/copy them
into `~/printer_data/database`. If `~/printer_data/database` is already
populated with a `data.mdb` and `lock.mdb`
delete them or simply overwrite them. Nothing should be lost as those should be
empty database files. Anyway, you made backups, right?
You can now proceed and restart Moonraker. Either from within Mainsail or
Fluidd, or use SSH and execute `sudo systemctl restart moonraker`.
If everything went smooth, you should be good to go again. If you see some
Moonraker warnings about deprecated options in the `moonraker.conf`, go ahead
and resolve them.
I will not cover them in detail here. A good source is the Moonraker
documentation: https://moonraker.readthedocs.io/en/latest/configuration/
**What if I have an existing Klipper/Moonraker multi-instance install?**\
Pretty much the same steps that are required for single instance installs apply to multi-instance setups. So please go ahead and read the previous paragraph if you didn't already.
Make backups of everything first. Then remove and install the desired amount of Klipper and Moonraker instances again.
Pretty much the same steps that are required for single instance installs apply
to multi-instance setups. So please go ahead and read the previous paragraph if
you didn't already.
Make backups of everything first. Then remove and install the desired amount of
Klipper and Moonraker instances again.
Now you need to move all config and database files to their new locations.\
Example with an instance called `printer_1`:\
The config files go from `~/klipper_config/printer_1` to `~/printer_1_data/config`.
The database files go from `~/.moonraker_database_1` to `~/printer_1_data/database`.
Now restart all Moonraker services. You can restart all of them at once if you launch KIAUH, and in the main menu type `restart moonraker` and hit Enter.
The config files go from `~/klipper_config/printer_1` to
`~/printer_1_data/config`.
The database files go from `~/.moonraker_database_1` to
`~/printer_1_data/database`.
Now restart all Moonraker services. You can restart all of them at once if you
launch KIAUH, and in the main menu type `restart moonraker` and hit Enter.
I hope I have covered the most important things. In case you need further support, the official Klipper Discord is a good place to ask for help.
I hope I have covered the most important things. In case you need further
support, the official Klipper Discord is a good place to ask for help.
### 2022-08-15
Support for "Obico for Klipper" was added! Huge thanks to [kennethjiang](https://github.com/kennethjiang) for helping me with the implementation!
Support for "Obico for Klipper" was added! Huge thanks
to [kennethjiang](https://github.com/kennethjiang) for helping me with the
implementation!
### 2022-05-29
KIAUH has now reached major version 4 !
* feat: Klipper can be installed under Python3 (still considered as experimental)
* feat: Klipper can be installed under Python3 (still considered as
experimental)
* feat: Klipper can be installed from custom repositories / inofficial forks
* feat: Custom instance name for multi instance installations of Klipper
* Any other multi instance will share the same name given to the corresponding Klipper instance
* E.g. klipper-voron2 -> moonraker-voron2 -> moonraker-telegram-bot-voron2
* feat: Option to allow installation of / updating to unstable Mainsail and Fluidd versions
* by default only stable versions get installed/updated
* feat: Multi-Instance OctoPrint installations now each have their own virtual python environment
* allows independent installation of plugins for each instance
* Any other multi instance will share the same name given to the
corresponding Klipper instance
* E.g. klipper-voron2 -> moonraker-voron2 -> moonraker-telegram-bot-voron2
* feat: Option to allow installation of / updating to unstable Mainsail and
Fluidd versions
* by default only stable versions get installed/updated
* feat: Multi-Instance OctoPrint installations now each have their own virtual
python environment
* allows independent installation of plugins for each instance
* feat: Implementing the use of shellcheck during development
* feat: Implementing a simple logging mechanic
* feat: Log-upload function now also allows uploading other logfiles (kiauh.log, webcamd.log etc.)
* feat: Log-upload function now also allows uploading other logfiles (kiauh.log,
webcamd.log etc.)
* feat: added several new help dialogs which try to explain various functions
* fix: During Klipper installation, checks for group membership of `tty` and `dialout` are made
* refactor: rework of the settings menu for better control the new KIAUH features
* fix: During Klipper installation, checks for group membership of `tty` and
`dialout` are made
* refactor: rework of the settings menu for better control the new KIAUH
features
* refactor: Support for DWC and DWC-for-Klipper has been removed
* refactor: The backup before update settings were moved to the KIAUH settings menu
* refactor: Switch branch function has been removed (was replaced by the custom Klipper repo feature)
* refactor: The update manager sections for Mainsail, Fluidd and KlipperScreen were removed from the moonraker.conf template
* They will now be individually added during installation of the corresponding interface
* refactor: The rollback function was reworked and now also allows rollbacks of Moonraker
* It now takes numerical inputs and reverts the corresponding repository by the given amount instead
* KIAUH does not save previous states to its config anymore like it did with the previous approach
* refactor: The backup before update settings were moved to the KIAUH settings
menu
* refactor: Switch branch function has been removed (was replaced by the custom
Klipper repo feature)
* refactor: The update manager sections for Mainsail, Fluidd and KlipperScreen
were removed from the moonraker.conf template
* They will now be individually added during installation of the
corresponding interface
* refactor: The rollback function was reworked and now also allows rollbacks of
Moonraker
* It now takes numerical inputs and reverts the corresponding repository by
the given amount instead
* KIAUH does not save previous states to its config anymore like it did with
the previous approach
### 2022-01-29
* Starting from the 28th of January, Moonraker can make use of PackageKit and PolicyKit.\
More details on that can be found [here](
https://github.com/Arksine/moonraker/issues/349) and [here](https://github.com/Arksine/moonraker/pull/346)
* KIAUH will install Moonrakers PolicyKit rules by default when __installing__ Moonraker
* KIAUH will also install Moonrakers PolicyKit rules when __updating__ Moonraker __via KIAUH__ as of now
* Starting from the 28th of January, Moonraker can make use of PackageKit and
PolicyKit.\
More details on that can be found [here](
https://github.com/Arksine/moonraker/issues/349)
and [here](https://github.com/Arksine/moonraker/pull/346)
* KIAUH will install Moonrakers PolicyKit rules by default when __installing__
Moonraker
* KIAUH will also install Moonrakers PolicyKit rules when __updating__ Moonraker
__via KIAUH__ as of now
### 2021-12-30
* Updated the doc for the usage of the [G-Code Shell Command Extension](docs/gcode_shell_command.md)
* It became apparent, that some user groups are missing on some systems. A missing video group \
membership for example caused issues when installing mjpg-streamer while not using the default pi user. \
Other issues could occur when trying to flash an MCU on Debian or Ubuntu distributions where a user might not be part
of the dialout group by default. A check for the tty group is also done. The tty group is needed for setting
up a linux MCU (currently not yet supported by KIAUH).
* There is an issue when trying to install Mainsail or Fluidd on Ubuntu 21.10. Permissions on that distro seem to have seen a rework
in comparison to 20.04 and users will be greeted with an "Error 403 - Permission denied" message after installing one of Klippers webinterfaces.
I still have to figure out a viable solution for that.
* Updated the doc for the usage of
the [G-Code Shell Command Extension](docs/gcode_shell_command.md)
* It became apparent, that some user groups are missing on some systems. A
missing video group \
membership for example caused issues when installing mjpg-streamer while not
using the default pi user. \
Other issues could occur when trying to flash an MCU on Debian or Ubuntu
distributions where a user might not be part
of the dialout group by default. A check for the tty group is also done. The
tty group is needed for setting
up a linux MCU (currently not yet supported by KIAUH).
* There is an issue when trying to install Mainsail or Fluidd on Ubuntu 21.10.
Permissions on that distro seem to have seen a rework
in comparison to 20.04 and users will be greeted with an "Error 403 -
Permission denied" message after installing one of Klippers webinterfaces.
I still have to figure out a viable solution for that.
### 2021-09-28
* New Feature! Added an installer for the Telegram Bot for Moonraker by [nlef](https://github.com/nlef).
Checkout his project! Remember to report all issues and/or bugs regarding that project in its corresponding repo and not here 😛.\
You can find it here: https://github.com/nlef/moonraker-telegram-bot
* New Feature! Added an installer for the Telegram Bot for Moonraker
by [nlef](https://github.com/nlef).
Checkout his project! Remember to report all issues and/or bugs regarding that
project in its corresponding repo and not here 😛.\
You can find it here: https://github.com/nlef/moonraker-telegram-bot
### 2021-09-24
* The flashing function got adjusted a bit. It is now possible to also flash controllers which are connected over UART and thus accessible via `/dev/ttyAMA0`. You now have to select a connection methop prior flashing which is either USB or UART.
* Due to several requests over time I have now created a Ko-fi account for those who want to support this project and my work with a small donation. Many thanks in advance to all future donors. You can support me on Ko-fi with this link: https://ko-fi.com/th33xitus
* As usual, if you find any bugs or issues please report them. I tested the little rework i did with the hardware i have available and haven't encountered any malfunctions of flashing them yet.
* The flashing function got adjusted a bit. It is now possible to also flash
controllers which are connected over UART and thus accessible via
`/dev/ttyAMA0`. You now have to select a connection methop prior flashing
which is either USB or UART.
* Due to several requests over time I have now created a Ko-fi account for those
who want to support this project and my work with a small donation. Many
thanks in advance to all future donors. You can support me on Ko-fi with this
link: https://ko-fi.com/th33xitus
* As usual, if you find any bugs or issues please report them. I tested the
little rework i did with the hardware i have available and haven't encountered
any malfunctions of flashing them yet.
### 2021-08-10
* KIAUH now supports the installation of the "PrettyGCode for Klipper" GCode-Viewer created by [Kragrathea](https://github.com/Kragrathea)! Installation, updating and removal are possible with KIAUH. For more details to this cool piece of software, please have a look here: https://github.com/Kragrathea/pgcode
* KIAUH now supports the installation of the "PrettyGCode for Klipper"
GCode-Viewer created by [Kragrathea](https://github.com/Kragrathea)!
Installation, updating and removal are possible with KIAUH. For more details
to this cool piece of software, please have a look
here: https://github.com/Kragrathea/pgcode
### 2021-07-10
* The NGINX configuration files got updated to be in sync with MainsailOS and FluiddPi. Issues with the NGINX service not starting up due to wrong configuration should be resolved now. To get the updated configuration files, please remove Moonraker and Mainsail / Fluidd with KIAUH first and then re-install it. An automated file check for those configuration files might follow in the future which then automates updating those files if there were important changes.
* The default `moonraker.conf` was updated to reflect the recent changes to the update manager section. The update channel is set to `dev`.
* The NGINX configuration files got updated to be in sync with MainsailOS and
FluiddPi. Issues with the NGINX service not starting up due to wrong
configuration should be resolved now. To get the updated configuration files,
please remove Moonraker and Mainsail / Fluidd with KIAUH first and then
re-install it. An automated file check for those configuration files might
follow in the future which then automates updating those files if there were
important changes.
* The default `moonraker.conf` was updated to reflect the recent changes to the
update manager section. The update channel is set to `dev`.
### 2021-06-29
* KIAUH will now patch the new `log_path` to existing moonraker.conf files when updating Moonraker and the entry is missing. Before that, it was necessary that the user provided that path manually to make Fluidd display the logfiles in its interface. This issue should be resolved now.
* KIAUH will now patch the new `log_path` to existing moonraker.conf files when
updating Moonraker and the entry is missing. Before that, it was necessary
that the user provided that path manually to make Fluidd display the logfiles
in its interface. This issue should be resolved now.
### 2021-06-15
* Moonraker introduced an optional `log_path` which clients can make use of to show log files located in that folder to their users. More info here: https://github.com/Arksine/moonraker/commit/829b3a4ee80579af35dd64a37ccc092a1f67682a \
Client developers agreed upon using `~/klipper_logs` as the new default log path.\
That means, from now on, Klipper and Moonraker services installed with KIAUH will place their logfiles in that mentioned folder.
* Additionally, KIAUH will now detect Klipper and Moonraker systemd services that still use the old default location of `/tmp/<service>.log` and will update them next time the user updates Klipper and/or Moonraker with the KIAUH update function.
* Additional symlinks for the following logfiles will get created along those update procedures to make them accessible through the webinterface once its supported:
* Moonraker introduced an optional `log_path` which clients can make use of to
show log files located in that folder to their users. More info
here: https://github.com/Arksine/moonraker/commit/829b3a4ee80579af35dd64a37ccc092a1f67682a \
Client developers agreed upon using `~/klipper_logs` as the new default log
path.\
That means, from now on, Klipper and Moonraker services installed with KIAUH
will place their logfiles in that mentioned folder.
* Additionally, KIAUH will now detect Klipper and Moonraker systemd services
that still use the old default location of `/tmp/<service>.log` and will
update them next time the user updates Klipper and/or Moonraker with the KIAUH
update function.
* Additional symlinks for the following logfiles will get created along those
update procedures to make them accessible through the webinterface once its
supported:
- webcamd.log
- mainsail-access.log
- mainsail-error.log
- fluidd-access.log
- fluidd-error.log
* For MainsailOS and FluiddPi users:\
MainsailOS and FluiddPi will switch the shipped Klipper service from SysVinit to systemd probably with their next release. KIAUH can already help migrate older MainsailOS (0.4.0 and below) and FluiddPi (v1.13.0) releases to match their new service-, file- and folder-structure so you don't have to re-flash the SD-Card of your Raspberry Pi.\
In detail here is what is going to happen when you use the new "CustomPiOS Migration Helper" from the Advanced Menu\
`(Main Menu -> 4 -> Enter -> 10 -> Enter)` in a short summary:
* The Klipper SysVinit service will get replaced by a Klipper systemd service
MainsailOS and FluiddPi will switch the shipped Klipper service from SysVinit
to systemd probably with their next release. KIAUH can already help migrate
older MainsailOS (0.4.0 and below) and FluiddPi (v1.13.0) releases to match
their new service-, file- and folder-structure so you don't have to re-flash
the SD-Card of your Raspberry Pi.\
In detail here is what is going to happen when you use the new "CustomPiOS
Migration Helper" from the Advanced Menu\
`(Main Menu -> 4 -> Enter -> 10 -> Enter)` in a short summary:
* The Klipper SysVinit service will get replaced by a Klipper systemd
service
* Klipper and Moonraker will use the new log-directory `~/klipper_logs`
* The webcamd service gets updated
* The webcamd script gets updated and moved from `/root/bin/webcamd` to `/usr/local/bin/webcamd`
* The NGINX `upstreams.conf` gets updated to be able to configure up to 4 webcams
* The `mainsail.txt` / `fluiddpi.txt` gets moved from `/boot` to `~/klipper_config` and renamed to `webcam.txt`
* Symlinks for the webcamd.log and various NGINX logs get created in `~/klipper_config`
* Configuration files for Klipper, Moonraker and webcamd get added to `/etc/logrotate.d`
* If they still exist, two lines will be removed from the mainsail.cfg or client_macros.cfg macro configurations:\
`SAVE_GCODE_STATE NAME=PAUSE_state` and `RESTORE_GCODE_STATE NAME=PAUSE_state`
* The webcamd script gets updated and moved from `/root/bin/webcamd` to
`/usr/local/bin/webcamd`
* The NGINX `upstreams.conf` gets updated to be able to configure up to 4
webcams
* The `mainsail.txt` / `fluiddpi.txt` gets moved from `/boot` to
`~/klipper_config` and renamed to `webcam.txt`
* Symlinks for the webcamd.log and various NGINX logs get created in
`~/klipper_config`
* Configuration files for Klipper, Moonraker and webcamd get added to
`/etc/logrotate.d`
* If they still exist, two lines will be removed from the mainsail.cfg or
client_macros.cfg macro configurations:\
`SAVE_GCODE_STATE NAME=PAUSE_state` and
`RESTORE_GCODE_STATE NAME=PAUSE_state`
* **Please note:**\
The "CustomPiOS Migration Helper" is intended to only work on "vanilla" MainsailOS and FluiddPi systems. Do not try to migrate a modified MainsailOS or FluiddPi system (for example if you already used KIAUH to re-install services or to set up a multi-instance installation for Klipper / Moonraker). This won't work.
The "CustomPiOS Migration Helper" is intended to only work on "vanilla"
MainsailOS and FluiddPi systems. Do not try to migrate a modified MainsailOS
or FluiddPi system (for example if you already used KIAUH to re-install
services or to set up a multi-instance installation for Klipper / Moonraker).
This won't work.
### 2021-01-31
* **This is a big one... KIAUH v3.0 is out.**\
With this update you can now install multiple instances of Klipper, Moonraker, Duet Web Control or Octoprint on the same Pi. This was quite a big rework of the whole script. So bugs can appear but with the help of some testers, i think there shouldn't be any critical ones anymore. In this regards thanks to @lixxbox and @zellneralex for testing.
With this update you can now install multiple instances of Klipper, Moonraker,
Duet Web Control or Octoprint on the same Pi. This was quite a big rework of
the whole script. So bugs can appear but with the help of some testers, i
think there shouldn't be any critical ones anymore. In this regards thanks to
@lixxbox and @zellneralex for testing.
* Important changes to how installations are set up now: All components get installed as systemd services. Installation via init.d was dropped completely! This shouldn't affect you at all, since the common linux distributions like RaspberryPi OS or custom distributions like MainsailOS, FluiddPi or OctoPi support both ways of installing services. I just wanted to mention it here.
* Important changes to how installations are set up now: All components get
installed as systemd services. Installation via init.d was dropped completely!
This shouldn't affect you at all, since the common linux distributions like
RaspberryPi OS or custom distributions like MainsailOS, FluiddPi or OctoPi
support both ways of installing services. I just wanted to mention it here.
* Now with KIAUH v3.0 and multi-instance installation capabilities, there are some things to point out. You will now need to tell KIAUH where your printers configurations are located when installing Klipper for the first time. Even though it is not recommended, you can change this location with the help of KIAUH and rewrite Klipper and Moonraker to use the new location.
* Now with KIAUH v3.0 and multi-instance installation capabilities, there are
some things to point out. You will now need to tell KIAUH where your printers
configurations are located when installing Klipper for the first time. Even
though it is not recommended, you can change this location with the help of
KIAUH and rewrite Klipper and Moonraker to use the new location.
* When setting up a multi-instance system, the folder structure will only change slightly. The goal was to keep it as compatible as possible with the custom distributions like mainsailOS and FluiddPi. This should help converting a single-instance setup of mainsailOS/FluiddPi to a multi-instance setup in no time, but keeping single-instance backwards compatibility if needed at a later point in time.
* When setting up a multi-instance system, the folder structure will only change
slightly. The goal was to keep it as compatible as possible with the custom
distributions like mainsailOS and FluiddPi. This should help converting a
single-instance setup of mainsailOS/FluiddPi to a multi-instance setup in no
time, but keeping single-instance backwards compatibility if needed at a later
point in time.
* The folder structure is as follows when setting up multi-instances:\
Each printer instance will get its own folder within your configuration location. The decision to this specific structure was made to make it as painless and easy as possible to convert to a multi-instance setup.
Here is an example:
Each printer instance will get its own folder within your configuration
location. The decision to this specific structure was made to make it as
painless and easy as possible to convert to a multi-instance setup.
Here is an example:
```shell
/home/<username>
└── klipper_config
@@ -237,12 +429,14 @@ Here is an example:
├── printer.cfg
└── moonraker.conf
```
* Also when setting up multi-instances of each service, the name of each service slightly changes.
Each service gets its corresponding instance added to the service filename.
* Also when setting up multi-instances of each service, the name of each service
slightly changes.
Each service gets its corresponding instance added to the service filename.
**This only applies to multi-instances! Single instance installations with KIAUH will keep their original names!**
**This only applies to multi-instances! Single instance installations with
KIAUH will keep their original names!**
Corresponding to the filetree example from above that would mean:
Corresponding to the filetree example from above that would mean:
```
Klipper services:
--> klipper-1.service
@@ -254,52 +448,102 @@ Each service gets its corresponding instance added to the service filename.
--> moonraker-2.service
--> moonraker-n.service
```
* The same service file rules from above apply to OctoPrint even though only Klipper and Moonraker are shown in this example.
* The same service file rules from above apply to OctoPrint even though only
Klipper and Moonraker are shown in this example.
* You can start, stop and restart all Klipper, Moonraker and OctoPrint instances from the KIAUH main menu. For doing this, just type "stop klipper", "start moonraker", "restart octoprint" and so on.
* You can start, stop and restart all Klipper, Moonraker and OctoPrint instances
from the KIAUH main menu. For doing this, just type "stop klipper", "start
moonraker", "restart octoprint" and so on.
* KIAUH v3.0 relocated its ini-file. It is now a hidden file in the users home-directory calles `.kiauh.ini`. This has the benefit of keeping all values in that file between possible re-installations of KIAUH. Otherwise that file would be lost.
* KIAUH v3.0 relocated its ini-file. It is now a hidden file in the users
home-directory calles `.kiauh.ini`. This has the benefit of keeping all values
in that file between possible re-installations of KIAUH. Otherwise that file
would be lost.
* The option of adding more trusted clients to the moonraker.conf file was dropped. Since you can edit this file right inside of Mainsail or Fluidd, only some basic entries are made which get you running.
* The option of adding more trusted clients to the moonraker.conf file was
dropped. Since you can edit this file right inside of Mainsail or Fluidd, only
some basic entries are made which get you running.
* I bet i have missed mentioning other stuff as well because it took me quite some time to re-write many functions. So i just hope you like the new version 😄
* I bet i have missed mentioning other stuff as well because it took me quite
some time to re-write many functions. So i just hope you like the new version
😄
### 2020-11-28
* KIAUH now supports the installation, update and removal of [KlipperScreen](https://github.com/jordanruthe/KlipperScreen). This feature was was provided by [jordanruthe](https://github.com/jordanruthe)! Thank you!
* KIAUH now supports the installation, update and removal
of [KlipperScreen](https://github.com/jordanruthe/KlipperScreen). This feature
was was provided by [jordanruthe](https://github.com/jordanruthe)! Thank you!
### 2020-11-18
* Some changes to Fluidd caused a little rework on how KIAUH will install/update Fluidd from now on. Please see the [fluidd v1.0.0-rc0 release notes](https://github.com/cadriel/fluidd/releases/tag/v1.0.0-rc.0) for further information about what modifications to the moonraker.conf file exactly had to be done. In a nutshell, KIAUH will now always patch the required entries to the moonraker.conf if not already there.
* Some changes to Fluidd caused a little rework on how KIAUH will install/update
Fluidd from now on. Please see
the [fluidd v1.0.0-rc0 release notes](https://github.com/cadriel/fluidd/releases/tag/v1.0.0-rc.0)
for further information about what modifications to the moonraker.conf file
exactly had to be done. In a nutshell, KIAUH will now always patch the
required entries to the moonraker.conf if not already there.
### 2020-10-30:
* The user can now choose to install Klipper as a systemd service.
* The Shell Command extension and `shell_command.py` got renamed to G-Code Shell Command extension and `gcode_shell_command.py`. In case the [pending PR](https://github.com/KevinOConnor/klipper/pull/2173) will be merged in the future, this was an early attempt to dodge possible incompatibilities. The [G-Code Shell Command docs](gcode_shell_command.md) has been updated accordingly.
* The Shell Command extension and `shell_command.py` got renamed to G-Code Shell
Command extension and `gcode_shell_command.py`. In case
the [pending PR](https://github.com/KevinOConnor/klipper/pull/2173) will be
merged in the future, this was an early attempt to dodge possible
incompatibilities. The [G-Code Shell Command docs](gcode_shell_command.md) has
been updated accordingly.
* The way how KIAUH interacts and writes to the users printer.cfg got changed. Usually KIAUH wrote everything directly into the printer.cfg. The way it will work from now on is, that a new file called `kiauh.cfg` will be created if there is something that needs to be written to the printer.cfg and everything gets written to `kiauh.cfg` instead. The only thing which then gets written to the users printer.cfg is `[include kiauh.cfg]`. This line will be located at the very top of the existing printer.cfg with a little comment as a note. The user can then decide to either keep the `kiauh.cfg` or take its content, places it into the printer.cfg directly and remove the `[include kiauh.cfg]`.
* The way how KIAUH interacts and writes to the users printer.cfg got changed.
Usually KIAUH wrote everything directly into the printer.cfg. The way it will
work from now on is, that a new file called `kiauh.cfg` will be created if
there is something that needs to be written to the printer.cfg and everything
gets written to `kiauh.cfg` instead. The only thing which then gets written to
the users printer.cfg is `[include kiauh.cfg]`. This line will be located at
the very top of the existing printer.cfg with a little comment as a note. The
user can then decide to either keep the `kiauh.cfg` or take its content,
places it into the printer.cfg directly and remove the `[include kiauh.cfg]`.
* The `mainsail_macros.cfg` got renamed to `webui_macros.cfg`. Since Mainsail and Fluidd both use the same kind of pause, cancel and resume macros, a more generic name was chosen for the file containing the example macros one can choose to install when installing those webinterfaces.
* The `mainsail_macros.cfg` got renamed to `webui_macros.cfg`. Since Mainsail
and Fluidd both use the same kind of pause, cancel and resume macros, a more
generic name was chosen for the file containing the example macros one can
choose to install when installing those webinterfaces.
### 2020-10-10:
* Support for changing the Klipper branch to the moonraker-dev branch from @Arksine has been dropped. Support for Moonraker has been merged into Klipper mainline a long time ago.
* Support for changing the Klipper branch to the moonraker-dev branch from
@Arksine has been dropped. Support for Moonraker has been merged into Klipper
mainline a long time ago.
* A new function is available from the main menu. You can now upload your log files to http://paste.c-net.org/ to share them for debugging purposes.
* A new function is available from the main menu. You can now upload your log
files to http://paste.c-net.org/ to share them for debugging purposes.
### 2020-10-06:
* Fluidd, a new Klipper interface got added to the list of available installers. At the same time some installation routines have changed or have seen some rework. Changes were made to the installation of NGINX configurations. A method was introduced to change the listen port of a webinterface configuration if there is already another webinterface listening on the default port (80).
* Fluidd, a new Klipper interface got added to the list of available installers.
At the same time some installation routines have changed or have seen some
rework. Changes were made to the installation of NGINX configurations. A
method was introduced to change the listen port of a webinterface
configuration if there is already another webinterface listening on the
default port (80).
* At the moment, the Moonraker installer no longer asks you whether you want to install a web interface too. For now you therefore have to install them with their respective installers. Please report any bugs or issues you encounter.
* At the moment, the Moonraker installer no longer asks you whether you want to
install a web interface too. For now you therefore have to install them with
their respective installers. Please report any bugs or issues you encounter.
### 2020-09-17:
* The dev-2.0 branch will be abandoned as of today. If you did a checkout to that branch in the past, you have to checkout back to master to receive updates.
* The dev-2.0 branch will be abandoned as of today. If you did a checkout to
that branch in the past, you have to checkout back to master to receive
updates.
### 2020-09-12:
* The old [dwc2-for-klipper](https://github.com/Stephan3/dwc2-for-klipper) won't be supported anymore!\
The is a new, fully rewritten project available: [dwc2-for-klipper-socket](https://github.com/Stephan3/dwc2-for-klipper-socket).\
The installer of this script also got rewritten to make use of that new project. You will not be able to install or remove the old [dwc2-for-klipper](https://github.com/Stephan3/dwc2-for-klipper) with KIAUH anymore if you updated KIAUH to the newest version.
* The old [dwc2-for-klipper](https://github.com/Stephan3/dwc2-for-klipper) won't
be supported anymore!\
The is a new, fully rewritten project
available: [dwc2-for-klipper-socket](https://github.com/Stephan3/dwc2-for-klipper-socket).\
The installer of this script also got rewritten to make use of that new
project. You will not be able to install or remove the
old [dwc2-for-klipper](https://github.com/Stephan3/dwc2-for-klipper) with
KIAUH anymore if you updated KIAUH to the newest version.
+66 -97
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
#=======================================================================#
# Copyright (C) 2020 - 2024 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -15,23 +15,30 @@ clear -x
# make sure we have the correct permissions while running the script
umask 022
### sourcing all additional scripts
KIAUH_SRCDIR="$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")"
for script in "${KIAUH_SRCDIR}/scripts/"*.sh; do . "${script}"; done
for script in "${KIAUH_SRCDIR}/scripts/ui/"*.sh; do . "${script}"; done
# gets the path where this script is located
KIAUH_SRCDIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd)
# colors
white="\033[37m"
cyan="\033[96m"
red="\033[91m"
yellow="\033[93m"
green="\033[92m"
#===================================================#
#=================== UPDATE KIAUH ==================#
#===================================================#
function update_kiauh() {
status_msg "Updating KIAUH ..."
echo "Updating KIAUH ..."
cd "${KIAUH_SRCDIR}"
git reset --hard && git pull
ok_msg "Update complete! Please restart KIAUH."
exit 0
echo "Update complete! Restarting..."
sleep 1
exec "$0" "$@" # restarts the script
}
#===================================================#
@@ -57,121 +64,83 @@ function kiauh_update_avail() {
fi
}
function save_startup_version() {
local launch_version
echo "${1}"
sed -i "/^version_to_launch=/d" "${INI_FILE}"
sed -i '$a'"version_to_launch=${1}" "${INI_FILE}"
}
function kiauh_update_dialog() {
[[ ! $(kiauh_update_avail) == "true" ]] && return
top_border
echo -e "/-------------------------------------------------------\\"
echo -e "|${green} New KIAUH update available! ${white}|"
hr
echo -e "|-------------------------------------------------------|"
echo -e "|${green} View Changelog: https://git.io/JnmlX ${white}|"
blank_line
echo -e "| |"
echo -e "|${yellow} It is recommended to keep KIAUH up to date. Updates ${white}|"
echo -e "|${yellow} usually contain bugfixes, important changes or new ${white}|"
echo -e "|${yellow} features. Please consider updating! ${white}|"
bottom_border
echo -e "\-------------------------------------------------------/"
local yn
read -p "${cyan}###### Do you want to update now? (Y/n):${white} " yn
echo -ne "${cyan}###### Do you want to update now? (Y/n):${white} "
read yn
while true; do
case "${yn}" in
Y|y|Yes|yes|"")
do_action "update_kiauh"
update_kiauh
break;;
N|n|No|no)
break;;
*)
deny_action "kiauh_update_dialog";;
echo -e "${red}Invalid input. Please try again.${white}"
kiauh_update_dialog;;
esac
done
}
function launch_kiauh_v5() {
main_menu
}
function launch_kiauh_v6() {
local entrypoint
if ! command -v python3 &>/dev/null || [[ $(python3 -V | cut -d " " -f2 | cut -d "." -f2) -lt 8 ]]; then
echo "Python 3.8 or higher is not installed!"
echo "Please install Python 3.8 or higher and try again."
function check_euid() {
if [[ ${EUID} -eq 0 ]]; then
echo -e "${red}"
echo -e "/-------------------------------------------------------\\"
echo -e "| !!! THIS SCRIPT MUST NOT RUN AS ROOT !!! |"
echo -e "| |"
echo -e "| It will ask for credentials as needed. |"
echo -e "\-------------------------------------------------------/"
echo -e "${white}"
exit 1
fi
}
entrypoint=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")
export PYTHONPATH="${entrypoint}"
clear -x
python3 "${entrypoint}/kiauh.py"
function check_if_ratos() {
if [[ -n $(which ratos) ]]; then
echo -e "${red}"
echo -e "/-------------------------------------------------------\\"
echo -e "| !!! RatOS 2.1 or greater detected !!! |"
echo -e "| |"
echo -e "| KIAUH does currently not support RatOS. |"
echo -e "| If you have any questions, please ask for help on the |"
echo -e "| RatRig Community Discord: https://discord.gg/ratrig |"
echo -e "\-------------------------------------------------------/"
echo -e "${white}"
exit 1
fi
}
function main() {
read_kiauh_ini "${FUNCNAME[0]}"
local entrypoint
if [[ ${version_to_launch} -eq 5 ]]; then
launch_kiauh_v5
elif [[ ${version_to_launch} -eq 6 ]]; then
launch_kiauh_v6
else
top_border
echo -e "| ${green}KIAUH v6.0.0-alpha1 is available now!${white} |"
hr
echo -e "| View Changelog: ${magenta}https://git.io/JnmlX${white} |"
blank_line
echo -e "| KIAUH v6 was completely rewritten from the ground up. |"
echo -e "| It's based on Python 3.8 and has many improvements. |"
blank_line
echo -e "| ${yellow}NOTE: Version 6 is still in alpha, so bugs may occur!${white} |"
echo -e "| ${yellow}Yet, your feedback and bug reports are very much${white} |"
echo -e "| ${yellow}appreciated and will help finalize the release.${white} |"
hr
echo -e "| Would you like to try out KIAUH v6? |"
echo -e "| 1) Yes |"
echo -e "| 2) No |"
echo -e "| 3) Yes, remember my choice for next time |"
echo -e "| 4) No, remember my choice for next time |"
quit_footer
while true; do
read -p "${cyan}###### Select action:${white} " -e input
case "${input}" in
1)
launch_kiauh_v6
break;;
2)
launch_kiauh_v5
break;;
3)
save_startup_version 6
launch_kiauh_v6
break;;
4)
save_startup_version 5
launch_kiauh_v5
break;;
Q|q)
echo -e "${green}###### Happy printing! ######${white}"; echo
exit 0;;
*)
error_msg "Invalid Input!\n";;
esac
done && input=""
fi
if ! command -v python3 &>/dev/null || [[ $(python3 -V | cut -d " " -f2 | cut -d "." -f2) -lt 8 ]]; then
echo "Python 3.8 or higher is not installed!"
echo "Please install Python 3.8 or higher and try again."
exit 1
fi
entrypoint=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")
export PYTHONPATH="${entrypoint}"
clear -x
python3 "${entrypoint}/kiauh/main.py" "$@"
}
check_if_ratos
check_euid
init_logfile
set_globals
kiauh_update_dialog
read_kiauh_ini
init_ini
main
# skip update prompt when arguments are passed -> dont block cli runs
if [[ $# -eq 0 ]]; then
kiauh_update_dialog
fi
main "$@"
+1 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+3 -3
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -9,7 +9,6 @@
from pathlib import Path
from core.backup_manager import BACKUP_ROOT_DIR
from core.constants import SYSTEMD
# repo
@@ -20,11 +19,12 @@ CROWSNEST_SERVICE_NAME = "crowsnest.service"
# directories
CROWSNEST_DIR = Path.home().joinpath("crowsnest")
CROWSNEST_BACKUP_DIR = BACKUP_ROOT_DIR.joinpath("crowsnest-backups")
CROWSNEST_ENV_DIR = Path.home().joinpath("crowsnest-env")
# files
CROWSNEST_MULTI_CONFIG = CROWSNEST_DIR.joinpath("tools/.config")
CROWSNEST_INSTALL_SCRIPT = CROWSNEST_DIR.joinpath("tools/install.sh")
CROWSNEST_DEPS_JSON_FILE = CROWSNEST_DIR.joinpath("system-dependencies.json")
CROWSNEST_BIN_FILE = Path("/usr/local/bin/crowsnest")
CROWSNEST_LOGROTATE_FILE = Path("/etc/logrotate.d/crowsnest")
CROWSNEST_SERVICE_FILE = SYSTEMD.joinpath(CROWSNEST_SERVICE_NAME)
+76 -17
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -15,9 +15,10 @@ from subprocess import CalledProcessError, run
from typing import List
from components.crowsnest import (
CROWSNEST_BACKUP_DIR,
CROWSNEST_BIN_FILE,
CROWSNEST_DEPS_JSON_FILE,
CROWSNEST_DIR,
CROWSNEST_ENV_DIR,
CROWSNEST_INSTALL_SCRIPT,
CROWSNEST_LOGROTATE_FILE,
CROWSNEST_MULTI_CONFIG,
@@ -26,8 +27,10 @@ from components.crowsnest import (
CROWSNEST_SERVICE_NAME,
)
from components.klipper.klipper import Klipper
from core.backup_manager.backup_manager import BackupManager
from components.moonraker.utils.sysdeps_parser import SysDepsParser
from components.moonraker.utils.utils import load_sysdeps_json
from core.logger import DialogType, Logger
from core.services.backup_service import BackupService
from core.settings.kiauh_settings import KiauhSettings
from core.types.component_status import ComponentStatus
from utils.common import (
@@ -35,6 +38,7 @@ from utils.common import (
get_install_status,
)
from utils.git_utils import (
get_current_branch,
git_clone_wrapper,
git_pull_wrapper,
)
@@ -48,7 +52,7 @@ from utils.sys_utils import (
def install_crowsnest() -> None:
# Step 1: Clone crowsnest repo
git_clone_wrapper(CROWSNEST_REPO, CROWSNEST_DIR, "master")
git_clone_wrapper(CROWSNEST_REPO, CROWSNEST_DIR)
# Step 2: Install dependencies
check_install_dependencies({"make"})
@@ -127,17 +131,16 @@ def update_crowsnest() -> None:
settings = KiauhSettings()
if settings.kiauh.backup_before_update:
bm = BackupManager()
bm.backup_directory(
CROWSNEST_DIR.name,
source=CROWSNEST_DIR,
target=CROWSNEST_BACKUP_DIR,
svc = BackupService()
svc.backup_directory(
source_path=CROWSNEST_DIR,
target_path="crowsnest",
backup_name="crowsnest",
)
git_pull_wrapper(CROWSNEST_DIR)
deps = parse_packages_from_file(CROWSNEST_INSTALL_SCRIPT)
check_install_dependencies({*deps})
install_crowsnest_packages()
cmd_sysctl_service(CROWSNEST_SERVICE_NAME, "restart")
@@ -148,12 +151,68 @@ def update_crowsnest() -> None:
def get_crowsnest_status() -> ComponentStatus:
files = [
CROWSNEST_BIN_FILE,
CROWSNEST_LOGROTATE_FILE,
CROWSNEST_SERVICE_FILE,
]
return get_install_status(CROWSNEST_DIR, files=files)
"""
Get the current install status of Crowsnest. Depending on the version the installed
files are different. If a version is not yet specified, it will search for a
non_existant file resulting in 'Incomplete' status.
:return: Installation status
"""
files_dict = {
4: [
CROWSNEST_BIN_FILE,
CROWSNEST_LOGROTATE_FILE,
CROWSNEST_SERVICE_FILE,
],
5: [CROWSNEST_SERVICE_FILE],
}
version = get_crowsnest_version()
non_existant = CROWSNEST_DIR.joinpath("non_existant")
files = files_dict.get(version, [non_existant])
env_dir = None
if version >= 5:
env_dir = CROWSNEST_ENV_DIR
return get_install_status(CROWSNEST_DIR, files=files, env_dir=env_dir)
def get_crowsnest_version() -> int:
"""
Get the current major version. Starting with v5 the default branch will be named
after the major version.
:return: Current major version
"""
version = get_current_branch(CROWSNEST_DIR)
if version is None:
return 0
if version == "master":
return 4
return int(version.removeprefix("v"))
def install_crowsnest_packages() -> None:
Logger.print_status("Parsing Crowsnest system dependencies ...")
crowsnest_deps = []
crowsnest_version = get_crowsnest_version()
if crowsnest_version >= 5 and CROWSNEST_DEPS_JSON_FILE.exists():
Logger.print_info(
f"Parsing system dependencies from {CROWSNEST_DEPS_JSON_FILE.name} ..."
)
parser = SysDepsParser()
sysdeps = load_sysdeps_json(CROWSNEST_DEPS_JSON_FILE)
crowsnest_deps.extend(parser.parse_dependencies(sysdeps))
elif crowsnest_version <= 4 and CROWSNEST_INSTALL_SCRIPT.exists():
Logger.print_info(
f"Parsing system dependencies from {CROWSNEST_INSTALL_SCRIPT.name} ..."
)
crowsnest_deps = parse_packages_from_file(CROWSNEST_INSTALL_SCRIPT)
if not crowsnest_deps:
raise ValueError("Error parsing crowsnest dependencies!")
check_install_dependencies({*crowsnest_deps})
def remove_crowsnest() -> None:
+1 -4
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -9,8 +9,6 @@
from pathlib import Path
from core.backup_manager import BACKUP_ROOT_DIR
MODULE_PATH = Path(__file__).resolve().parent
KLIPPER_REPO_URL = "https://github.com/Klipper3d/klipper.git"
@@ -27,7 +25,6 @@ KLIPPER_SERVICE_NAME = "klipper.service"
KLIPPER_DIR = Path.home().joinpath("klipper")
KLIPPER_KCONFIGS_DIR = Path.home().joinpath("klipper-kconfigs")
KLIPPER_ENV_DIR = Path.home().joinpath("klippy-env")
KLIPPER_BACKUP_DIR = BACKUP_ROOT_DIR.joinpath("klipper-backups")
# files
KLIPPER_REQ_FILE = KLIPPER_DIR.joinpath("scripts/klippy-requirements.txt")
+1 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+1 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+50 -34
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -16,7 +16,6 @@ from subprocess import CalledProcessError, run
from typing import Dict, List
from components.klipper import (
KLIPPER_BACKUP_DIR,
KLIPPER_DIR,
KLIPPER_ENV_DIR,
KLIPPER_INSTALL_SCRIPT,
@@ -28,14 +27,12 @@ from components.klipper.klipper_dialogs import (
print_select_instance_count_dialog,
)
from components.webui_client.base_data import BaseWebClient
from components.webui_client.client_config.client_config_setup import (
create_client_config_symlink,
)
from core.backup_manager.backup_manager import BackupManager
from components.webui_client.client_utils import create_client_config_symlink
from core.constants import CURRENT_USER
from core.instance_manager.base_instance import SUFFIX_BLACKLIST
from core.logger import DialogType, Logger
from core.submodules.simple_config_parser.src.simple_config_parser.simple_config_parser import (
from core.services.backup_service import BackupService
from core.simple_config_parser.simple_config_parser import (
SimpleConfigParser,
)
from core.types.component_status import ComponentStatus
@@ -89,33 +86,45 @@ def assign_custom_name(key: int, name_dict: Dict[int, str]) -> None:
name_dict[key] = get_string_input(question, exclude=existing_names, regex=pattern)
def check_user_groups() -> None:
def check_user_groups(interactive: bool = True) -> None:
"""Ensure the current user is in the ``tty`` and ``dialout`` groups.
When ``interactive`` is true (the TUI path), the user is shown a dialog and
must confirm before groups are modified. When ``interactive`` is false (the
headless CLI path), groups are added automatically without prompting.
"""
user_groups = [grp.getgrgid(gid).gr_name for gid in os.getgroups()]
missing_groups = [g for g in ["tty", "dialout"] if g not in user_groups]
if not missing_groups:
return
Logger.print_dialog(
DialogType.ATTENTION,
[
"Your current user is not in group:",
*[f"{g}" for g in missing_groups],
"\n\n",
"It is possible that you won't be able to successfully connect and/or "
"flash the controller board without your user being a member of that "
"group. If you want to add the current user to the group(s) listed above, "
"answer with 'Y'. Else skip with 'n'.",
"\n\n",
"INFO:",
"Relog required for group assignments to take effect!",
],
)
if interactive:
Logger.print_dialog(
DialogType.ATTENTION,
[
"Your current user is not in group:",
*[f"{g}" for g in missing_groups],
"\n\n",
"It is possible that you won't be able to successfully connect and/or "
"flash the controller board without your user being a member of that "
"group. If you want to add the current user to the group(s) listed above, "
"answer with 'Y'. Else skip with 'n'.",
"\n\n",
"INFO:",
"Relog required for group assignments to take effect!",
],
)
if not get_confirm(f"Add user '{CURRENT_USER}' to group(s) now?"):
log = "Skipped adding user to required groups. You might encounter issues."
Logger.warn(log)
return
if not get_confirm(f"Add user '{CURRENT_USER}' to group(s) now?"):
log = "Skipped adding user to required groups. You might encounter issues."
Logger.print_warn(log)
return
else:
Logger.print_info(
f"Adding user '{CURRENT_USER}' to required groups: "
f"{', '.join(missing_groups)}"
)
try:
for group in missing_groups:
@@ -127,8 +136,9 @@ def check_user_groups() -> None:
Logger.print_error(f"Unable to add user to usergroups: {e}")
raise
log = "Remember to relog/restart this machine for the group(s) to be applied!"
Logger.print_warn(log)
if interactive:
log = "Remember to relog/restart this machine for the group(s) to be applied!"
Logger.print_warn(log)
def handle_disruptive_system_packages() -> None:
@@ -198,9 +208,17 @@ def create_example_printer_cfg(
def backup_klipper_dir() -> None:
bm = BackupManager()
bm.backup_directory("klipper", source=KLIPPER_DIR, target=KLIPPER_BACKUP_DIR)
bm.backup_directory("klippy-env", source=KLIPPER_ENV_DIR, target=KLIPPER_BACKUP_DIR)
svc = BackupService()
svc.backup_directory(
source_path=KLIPPER_DIR,
backup_name="klipper",
target_path="klipper",
)
svc.backup_directory(
source_path=KLIPPER_ENV_DIR,
backup_name="klippy-env",
target_path="klipper",
)
def install_klipper_packages() -> None:
@@ -230,7 +248,6 @@ def install_input_shaper_deps() -> None:
"If you agree, the following additional system packages will be installed:",
"● python3-numpy",
"● python3-matplotlib",
"● libatlas-base-dev",
"● libopenblas-dev",
"\n\n",
"Also, the following Python package will be installed:",
@@ -246,7 +263,6 @@ def install_input_shaper_deps() -> None:
apt_deps = (
"python3-numpy",
"python3-matplotlib",
"libatlas-base-dev",
"libopenblas-dev",
)
check_install_dependencies({*apt_deps})
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -8,6 +8,7 @@
# ======================================================================= #
from __future__ import annotations
import traceback
from copy import copy
from typing import Dict, List, Tuple
@@ -94,132 +95,234 @@ class KlipperSetupService:
self.msgsvc = MessageService()
def __refresh_state(self) -> None:
def _refresh_state(self) -> None:
self.kisvc.load_instances()
self.klipper_list = self.kisvc.get_all_instances()
self.misvc.load_instances()
self.moonraker_list = self.misvc.get_all_instances()
def install(self) -> None:
self.__refresh_state()
def install(
self,
count: int | None = None,
custom_names: Dict[int, str] | None = None,
create_example_cfg: bool | None = None,
match_moonraker: bool = False,
interactive: bool = True,
) -> bool:
"""Install Klipper.
When called without arguments from the TUI, all choices are prompted
interactively. The CLI passes explicit values and ``interactive=False``.
Returns ``True`` on success and ``False`` when installation cannot proceed.
"""
self._refresh_state()
Logger.print_status("Installing Klipper ...")
match_moonraker: bool = False
name_dict: Dict[int, str] = {}
# if there are more moonraker instances than klipper instances, ask the user to
# match the klipper instance count to the count of moonraker instances with the same suffix
if len(self.moonraker_list) > len(self.klipper_list):
is_confirmed = self.__display_moonraker_info()
if not is_confirmed:
if custom_names is not None:
name_dict = custom_names
elif match_moonraker and len(self.moonraker_list) > len(self.klipper_list):
if interactive:
if not self._display_moonraker_info():
Logger.print_status(EXIT_KLIPPER_SETUP)
return True
name_dict = {
i: moonraker.suffix for i, moonraker in enumerate(self.moonraker_list)
}
elif count is not None:
name_dict = {i: "" for i in range(count)}
elif interactive:
install_count, name_dict = self.__get_install_count_and_name_dict()
if install_count == 0:
Logger.print_status(EXIT_KLIPPER_SETUP)
return
match_moonraker = True
return True
install_count, name_dict = self.__get_install_count_and_name_dict()
is_multi_install = install_count > 1 or (
len(name_dict) >= 1 and install_count >= 1
)
if not name_dict and install_count == 1:
name_dict = {0: ""}
elif is_multi_install and not self.__count_from_moonraker_match(
install_count, name_dict
):
use_custom_names = self.__use_custom_names_or_go_back()
if use_custom_names is None:
Logger.print_status(EXIT_KLIPPER_SETUP)
return True
if install_count == 0:
Logger.print_status(EXIT_KLIPPER_SETUP)
return
is_multi_install = install_count > 1 or (
len(name_dict) >= 1 and install_count >= 1
)
if not name_dict and install_count == 1:
self.__handle_instance_names(install_count, name_dict, use_custom_names)
else:
name_dict = {0: ""}
elif is_multi_install and not match_moonraker:
custom_names = self.__use_custom_names_or_go_back()
if custom_names is None:
Logger.print_status(EXIT_KLIPPER_SETUP)
return
self.__handle_instance_names(install_count, name_dict, custom_names)
if not name_dict:
Logger.print_status(EXIT_KLIPPER_SETUP)
return True
if create_example_cfg is None:
create_example_cfg = (
get_confirm("Create example printer.cfg?") if interactive else False
)
create_example_cfg = get_confirm("Create example printer.cfg?")
# run the actual installation
try:
self.__run_setup(name_dict, create_example_cfg)
except Exception as e:
Logger.print_error(e)
self.__run_setup(name_dict, create_example_cfg, interactive=interactive)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error("Klipper installation failed!")
return
return False
def update(self) -> None:
Logger.print_dialog(
DialogType.WARNING,
[
"Do NOT continue if there are ongoing prints running!",
"All Klipper instances will be restarted during the update process and "
"ongoing prints WILL FAIL.",
],
)
return True
if not get_confirm("Update Klipper now?"):
return
def update(self, interactive: bool = True) -> bool:
"""Update Klipper.
self.__refresh_state()
When called from the TUI, a warning and confirmation are shown. The CLI
passes ``interactive=False`` to run silently.
if self.settings.kiauh.backup_before_update:
backup_klipper_dir()
Returns ``True`` on success and ``False`` if the update could not be completed.
"""
if interactive:
Logger.print_dialog(
DialogType.WARNING,
[
"Do NOT continue if there are ongoing prints running!",
"All Klipper instances will be restarted during the update process and "
"ongoing prints WILL FAIL.",
],
)
InstanceManager.stop_all(self.klipper_list)
git_pull_wrapper(KLIPPER_DIR)
install_klipper_packages()
install_python_requirements(KLIPPER_ENV_DIR, KLIPPER_REQ_FILE)
InstanceManager.start_all(self.klipper_list)
if not get_confirm("Update Klipper now?"):
return False
self._refresh_state()
try:
if self.settings.kiauh.backup_before_update:
backup_klipper_dir()
InstanceManager.stop_all(self.klipper_list)
git_pull_wrapper(KLIPPER_DIR)
install_klipper_packages()
install_python_requirements(KLIPPER_ENV_DIR, KLIPPER_REQ_FILE)
InstanceManager.start_all(self.klipper_list)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error("Error while updating Klipper!")
return False
return True
def remove(
self,
remove_service: bool,
remove_dir: bool,
remove_env: bool,
) -> None:
self.__refresh_state()
*,
remove_all: bool = False,
instance_suffixes: List[str] | None = None,
interactive: bool = True,
) -> bool:
"""Remove Klipper.
completion_msg = Message(
title="Klipper Removal Process completed",
color=Color.GREEN,
)
When called from the TUI, the user selects instances interactively. In
headless mode (``interactive=False``) the caller MUST express explicit
intent: pass ``remove_all=True`` to wipe every instance or
``instance_suffixes=[...]`` to remove a named subset. Without explicit
intent the service refuses and removes nothing so a CLI user can never
accidentally destroy every Klipper instance on the machine.
if remove_service:
Logger.print_status("Removing Klipper instances ...")
if self.klipper_list:
instances_to_remove = self.__get_instances_to_remove()
self.__remove_instances(instances_to_remove)
if instances_to_remove:
instance_names = [
i.service_file_path.stem for i in instances_to_remove
Returns ``True`` on success and ``False`` if removal could not be completed.
"""
self._refresh_state()
try:
if interactive:
completion_msg = Message(
title="Klipper Removal Process completed",
color=Color.GREEN,
)
if remove_service:
Logger.print_status("Removing Klipper instances ...")
if self.klipper_list:
instances_to_remove = self._get_instances_to_remove()
self.__remove_instances(instances_to_remove)
if instances_to_remove:
instance_names = [
i.service_file_path.stem for i in instances_to_remove
]
txt = f"● Klipper instances removed: {', '.join(instance_names)}"
completion_msg.text.append(txt)
else:
Logger.print_info("No Klipper Services installed! Skipped ...")
if (remove_dir or remove_env) and unit_file_exists(
"klipper", suffix="service"
):
completion_msg.text = [
"Some Klipper services are still installed:",
f"'{KLIPPER_DIR}' was not removed, even though selected for removal.",
f"'{KLIPPER_ENV_DIR}' was not removed, even though selected for removal.",
]
txt = f"● Klipper instances removed: {', '.join(instance_names)}"
completion_msg.text.append(txt)
else:
if remove_dir:
Logger.print_status("Removing Klipper local repository ...")
if run_remove_routines(KLIPPER_DIR):
completion_msg.text.append(
"● Klipper local repository removed"
)
if remove_env:
Logger.print_status("Removing Klipper Python environment ...")
if run_remove_routines(KLIPPER_ENV_DIR):
completion_msg.text.append(
"● Klipper Python environment removed"
)
if completion_msg.text:
completion_msg.text.insert(
0, "The following actions were performed:"
)
else:
completion_msg.color = Color.YELLOW
completion_msg.centered = True
completion_msg.text = ["Nothing to remove."]
self.msgsvc.set_message(completion_msg)
else:
Logger.print_info("No Klipper Services installed! Skipped ...")
if remove_service and self.klipper_list:
selected = self._select_instances_for_headless_removal(
remove_all, instance_suffixes
)
if selected is None:
Logger.print_error(
"Refusing to remove Klipper instances: no explicit "
"intent. Pass remove_all=True or instance_suffixes."
)
return False
self.__remove_instances(selected)
if (remove_dir or remove_env) and unit_file_exists("klipper", suffix="service"):
completion_msg.text = [
"Some Klipper services are still installed:",
f"'{KLIPPER_DIR}' was not removed, even though selected for removal.",
f"'{KLIPPER_ENV_DIR}' was not removed, even though selected for removal.",
]
else:
if remove_dir:
Logger.print_status("Removing Klipper local repository ...")
if run_remove_routines(KLIPPER_DIR):
completion_msg.text.append("● Klipper local repository removed")
if remove_env:
Logger.print_status("Removing Klipper Python environment ...")
if run_remove_routines(KLIPPER_ENV_DIR):
completion_msg.text.append("● Klipper Python environment removed")
if (remove_dir or remove_env) and unit_file_exists(
"klipper", suffix="service"
):
Logger.print_info(
"Klipper services still installed; skipping repository/env removal."
)
return True
if completion_msg.text:
completion_msg.text.insert(0, "The following actions were performed:")
else:
completion_msg.color = Color.YELLOW
completion_msg.centered = True
completion_msg.text = ["Nothing to remove."]
if remove_dir:
run_remove_routines(KLIPPER_DIR)
if remove_env:
run_remove_routines(KLIPPER_ENV_DIR)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error("Error while removing Klipper!")
return False
self.msgsvc.set_message(completion_msg)
return True
def __get_install_count_and_name_dict(self) -> Tuple[int, Dict[int, str]]:
install_count: int | None
@@ -240,9 +343,16 @@ class KlipperSetupService:
return install_count, name_dict
def __run_setup(self, name_dict: Dict[int, str], create_example_cfg: bool) -> None:
def __run_setup(
self,
name_dict: Dict[int, str],
create_example_cfg: bool,
interactive: bool = True,
) -> None:
if not self.klipper_list:
self.__install_deps()
# Only create a fresh venv when none exists; existing venvs are
# preserved in both TUI and CLI modes.
self.__install_deps(interactive=interactive)
for i in name_dict:
# skip this iteration if there is already an instance with the name
@@ -266,9 +376,9 @@ class KlipperSetupService:
handle_disruptive_system_packages()
# step 5: check for required group membership
check_user_groups()
check_user_groups(interactive=interactive)
def __install_deps(self) -> None:
def __install_deps(self, interactive: bool = True) -> None:
default_repo = (KLIPPER_REPO_URL, "master")
repo = self.settings.klipper.repositories
# pull the first repo defined in kiauh.cfg or fallback to the official Klipper repo
@@ -277,13 +387,19 @@ class KlipperSetupService:
try:
install_klipper_packages()
if create_python_venv(KLIPPER_ENV_DIR, False, False, self.settings.klipper.use_python_binary):
if create_python_venv(
KLIPPER_ENV_DIR,
force=False,
allow_access_to_system_site_packages=False,
use_python_binary=self.settings.klipper.use_python_binary,
interactive=interactive,
):
install_python_requirements(KLIPPER_ENV_DIR, KLIPPER_REQ_FILE)
except Exception:
Logger.print_error("Error during installation of Klipper requirements!")
raise
def __display_moonraker_info(self) -> bool:
def _display_moonraker_info(self) -> bool:
# todo: only show the klipper instances that are not already installed
Logger.print_dialog(
DialogType.INFO,
@@ -308,6 +424,17 @@ class KlipperSetupService:
else:
name_dict[key] = str(len(name_dict) + 1)
def __count_from_moonraker_match(
self, install_count: int, name_dict: Dict[int, str]
) -> bool:
"""Return True when the count/names came from matching Moonraker instances."""
if len(self.moonraker_list) <= len(self.klipper_list):
return False
if install_count != len(self.moonraker_list):
return False
expected = [m.suffix for m in self.moonraker_list]
return list(name_dict.values()) == expected
def __use_custom_names_or_go_back(self) -> bool | None:
print_select_custom_name_dialog()
_input: bool | None = get_confirm(
@@ -317,7 +444,7 @@ class KlipperSetupService:
)
return _input
def __get_instances_to_remove(self) -> List[Klipper] | None:
def _get_instances_to_remove(self) -> List[Klipper] | None:
start_index = 1
curr_instances: List[Klipper] = self.klipper_list
instance_count = len(curr_instances)
@@ -341,6 +468,26 @@ class KlipperSetupService:
return [instance_map[selection]]
def _select_instances_for_headless_removal(
self,
remove_all: bool,
instance_suffixes: List[str] | None,
) -> List[Klipper] | None:
"""Resolve which instances to remove in headless mode.
Returns the list of instances to remove, or ``None`` when the caller did
not express explicit intent (no ``remove_all`` and no ``instance_suffixes``).
A ``None`` return is the "refuse to wipe everything" signal the CLI path
relies on. Kept as a single-public-seam helper (no name mangling) so
tests can patch it without brittle ``_Class__method`` access.
"""
if remove_all:
return list(self.klipper_list)
if instance_suffixes:
wanted = set(instance_suffixes)
return [i for i in self.klipper_list if i.suffix in wanted]
return None
def __remove_instances(
self,
instance_list: List[Klipper] | None,
@@ -353,11 +500,11 @@ class KlipperSetupService:
f"Removing instance {instance.service_file_path.stem} ..."
)
InstanceManager.remove(instance)
self.__delete_klipper_env_file(instance)
self._delete_klipper_env_file(instance)
self.__refresh_state()
self._refresh_state()
def __delete_klipper_env_file(self, instance: Klipper):
def _delete_klipper_env_file(self, instance: Klipper):
Logger.print_status(f"Remove '{instance.env_file}'")
if not instance.env_file.exists():
msg = f"Env file in {instance.base.sysd_dir} not found. Skipped ..."
@@ -0,0 +1,445 @@
from __future__ import annotations
from typing import Any, Dict, List
import pytest
from components.klipper.services.klipper_setup_service import KlipperSetupService
@pytest.fixture
def reset_service(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(KlipperSetupService, "_KlipperSetupService__cls_instance", None)
class FakeKlipper:
def __init__(self, suffix: str = "") -> None:
self.suffix = suffix
self.create_calls: List[Any] = []
def create(self) -> None:
self.create_calls.append(True)
@pytest.fixture
def patched_install_deps(
monkeypatch: pytest.MonkeyPatch, reset_service
) -> Dict[str, List[Any]]:
calls: Dict[str, List[Any]] = {
"klipper_create": [],
"enable": [],
"start": [],
}
module = "components.klipper.services.klipper_setup_service"
def fake_klipper(suffix: str = "") -> FakeKlipper:
instance = FakeKlipper(suffix)
calls["klipper_create"].append(instance)
return instance
monkeypatch.setattr(f"{module}.Klipper", fake_klipper)
monkeypatch.setattr(
f"{module}.InstanceManager.enable",
staticmethod(lambda instance: calls["enable"].append(instance.suffix)),
)
monkeypatch.setattr(
f"{module}.InstanceManager.start",
staticmethod(lambda instance: calls["start"].append(instance.suffix)),
)
monkeypatch.setattr(f"{module}.git_clone_wrapper", lambda *a, **k: None)
monkeypatch.setattr(f"{module}.install_klipper_packages", lambda: None)
monkeypatch.setattr(f"{module}.create_python_venv", lambda *a, **k: True)
monkeypatch.setattr(f"{module}.install_python_requirements", lambda *a, **k: None)
monkeypatch.setattr(f"{module}.handle_disruptive_system_packages", lambda: None)
monkeypatch.setattr(f"{module}.check_user_groups", lambda interactive=True: None)
monkeypatch.setattr(f"{module}.cmd_sysctl_manage", lambda *a, **k: None)
return calls
class TestKlipperInstallHeadless:
def test_installs_single_instance_by_default(
self, patched_install_deps, monkeypatch
) -> None:
service = KlipperSetupService()
service.install(interactive=False)
assert len(patched_install_deps["klipper_create"]) == 1
assert patched_install_deps["enable"] == [""]
assert patched_install_deps["start"] == [""]
def test_installs_multiple_instances_by_count(
self, patched_install_deps, monkeypatch
) -> None:
service = KlipperSetupService()
service.install(count=2, interactive=False)
assert len(patched_install_deps["klipper_create"]) == 2
assert patched_install_deps["enable"] == ["", ""]
assert patched_install_deps["start"] == ["", ""]
def test_installs_with_custom_names(
self, patched_install_deps, monkeypatch
) -> None:
service = KlipperSetupService()
service.install(custom_names={0: "a", 1: "b"}, interactive=False)
assert len(patched_install_deps["klipper_create"]) == 2
instances = patched_install_deps["klipper_create"]
assert instances[0].suffix == "a"
assert instances[1].suffix == "b"
class TestKlipperRemoveHeadless:
def _make_fake_instance(self, suffix: str = ""):
Path = __import__("pathlib").Path
return type(
"FakeInstance",
(),
{
"suffix": suffix,
"service_file_path": Path(f"klipper-{suffix}.service"),
"env_file": Path("/tmp/klipper.env"),
"base": type("Base", (), {"sysd_dir": Path("/tmp")})(),
},
)()
def _patch_remove_internals(self, monkeypatch, removed):
module = "components.klipper.services.klipper_setup_service"
monkeypatch.setattr(
f"{module}.KlipperSetupService._refresh_state",
lambda self: None,
)
monkeypatch.setattr(
f"{module}.InstanceManager.remove",
staticmethod(lambda instance: removed["instances"].append(instance.suffix)),
)
monkeypatch.setattr(f"{module}.unit_file_exists", lambda *a, **k: False)
monkeypatch.setattr(
f"{module}.run_remove_routines",
lambda path: removed["paths"].append(str(path)) or True,
)
def test_removes_explicit_all_services_and_files(
self, reset_service, monkeypatch
) -> None:
removed: Dict[str, List[Any]] = {"instances": [], "paths": []}
self._patch_remove_internals(monkeypatch, removed)
fake_instance = self._make_fake_instance("")
service = KlipperSetupService()
service.klipper_list = [fake_instance]
service.remove(
remove_service=True,
remove_dir=True,
remove_env=True,
remove_all=True,
interactive=False,
)
assert removed["instances"] == [""]
assert any("klipper" in p for p in removed["paths"])
def test_without_explicit_intent_removes_nothing(
self, reset_service, monkeypatch
) -> None:
# non-interactive remove with no --all and no --instance must
# NOT call InstanceManager.remove or run_remove_routines and must
# refuse with a non-zero (False) result.
removed: Dict[str, List[Any]] = {"instances": [], "paths": []}
self._patch_remove_internals(monkeypatch, removed)
fake_instance = self._make_fake_instance("a")
service = KlipperSetupService()
service.klipper_list = [fake_instance]
result = service.remove(
remove_service=True,
remove_dir=False,
remove_env=False,
interactive=False,
)
assert result is False
assert removed["instances"] == []
assert removed["paths"] == []
def test_with_instance_suffix_removes_only_matching(
self, reset_service, monkeypatch
) -> None:
removed: Dict[str, List[Any]] = {"instances": [], "paths": []}
self._patch_remove_internals(monkeypatch, removed)
service = KlipperSetupService()
service.klipper_list = [
self._make_fake_instance("a"),
self._make_fake_instance("b"),
]
service.remove(
remove_service=True,
remove_dir=False,
remove_env=False,
instance_suffixes=["a"],
interactive=False,
)
assert removed["instances"] == ["a"]
class TestKlipperUpdateHeadless:
def test_update_runs_expected_steps(self, reset_service, monkeypatch) -> None:
module = "components.klipper.services.klipper_setup_service"
calls: List[str] = []
monkeypatch.setattr(
f"{module}.backup_klipper_dir", lambda: calls.append("backup")
)
monkeypatch.setattr(
f"{module}.InstanceManager.stop_all",
staticmethod(lambda instances: calls.append("stop")),
)
monkeypatch.setattr(
f"{module}.git_pull_wrapper", lambda *a, **k: calls.append("pull")
)
monkeypatch.setattr(
f"{module}.install_klipper_packages", lambda: calls.append("packages")
)
monkeypatch.setattr(
f"{module}.install_python_requirements",
lambda *a, **k: calls.append("requirements"),
)
monkeypatch.setattr(
f"{module}.InstanceManager.start_all",
staticmethod(lambda instances: calls.append("start")),
)
service = KlipperSetupService()
service.settings.kiauh.backup_before_update = True
result = service.update(interactive=False)
assert result is True
assert calls == ["backup", "stop", "pull", "packages", "requirements", "start"]
def test_update_cancelled_by_user_returns_false(
self, reset_service, monkeypatch
) -> None:
module = "components.klipper.services.klipper_setup_service"
pulled: List[str] = []
monkeypatch.setattr(
f"{module}.git_pull_wrapper", lambda *a, **k: pulled.append("pull")
)
monkeypatch.setattr(f"{module}.get_confirm", lambda *a, **k: False)
service = KlipperSetupService()
result = service.update(interactive=True)
assert result is False
assert pulled == []
class FakeMoonraker:
def __init__(self, suffix: str = "") -> None:
self.suffix = suffix
class TestKlipperInteractiveMoonrakerMatch:
def test_installs_exactly_one_klipper_per_moonraker(
self, reset_service, patched_install_deps, monkeypatch
) -> None:
module = "components.klipper.services.klipper_setup_service"
monkeypatch.setattr(
f"{module}.KlipperSetupService._refresh_state",
lambda self: None,
)
monkeypatch.setattr(
f"{module}.KlipperSetupService._display_moonraker_info",
lambda self: True,
)
monkeypatch.setattr(f"{module}.get_confirm", lambda *a, **k: True)
service = KlipperSetupService()
service.klipper_list = []
service.moonraker_list = [FakeMoonraker(""), FakeMoonraker("b")]
result = service.install(interactive=True, create_example_cfg=False)
assert result is True
assert len(patched_install_deps["klipper_create"]) == 2
instances = patched_install_deps["klipper_create"]
assert instances[0].suffix == ""
assert instances[1].suffix == "b"
def test_headless_match_moonraker_skips_dialog(
self, reset_service, patched_install_deps, monkeypatch
) -> None:
module = "components.klipper.services.klipper_setup_service"
monkeypatch.setattr(
f"{module}.KlipperSetupService._refresh_state",
lambda self: None,
)
dialog_calls: List[Any] = []
monkeypatch.setattr(
f"{module}.KlipperSetupService._display_moonraker_info",
lambda self: dialog_calls.append(True) or False,
)
service = KlipperSetupService()
service.klipper_list = []
service.moonraker_list = [FakeMoonraker("a"), FakeMoonraker("b")]
result = service.install(match_moonraker=True, interactive=False)
assert result is True
assert dialog_calls == []
assert len(patched_install_deps["klipper_create"]) == 2
instances = patched_install_deps["klipper_create"]
assert [i.suffix for i in instances] == ["a", "b"]
class TestKlipperVenvNonDestructive:
"""a headless install must not force-recreate an existing Klipper
venv. ``__install_deps`` must pass ``force=False`` and ``interactive=False``
to ``create_python_venv`` so an existing venv is left untouched (no prompt,
no ``rmtree``)."""
def test_headless_install_does_not_force_recreate_venv(
self, reset_service, monkeypatch
) -> None:
module = "components.klipper.services.klipper_setup_service"
monkeypatch.setattr(
f"{module}.KlipperSetupService._refresh_state",
lambda self: None,
)
venv_calls: List[Any] = []
monkeypatch.setattr(
f"{module}.create_python_venv",
lambda *a, **k: venv_calls.append(k) or True,
)
monkeypatch.setattr(f"{module}.git_clone_wrapper", lambda *a, **k: None)
monkeypatch.setattr(f"{module}.install_klipper_packages", lambda: None)
monkeypatch.setattr(
f"{module}.install_python_requirements", lambda *a, **k: None
)
service = KlipperSetupService()
service.klipper_list = []
service.install(interactive=False)
assert venv_calls, "create_python_venv should have been called"
assert venv_calls[0]["force"] is False
assert venv_calls[0]["interactive"] is False
class TestCheckUserGroups:
def test_interactive_mode_prompts_before_adding_user(self, monkeypatch) -> None:
from components.klipper.klipper_utils import check_user_groups
monkeypatch.setattr("os.getgroups", lambda: [])
monkeypatch.setattr(
"grp.getgrgid",
lambda gid: type("Group", (), {"gr_name": "tty"})(),
)
prompted: List[str] = []
monkeypatch.setattr(
"components.klipper.klipper_utils.get_confirm",
lambda question, *a, **k: prompted.append(question) or True,
)
run_calls: List[List[str]] = []
monkeypatch.setattr(
"components.klipper.klipper_utils.run",
lambda cmd, **kwargs: (
run_calls.append(cmd) or type("R", (), {"returncode": 0})()
),
)
check_user_groups(interactive=True)
assert any("group" in q.lower() for q in prompted)
assert run_calls
def test_headless_mode_auto_adds_without_prompt(self, monkeypatch) -> None:
from components.klipper.klipper_utils import check_user_groups
monkeypatch.setattr("os.getgroups", lambda: [])
monkeypatch.setattr(
"grp.getgrgid",
lambda gid: type("Group", (), {"gr_name": "tty"})(),
)
monkeypatch.setattr(
"components.klipper.klipper_utils.get_confirm",
lambda *a, **k: pytest.fail("should not prompt in headless mode"),
)
run_calls: List[List[str]] = []
monkeypatch.setattr(
"components.klipper.klipper_utils.run",
lambda cmd, **kwargs: (
run_calls.append(cmd) or type("R", (), {"returncode": 0})()
),
)
check_user_groups(interactive=False)
assert run_calls
class TestKlipperRemoveInteractiveTui:
"""Exercise the interactive (TUI) remove branch so the message-assembly
path stays covered: the TUI path must remain unchanged."""
def _make_fake_instance(self, suffix: str = ""):
Path = __import__("pathlib").Path
return type(
"FakeInstance",
(),
{
"suffix": suffix,
"service_file_path": Path(f"klipper-{suffix}.service"),
"env_file": Path("/tmp/klipper.env"),
"base": type("Base", (), {"sysd_dir": Path("/tmp")})(),
},
)()
def test_interactive_remove_sets_completion_message(
self, reset_service, monkeypatch
) -> None:
module = "components.klipper.services.klipper_setup_service"
fake_instance = self._make_fake_instance("a")
removed: Dict[str, List[Any]] = {"instances": [], "paths": []}
monkeypatch.setattr(
f"{module}.KlipperSetupService._refresh_state",
lambda self: None,
)
monkeypatch.setattr(
f"{module}.KlipperSetupService._get_instances_to_remove",
lambda self: [fake_instance],
)
monkeypatch.setattr(
f"{module}.InstanceManager.remove",
staticmethod(lambda instance: removed["instances"].append(instance)),
)
monkeypatch.setattr(
f"{module}.KlipperSetupService._delete_klipper_env_file",
lambda self, inst: None,
)
monkeypatch.setattr(f"{module}.unit_file_exists", lambda *a, **k: False)
monkeypatch.setattr(
f"{module}.run_remove_routines",
lambda path: removed["paths"].append(str(path)) or True,
)
set_messages: List[Any] = []
monkeypatch.setattr(
f"{module}.MessageService",
lambda: type(
"MS", (), {"set_message": lambda self, m: set_messages.append(m)}
)(),
)
service = KlipperSetupService()
service.klipper_list = [fake_instance]
result = service.remove(
remove_service=True, remove_dir=True, remove_env=True, interactive=True
)
assert result is True
assert removed["instances"] == [fake_instance]
assert set_messages, "TUI remove must set the completion message"
assert any("klipper-a" in line for line in set_messages[0].text)
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -236,9 +236,11 @@ class KlipperSelectMcuConnectionMenu(BaseMenu):
if len(self.flash_options.mcu_list) < 1:
Logger.print_warn("No MCUs found!")
Logger.print_warn("Make sure they are connected and repeat this step.")
time.sleep(3)
return
# if standalone is True, we only display the MCUs to the user and return
if self.__standalone and len(self.flash_options.mcu_list) > 0:
if self.__standalone:
Logger.print_ok("The following MCUs were found:", prefix=False)
for i, mcu in enumerate(self.flash_options.mcu_list):
print(f" ● MCU #{i}: {Color.CYAN}{mcu}{Color.RST}")
+1 -3
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -8,7 +8,6 @@
# ======================================================================= #
from pathlib import Path
from core.backup_manager import BACKUP_ROOT_DIR
from core.constants import SYSTEMD
# repo
@@ -22,7 +21,6 @@ KLIPPERSCREEN_LOG_NAME = "KlipperScreen.log"
# directories
KLIPPERSCREEN_DIR = Path.home().joinpath("KlipperScreen")
KLIPPERSCREEN_ENV_DIR = Path.home().joinpath(".KlipperScreen-env")
KLIPPERSCREEN_BACKUP_DIR = BACKUP_ROOT_DIR.joinpath("klipperscreen-backups")
# files
KLIPPERSCREEN_REQ_FILE = KLIPPERSCREEN_DIR.joinpath(
+13 -12
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -13,7 +13,6 @@ from typing import List
from components.klipper.klipper import Klipper
from components.klipperscreen import (
KLIPPERSCREEN_BACKUP_DIR,
KLIPPERSCREEN_DIR,
KLIPPERSCREEN_ENV_DIR,
KLIPPERSCREEN_INSTALL_SCRIPT,
@@ -25,10 +24,10 @@ from components.klipperscreen import (
KLIPPERSCREEN_UPDATER_SECTION_NAME,
)
from components.moonraker.moonraker import Moonraker
from core.backup_manager.backup_manager import BackupManager
from core.constants import SYSTEMD
from core.instance_manager.instance_manager import InstanceManager
from core.logger import DialogType, Logger
from core.services.backup_service import BackupService
from core.settings.kiauh_settings import KiauhSettings
from core.types.component_status import ComponentStatus
from utils.common import (
@@ -97,6 +96,7 @@ def install_klipperscreen() -> None:
def patch_klipperscreen_update_manager(instances: List[Moonraker]) -> None:
BackupService().backup_moonraker_conf()
add_config_section(
section=KLIPPERSCREEN_UPDATER_SECTION_NAME,
instances=instances,
@@ -183,6 +183,7 @@ def remove_klipperscreen() -> None:
mr_instances: List[Moonraker] = get_instances(Moonraker)
if mr_instances:
Logger.print_status("Removing KlipperScreen from update manager ...")
BackupService().backup_moonraker_conf()
remove_config_section("update_manager KlipperScreen", mr_instances)
Logger.print_ok("KlipperScreen successfully removed from update manager!")
@@ -193,14 +194,14 @@ def remove_klipperscreen() -> None:
def backup_klipperscreen_dir() -> None:
bm = BackupManager()
bm.backup_directory(
KLIPPERSCREEN_DIR.name,
source=KLIPPERSCREEN_DIR,
target=KLIPPERSCREEN_BACKUP_DIR,
svc = BackupService()
svc.backup_directory(
source_path=KLIPPERSCREEN_DIR,
backup_name="KlipperScreen",
target_path="KlipperScreen",
)
bm.backup_directory(
KLIPPERSCREEN_ENV_DIR.name,
source=KLIPPERSCREEN_ENV_DIR,
target=KLIPPERSCREEN_BACKUP_DIR,
svc.backup_directory(
source_path=KLIPPERSCREEN_ENV_DIR,
backup_name="KlipperScreen-env",
target_path="KlipperScreen",
)
+1 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+1 -5
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -9,8 +9,6 @@
from pathlib import Path
from core.backup_manager import BACKUP_ROOT_DIR
MODULE_PATH = Path(__file__).resolve().parent
MOONRAKER_REPO_URL = "https://github.com/Arksine/moonraker.git"
@@ -25,8 +23,6 @@ MOONRAKER_ENV_FILE_NAME = "moonraker.env"
# directories
MOONRAKER_DIR = Path.home().joinpath("moonraker")
MOONRAKER_ENV_DIR = Path.home().joinpath("moonraker-env")
MOONRAKER_BACKUP_DIR = BACKUP_ROOT_DIR.joinpath("moonraker-backups")
MOONRAKER_DB_BACKUP_DIR = BACKUP_ROOT_DIR.joinpath("moonraker-db-backups")
# files
MOONRAKER_INSTALL_SCRIPT = MOONRAKER_DIR.joinpath("scripts/install-moonraker.sh")
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+2 -2
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -25,7 +25,7 @@ from components.moonraker import (
from core.constants import CURRENT_USER
from core.instance_manager.base_instance import BaseInstance
from core.logger import Logger
from core.submodules.simple_config_parser.src.simple_config_parser.simple_config_parser import (
from core.simple_config_parser.simple_config_parser import (
SimpleConfigParser,
)
from utils.fs_utils import create_folders
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -8,8 +8,9 @@
# ======================================================================= #
from __future__ import annotations
import traceback
from copy import copy
from subprocess import DEVNULL, PIPE, CalledProcessError, run
from subprocess import DEVNULL, PIPE, run
from typing import List
from components.klipper.klipper import Klipper
@@ -104,87 +105,128 @@ class MoonrakerSetupService:
self.msgsvc = MessageService()
def __refresh_state(self) -> None:
def _refresh_state(self) -> None:
self.kisvc.load_instances()
self.klipper_list = self.kisvc.get_all_instances()
self.misvc.load_instances()
self.moonraker_list = self.misvc.get_all_instances()
def install(self) -> None:
self.__refresh_state()
def install(
self,
klipper_suffixes: List[str] | None = None,
create_example_cfg: bool | None = None,
interactive: bool = True,
) -> bool:
"""Install Moonraker.
if not self.__check_requirements(self.klipper_list):
return
When called from the TUI, the Klipper instance is selected interactively.
The CLI passes explicit suffixes and ``interactive=False``.
Returns ``True`` on success and ``False`` when installation cannot proceed.
"""
self._refresh_state()
if not self._check_requirements(self.klipper_list):
return False
new_instances: List[Moonraker] = []
selected_option: str | Klipper
if len(self.klipper_list) == 1:
suffix: str = self.klipper_list[0].suffix
new_inst = self.misvc.create_new_instance(suffix)
new_instances.append(new_inst)
if klipper_suffixes is not None:
for suffix in klipper_suffixes:
new_instances.append(self.misvc.create_new_instance(suffix))
elif interactive:
selected_option: str | Klipper
else:
print_moonraker_overview(
self.klipper_list,
self.moonraker_list,
show_index=True,
show_select_all=True,
)
options = {str(i + 1): k for i, k in enumerate(self.klipper_list)}
additional_options = {"a": None, "b": None}
options = {**options, **additional_options}
question = "Select Klipper instance to setup Moonraker for"
selected_option = get_selection_input(question, options)
if selected_option == "b":
Logger.print_status(EXIT_MOONRAKER_SETUP)
return
if selected_option == "a":
new_inst_list: List[Moonraker] = [
self.misvc.create_new_instance(k.suffix) for k in self.klipper_list
]
new_instances.extend(new_inst_list)
if len(self.klipper_list) == 1:
selected_suffix: str = self.klipper_list[0].suffix
new_instances.append(self.misvc.create_new_instance(selected_suffix))
else:
klipper_instance: Klipper | None = options.get(selected_option)
if klipper_instance is None:
raise Exception("Error selecting instance!")
new_inst = self.misvc.create_new_instance(klipper_instance.suffix)
new_instances.append(new_inst)
print_moonraker_overview(
self.klipper_list,
self.moonraker_list,
show_index=True,
show_select_all=True,
)
options = {str(i + 1): k for i, k in enumerate(self.klipper_list)}
additional_options = {"a": None, "b": None}
options = {**options, **additional_options}
question = "Select Klipper instance to setup Moonraker for"
selected_option = get_selection_input(question, options)
create_example_cfg = get_confirm("Create example moonraker.conf?")
if selected_option == "b":
Logger.print_status(EXIT_MOONRAKER_SETUP)
return True
if selected_option == "a":
new_inst_list: List[Moonraker] = [
self.misvc.create_new_instance(k.suffix)
for k in self.klipper_list
]
new_instances.extend(new_inst_list)
else:
klipper_instance: Klipper | None = options.get(selected_option)
if klipper_instance is None:
raise Exception("Error selecting instance!")
new_instances.append(
self.misvc.create_new_instance(klipper_instance.suffix)
)
else:
for k in self.klipper_list:
new_instances.append(self.misvc.create_new_instance(k.suffix))
if create_example_cfg is None:
create_example_cfg = (
get_confirm("Create example moonraker.conf?") if interactive else False
)
try:
self.__run_setup(new_instances, create_example_cfg)
except Exception as e:
Logger.print_error(f"Error while installing Moonraker: {e}")
return
self._run_setup(new_instances, create_example_cfg, interactive=interactive)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error("Error while installing Moonraker!")
return False
def update(self) -> None:
Logger.print_dialog(
DialogType.WARNING,
[
"Be careful if there are ongoing prints running!",
"All Moonraker instances will be restarted during the update process and "
"ongoing prints COULD FAIL.",
],
)
return True
if not get_confirm("Update Moonraker now?"):
return
def update(self, interactive: bool = True) -> bool:
"""Update Moonraker.
self.__refresh_state()
When called from the TUI, a warning and confirmation are shown. The CLI
passes ``interactive=False`` to run silently.
if self.settings.kiauh.backup_before_update:
backup_moonraker_dir()
Returns ``True`` on success and ``False`` if the update could not be completed.
"""
if interactive:
Logger.print_dialog(
DialogType.WARNING,
[
"Be careful if there are ongoing prints running!",
"All Moonraker instances will be restarted during the update process and "
"ongoing prints COULD FAIL.",
],
)
InstanceManager.stop_all(self.moonraker_list)
git_pull_wrapper(MOONRAKER_DIR)
install_moonraker_packages()
install_python_requirements(MOONRAKER_ENV_DIR, MOONRAKER_REQ_FILE)
InstanceManager.start_all(self.moonraker_list)
if not get_confirm("Update Moonraker now?"):
return False
self._refresh_state()
try:
if self.settings.kiauh.backup_before_update:
backup_moonraker_dir()
InstanceManager.stop_all(self.moonraker_list)
git_pull_wrapper(MOONRAKER_DIR)
install_moonraker_packages()
install_python_requirements(MOONRAKER_ENV_DIR, MOONRAKER_REQ_FILE)
InstanceManager.start_all(self.moonraker_list)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error("Error while updating Moonraker!")
return False
return True
def remove(
self,
@@ -192,65 +234,132 @@ class MoonrakerSetupService:
remove_dir: bool,
remove_env: bool,
remove_polkit: bool,
) -> None:
self.__refresh_state()
*,
remove_all: bool = False,
instance_suffixes: List[str] | None = None,
interactive: bool = True,
) -> bool:
"""Remove Moonraker.
completion_msg = Message(
title="Moonraker Removal Process completed",
color=Color.GREEN,
)
When called from the TUI, the user selects instances interactively. In
headless mode (``interactive=False``) the caller MUST express explicit
intent: pass ``remove_all=True`` to wipe every instance or
``instance_suffixes=[...]`` to remove a named subset. Without explicit
intent the service refuses and removes nothing, so a CLI user can never
accidentally destroy every Moonraker instance.
if remove_service:
Logger.print_status("Removing Moonraker instances ...")
if self.moonraker_list:
instances_to_remove = self.__get_instances_to_remove()
self.__remove_instances(instances_to_remove)
if instances_to_remove:
instance_names = [
i.service_file_path.stem for i in instances_to_remove
Returns ``True`` on success and ``False`` if removal could not be completed.
"""
self._refresh_state()
try:
if interactive:
completion_msg = Message(
title="Moonraker Removal Process completed",
color=Color.GREEN,
)
if remove_service:
Logger.print_status("Removing Moonraker instances ...")
if self.moonraker_list:
selected = self._get_instances_to_remove()
self.__remove_instances(selected)
if selected:
instance_names = [
i.service_file_path.stem for i in selected
]
txt = f"● Moonraker instances removed: {', '.join(instance_names)}"
completion_msg.text.append(txt)
else:
Logger.print_info(
"No Moonraker Services installed! Skipped ..."
)
if (remove_polkit or remove_dir or remove_env) and unit_file_exists(
"moonraker", suffix="service"
):
completion_msg.text = [
"Some Klipper services are still installed:",
"● Moonraker PolicyKit rules were not removed, even though selected for removal.",
f"'{MOONRAKER_DIR}' was not removed, even though selected for removal.",
f"'{MOONRAKER_ENV_DIR}' was not removed, even though selected for removal.",
]
txt = f"● Moonraker instances removed: {', '.join(instance_names)}"
completion_msg.text.append(txt)
else:
if remove_polkit:
Logger.print_status(
"Removing all Moonraker policykit rules ..."
)
if remove_polkit_rules():
completion_msg.text.append(
"● Moonraker policykit rules removed"
)
if remove_dir:
Logger.print_status("Removing Moonraker local repository ...")
if run_remove_routines(MOONRAKER_DIR):
completion_msg.text.append(
"● Moonraker local repository removed"
)
if remove_env:
Logger.print_status("Removing Moonraker Python environment ...")
if run_remove_routines(MOONRAKER_ENV_DIR):
completion_msg.text.append(
"● Moonraker Python environment removed"
)
if completion_msg.text:
completion_msg.text.insert(
0, "The following actions were performed:"
)
else:
completion_msg.color = Color.YELLOW
completion_msg.centered = True
completion_msg.text = ["Nothing to remove."]
self.msgsvc.set_message(completion_msg)
else:
Logger.print_info("No Moonraker Services installed! Skipped ...")
if remove_service and self.moonraker_list:
selected = self._select_instances_for_headless_removal(
remove_all, instance_suffixes
)
if selected is None:
Logger.print_error(
"Refusing to remove Moonraker instances: no explicit "
"intent. Pass remove_all=True or instance_suffixes."
)
return False
self.__remove_instances(selected)
if (remove_polkit or remove_dir or remove_env) and unit_file_exists(
"moonraker", suffix="service"
):
completion_msg.text = [
"Some Klipper services are still installed:",
"● Moonraker PolicyKit rules were not removed, even though selected for removal.",
f"'{MOONRAKER_DIR}' was not removed, even though selected for removal.",
f"'{MOONRAKER_ENV_DIR}' was not removed, even though selected for removal.",
]
else:
if remove_polkit:
Logger.print_status("Removing all Moonraker policykit rules ...")
if remove_polkit_rules():
completion_msg.text.append("● Moonraker policykit rules removed")
if remove_dir:
Logger.print_status("Removing Moonraker local repository ...")
if run_remove_routines(MOONRAKER_DIR):
completion_msg.text.append("● Moonraker local repository removed")
if remove_env:
Logger.print_status("Removing Moonraker Python environment ...")
if run_remove_routines(MOONRAKER_ENV_DIR):
completion_msg.text.append("● Moonraker Python environment removed")
if (remove_polkit or remove_dir or remove_env) and unit_file_exists(
"moonraker", suffix="service"
):
Logger.print_info(
"Moonraker services still installed; skipping repository/env removal."
)
return True
if completion_msg.text:
completion_msg.text.insert(0, "The following actions were performed:")
else:
completion_msg.color = Color.YELLOW
completion_msg.centered = True
completion_msg.text = ["Nothing to remove."]
if remove_polkit:
remove_polkit_rules()
if remove_dir:
run_remove_routines(MOONRAKER_DIR)
if remove_env:
run_remove_routines(MOONRAKER_ENV_DIR)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error("Error while removing Moonraker!")
return False
self.msgsvc.set_message(completion_msg)
return True
def __run_setup(
self, new_instances: List[Moonraker], create_example_cfg: bool
def _run_setup(
self,
new_instances: List[Moonraker],
create_example_cfg: bool,
interactive: bool = True,
) -> None:
check_install_dependencies()
self.__install_deps()
# Only create a fresh venv when none exists; existing venvs are
# preserved in both TUI and CLI modes.
self._install_deps(interactive=interactive)
ports_map = self.misvc.get_instance_port_map()
for i in new_instances:
@@ -289,14 +398,21 @@ class MoonrakerSetupService:
dialog_content.append("You can access Moonraker via the following URL:")
dialog_content.extend(url_list)
Logger.print_dialog(
DialogType.CUSTOM,
custom_title="Moonraker successfully installed!",
custom_color=Color.GREEN,
content=dialog_content,
)
if interactive:
Logger.print_dialog(
DialogType.CUSTOM,
custom_title="Moonraker successfully installed!",
custom_color=Color.GREEN,
content=dialog_content,
)
else:
if url_list:
for url in url_list:
Logger.print_info(url)
else:
Logger.print_info("Moonraker successfully installed!")
def __check_requirements(self, klipper_list: List[Klipper]) -> bool:
def _check_requirements(self, klipper_list: List[Klipper]) -> bool:
is_klipper_installed = len(klipper_list) >= 1
if not is_klipper_installed:
Logger.print_warn("Klipper not installed!")
@@ -306,7 +422,7 @@ class MoonrakerSetupService:
return is_klipper_installed and is_python_ok
def __install_deps(self) -> None:
def _install_deps(self, interactive: bool = True) -> None:
default_repo = (MOONRAKER_REPO_URL, "master")
repo = self.settings.moonraker.repositories
# pull the first repo defined in kiauh.cfg or fallback to the official Moonraker repo
@@ -315,18 +431,24 @@ class MoonrakerSetupService:
try:
install_moonraker_packages()
if create_python_venv(MOONRAKER_ENV_DIR, False, False, self.settings.moonraker.use_python_binary):
if create_python_venv(
MOONRAKER_ENV_DIR,
force=False,
allow_access_to_system_site_packages=False,
use_python_binary=self.settings.moonraker.use_python_binary,
interactive=interactive,
):
install_python_requirements(MOONRAKER_ENV_DIR, MOONRAKER_REQ_FILE)
if self.settings.moonraker.optional_speedups:
install_python_requirements(
MOONRAKER_ENV_DIR, MOONRAKER_SPEEDUPS_REQ_FILE
)
self.__install_polkit()
self._install_polkit()
except Exception:
Logger.print_error("Error during installation of Moonraker requirements!")
raise
def __install_polkit(self) -> None:
def _install_polkit(self) -> None:
Logger.print_status("Installing Moonraker policykit rules ...")
legacy_file_exists = check_file_exist(POLKIT_LEGACY_FILE, True)
@@ -337,27 +459,23 @@ class MoonrakerSetupService:
Logger.print_info("Moonraker policykit rules are already installed.")
return
try:
command = [POLKIT_SCRIPT, "--disable-systemctl"]
result = run(
command,
stderr=PIPE,
stdout=DEVNULL,
text=True,
)
if result.returncode != 0 or result.stderr:
Logger.print_error(f"{result.stderr}", False)
Logger.print_error("Installing Moonraker policykit rules failed!")
return
command = [POLKIT_SCRIPT, "--disable-systemctl"]
result = run(
command,
stderr=PIPE,
stdout=DEVNULL,
text=True,
)
if result.returncode != 0 or result.stderr:
Logger.print_error(f"{result.stderr}", False)
Logger.print_error("Installing Moonraker policykit rules failed!")
# Intentional fail-soft: polkit rules are optional on many systems
# and a failure here must not abort the whole Moonraker installation.
return
Logger.print_ok("Moonraker policykit rules successfully installed!")
except CalledProcessError as e:
log = (
f"Error while installing Moonraker policykit rules: {e.stderr.decode()}"
)
Logger.print_error(log)
Logger.print_ok("Moonraker policykit rules successfully installed!")
def __get_instances_to_remove(self) -> List[Moonraker] | None:
def _get_instances_to_remove(self) -> List[Moonraker] | None:
start_index = 1
curr_instances: List[Moonraker] = self.moonraker_list
instance_count = len(curr_instances)
@@ -383,6 +501,26 @@ class MoonrakerSetupService:
return [instance_map[selection]]
def _select_instances_for_headless_removal(
self,
remove_all: bool,
instance_suffixes: List[str] | None,
) -> List[Moonraker] | None:
"""Resolve which instances to remove in headless mode.
Returns the list of instances to remove, or ``None`` when the caller did
not express explicit intent (no ``remove_all`` and no ``instance_suffixes``).
A ``None`` return is the "refuse to wipe everything" signal the CLI path
relies on. Kept as a single-public-seam helper (no name mangling) so
tests can patch it without brittle ``_Class__method`` access.
"""
if remove_all:
return list(self.moonraker_list)
if instance_suffixes:
wanted = set(instance_suffixes)
return [i for i in self.moonraker_list if i.suffix in wanted]
return None
def __remove_instances(
self,
instance_list: List[Moonraker] | None,
@@ -397,7 +535,7 @@ class MoonrakerSetupService:
InstanceManager.remove(instance)
self.__delete_env_file(instance)
self.__refresh_state()
self._refresh_state()
def __delete_env_file(self, instance: Moonraker):
Logger.print_status(f"Remove '{instance.env_file}'")
@@ -0,0 +1,4 @@
from __future__ import annotations
@@ -0,0 +1,560 @@
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, List
import pytest
from components.moonraker.services.moonraker_setup_service import MoonrakerSetupService
class FakeKlipper:
def __init__(self, suffix: str = "") -> None:
self.suffix = suffix
name = f"klipper-{suffix}" if suffix else "klipper"
self.service_file_path = Path(f"/etc/systemd/system/{name}.service")
class FakeMoonraker:
def __init__(self, suffix: str = "") -> None:
self.suffix = suffix
name = f"moonraker-{suffix}" if suffix else "moonraker"
self.service_file_path = Path(f"/etc/systemd/system/{name}.service")
self.env_file = Path(f"/tmp/{name}.env")
self.port = 7125
self.base = type("Base", (), {"sysd_dir": Path("/tmp")})()
def create(self) -> None:
pass
class FakeKlipperInstanceService:
def __init__(self, instances: List[FakeKlipper]) -> None:
self._instances = instances
def load_instances(self) -> None:
pass
def get_all_instances(self) -> List[FakeKlipper]:
return self._instances
class FakeMoonrakerInstanceService:
def __init__(self, instances: List[FakeMoonraker]) -> None:
self._instances = instances
self.created: List[str] = []
def load_instances(self) -> None:
pass
def get_all_instances(self) -> List[FakeMoonraker]:
return self._instances
def create_new_instance(self, suffix: str) -> FakeMoonraker:
self.created.append(suffix)
return FakeMoonraker(suffix)
def get_instance_by_suffix(self, suffix: str) -> FakeMoonraker:
return FakeMoonraker(suffix)
def get_instance_port_map(self) -> Dict[str, int]:
return {}
@pytest.fixture
def reset_service(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
MoonrakerSetupService, "_MoonrakerSetupService__cls_instance", None
)
@pytest.fixture
def patch_instance_services(
monkeypatch: pytest.MonkeyPatch, reset_service
) -> Dict[str, Any]:
state = {"klipper": [], "moonraker": []}
def make_kis(*args, **kwargs):
return FakeKlipperInstanceService(state["klipper"])
def make_mis(*args, **kwargs):
return FakeMoonrakerInstanceService(state["moonraker"])
module = "components.moonraker.services.moonraker_setup_service"
monkeypatch.setattr(f"{module}.KlipperInstanceService", make_kis)
monkeypatch.setattr(f"{module}.MoonrakerInstanceService", make_mis)
return state
class TestMoonrakerInstall:
def test_installs_for_single_klipper_instance(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["klipper"] = [FakeKlipper("")]
setup_calls: List[Any] = []
module = "components.moonraker.services.moonraker_setup_service"
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._check_requirements",
lambda self, kl: True,
)
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._run_setup",
lambda self, instances, cfg, interactive=True: setup_calls.append((
instances,
cfg,
interactive,
)),
)
monkeypatch.setattr(f"{module}.get_confirm", lambda *a, **k: True)
service = MoonrakerSetupService()
service.install()
assert len(setup_calls) == 1
instances, cfg, _interactive = setup_calls[0]
assert len(instances) == 1
assert instances[0].suffix == ""
assert cfg is True
def test_installs_for_selected_klipper_instance(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["klipper"] = [FakeKlipper("a"), FakeKlipper("b")]
setup_calls: List[Any] = []
module = "components.moonraker.services.moonraker_setup_service"
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._check_requirements",
lambda self, kl: True,
)
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._run_setup",
lambda self, instances, cfg, interactive=True: setup_calls.append((
instances,
cfg,
interactive,
)),
)
monkeypatch.setattr(f"{module}.get_selection_input", lambda *a, **k: "1")
monkeypatch.setattr(f"{module}.get_confirm", lambda *a, **k: True)
service = MoonrakerSetupService()
service.install()
assert len(setup_calls) == 1
assert setup_calls[0][0][0].suffix == "a"
class TestMoonrakerUpdate:
def test_update_runs_expected_steps(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["moonraker"] = [FakeMoonraker("")]
module = "components.moonraker.services.moonraker_setup_service"
calls: List[str] = []
monkeypatch.setattr(f"{module}.get_confirm", lambda *a, **k: True)
monkeypatch.setattr(
f"{module}.backup_moonraker_dir", lambda: calls.append("backup")
)
monkeypatch.setattr(
f"{module}.InstanceManager.stop_all",
staticmethod(lambda instances: calls.append("stop")),
)
monkeypatch.setattr(
f"{module}.git_pull_wrapper", lambda *a, **k: calls.append("pull")
)
monkeypatch.setattr(
f"{module}.install_moonraker_packages", lambda: calls.append("packages")
)
monkeypatch.setattr(
f"{module}.install_python_requirements",
lambda *a, **k: calls.append("requirements"),
)
monkeypatch.setattr(
f"{module}.InstanceManager.start_all",
staticmethod(lambda instances: calls.append("start")),
)
service = MoonrakerSetupService()
service.settings.kiauh.backup_before_update = True
service.update()
assert calls == ["backup", "stop", "pull", "packages", "requirements", "start"]
class TestMoonrakerRemove:
def test_removes_selected_instance(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["moonraker"] = [FakeMoonraker("")]
module = "components.moonraker.services.moonraker_setup_service"
removed: Dict[str, List[Any]] = {"instances": [], "paths": []}
fake_instance = FakeMoonraker("")
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._get_instances_to_remove",
lambda self: [fake_instance],
)
monkeypatch.setattr(
f"{module}.InstanceManager.remove",
staticmethod(lambda instance: removed["instances"].append(instance)),
)
monkeypatch.setattr(f"{module}.unit_file_exists", lambda *a, **k: False)
monkeypatch.setattr(f"{module}.remove_polkit_rules", lambda: True)
monkeypatch.setattr(
f"{module}.run_remove_routines",
lambda path: removed["paths"].append(str(path)) or True,
)
service = MoonrakerSetupService()
service.remove(
remove_service=True, remove_dir=True, remove_env=True, remove_polkit=True
)
assert removed["instances"] == [fake_instance]
assert any("moonraker" in p for p in removed["paths"])
class TestMoonrakerInstallHeadless:
def test_headless_install_does_not_show_success_dialog(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["klipper"] = [FakeKlipper("")]
module = "components.moonraker.services.moonraker_setup_service"
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._check_requirements",
lambda self, kl: True,
)
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._install_deps",
lambda self, interactive: None,
)
monkeypatch.setattr(f"{module}.get_confirm", lambda *a, **k: True)
monkeypatch.setattr(f"{module}.cmd_sysctl_service", lambda *a, **k: None)
monkeypatch.setattr(f"{module}.cmd_sysctl_manage", lambda *a, **k: None)
monkeypatch.setattr(
f"{module}.check_install_dependencies", lambda *a, **k: None
)
monkeypatch.setattr(f"{module}.get_ipv4_addr", lambda: "127.0.0.1")
monkeypatch.setattr(
f"{module}.Logger.print_dialog",
lambda *a, **k: pytest.fail("should not show dialog in headless install"),
)
errors: List[str] = []
monkeypatch.setattr(
f"{module}.Logger.print_error",
lambda msg, *a, **k: errors.append(str(msg)),
)
service = MoonrakerSetupService()
result = service.install(interactive=False)
assert errors == [], f"unexpected errors: {errors}"
assert result is True
def test_installs_with_explicit_klipper_suffixes(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["klipper"] = [FakeKlipper("a"), FakeKlipper("b")]
setup_calls: List[Any] = []
module = "components.moonraker.services.moonraker_setup_service"
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._check_requirements",
lambda self, kl: True,
)
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._run_setup",
lambda self, instances, cfg, interactive=True: setup_calls.append((
instances,
cfg,
interactive,
)),
)
service = MoonrakerSetupService()
result = service.install(klipper_suffixes=["a", "b"], interactive=False)
assert result is True
assert len(setup_calls) == 1
instances, cfg, interactive = setup_calls[0]
assert [i.suffix for i in instances] == ["a", "b"]
assert cfg is False
assert interactive is False
def test_installs_for_all_klipper_instances_when_non_interactive(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["klipper"] = [FakeKlipper("a"), FakeKlipper("b")]
setup_calls: List[Any] = []
module = "components.moonraker.services.moonraker_setup_service"
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._check_requirements",
lambda self, kl: True,
)
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._run_setup",
lambda self, instances, cfg, interactive=True: setup_calls.append((
instances,
cfg,
interactive,
)),
)
service = MoonrakerSetupService()
result = service.install(interactive=False)
assert result is True
assert [i.suffix for i in setup_calls[0][0]] == ["a", "b"]
assert setup_calls[0][2] is False
def test_returns_false_when_klipper_is_missing(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["klipper"] = []
service = MoonrakerSetupService()
result = service.install(interactive=False)
assert result is False
def test_returns_false_when_setup_raises(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["klipper"] = [FakeKlipper("")]
module = "components.moonraker.services.moonraker_setup_service"
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._check_requirements",
lambda self, kl: True,
)
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._run_setup",
lambda *a, **k: (_ for _ in ()).throw(RuntimeError("boom")),
)
service = MoonrakerSetupService()
result = service.install(interactive=False)
assert result is False
class TestMoonrakerUpdateHeadless:
def test_update_runs_without_confirmation(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["moonraker"] = [FakeMoonraker("")]
module = "components.moonraker.services.moonraker_setup_service"
calls: List[str] = []
monkeypatch.setattr(
f"{module}.backup_moonraker_dir", lambda: calls.append("backup")
)
monkeypatch.setattr(
f"{module}.InstanceManager.stop_all",
staticmethod(lambda instances: calls.append("stop")),
)
monkeypatch.setattr(
f"{module}.git_pull_wrapper", lambda *a, **k: calls.append("pull")
)
monkeypatch.setattr(
f"{module}.install_moonraker_packages", lambda: calls.append("packages")
)
monkeypatch.setattr(
f"{module}.install_python_requirements",
lambda *a, **k: calls.append("requirements"),
)
monkeypatch.setattr(
f"{module}.InstanceManager.start_all",
staticmethod(lambda instances: calls.append("start")),
)
service = MoonrakerSetupService()
service.settings.kiauh.backup_before_update = True
service.update(interactive=False)
assert calls == ["backup", "stop", "pull", "packages", "requirements", "start"]
def test_update_cancelled_by_user_returns_false(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["moonraker"] = [FakeMoonraker("")]
pulled: List[str] = []
module = "components.moonraker.services.moonraker_setup_service"
monkeypatch.setattr(
f"{module}.git_pull_wrapper", lambda *a, **k: pulled.append("pull")
)
monkeypatch.setattr(f"{module}.get_confirm", lambda *a, **k: False)
service = MoonrakerSetupService()
result = service.update(interactive=True)
assert result is False
assert pulled == []
class TestMoonrakerPolkitBehavior:
def test_install_polkit_failure_logs_error_and_continues(
self, patch_instance_services, monkeypatch
) -> None:
module = "components.moonraker.services.moonraker_setup_service"
class FakeResult:
returncode = 1
stderr = "polkit install failed"
monkeypatch.setattr(f"{module}.run", lambda *a, **k: FakeResult())
monkeypatch.setattr(
f"{module}.check_file_exist", lambda p, follow_symlinks=False: False
)
error_messages: List[str] = []
monkeypatch.setattr(
f"{module}.Logger.print_error",
lambda msg, *a, **k: error_messages.append(str(msg)),
)
service = MoonrakerSetupService()
service._install_polkit()
assert any("polkit" in m.lower() for m in error_messages)
def test_install_succeeds_when_polkit_rules_fail(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["klipper"] = [FakeKlipper("")]
module = "components.moonraker.services.moonraker_setup_service"
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._check_requirements",
lambda self, kl: True,
)
setup_calls: List[Any] = []
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._run_setup",
lambda self, instances, cfg, interactive=True: setup_calls.append((
instances,
cfg,
interactive,
)),
)
class FakeResult:
returncode = 1
stderr = "polkit install failed"
monkeypatch.setattr(f"{module}.run", lambda *a, **k: FakeResult())
monkeypatch.setattr(
f"{module}.check_file_exist", lambda p, follow_symlinks=False: False
)
monkeypatch.setattr(f"{module}.get_confirm", lambda *a, **k: True)
def fake_install_deps(self, interactive: bool = True) -> None:
self._install_polkit()
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._install_deps",
fake_install_deps,
)
service = MoonrakerSetupService()
result = service.install()
assert result is True
assert len(setup_calls) == 1
class TestMoonrakerRemoveHeadless:
def _patch_remove_internals(self, monkeypatch, removed):
module = "components.moonraker.services.moonraker_setup_service"
monkeypatch.setattr(
f"{module}.InstanceManager.remove",
staticmethod(lambda instance: removed["instances"].append(instance.suffix)),
)
monkeypatch.setattr(
f"{module}.MoonrakerSetupService._refresh_state",
lambda self: None,
)
monkeypatch.setattr(f"{module}.unit_file_exists", lambda *a, **k: False)
monkeypatch.setattr(
f"{module}.remove_polkit_rules",
lambda: removed["paths"].append("polkit") or True,
)
monkeypatch.setattr(
f"{module}.run_remove_routines",
lambda path: removed["paths"].append(str(path)) or True,
)
def test_removes_all_instances_when_explicit_all(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["moonraker"] = [FakeMoonraker("a"), FakeMoonraker("b")]
removed: Dict[str, List[Any]] = {"instances": [], "paths": []}
self._patch_remove_internals(monkeypatch, removed)
service = MoonrakerSetupService()
service.remove(
remove_service=True,
remove_dir=True,
remove_env=True,
remove_polkit=True,
remove_all=True,
interactive=False,
)
assert set(removed["instances"]) == {"a", "b"}
assert "polkit" in removed["paths"]
def test_without_explicit_intent_removes_nothing(
self, patch_instance_services, monkeypatch
) -> None:
# non-interactive remove with no --all / --instance must not destroy any instance and must refuse.
patch_instance_services["moonraker"] = [FakeMoonraker("a"), FakeMoonraker("b")]
removed: Dict[str, List[Any]] = {"instances": [], "paths": []}
self._patch_remove_internals(monkeypatch, removed)
service = MoonrakerSetupService()
result = service.remove(
remove_service=True,
remove_dir=False,
remove_env=False,
remove_polkit=False,
interactive=False,
)
assert result is False
assert removed["instances"] == []
assert removed["paths"] == []
def test_with_instance_suffix_removes_only_matching(
self, patch_instance_services, monkeypatch
) -> None:
patch_instance_services["moonraker"] = [
FakeMoonraker("a"),
FakeMoonraker("b"),
]
removed: Dict[str, List[Any]] = {"instances": [], "paths": []}
self._patch_remove_internals(monkeypatch, removed)
service = MoonrakerSetupService()
service.remove(
remove_service=True,
remove_dir=False,
remove_env=False,
remove_polkit=False,
instance_suffixes=["a"],
interactive=False,
)
assert removed["instances"] == ["a"]
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -61,6 +61,9 @@ class SysDepsParser:
version = distro_info.get("distro_version")
if version:
self.distro_version = _convert_version(version)
self.vendor: str = ""
if pathlib.Path("/etc/rpi-issue").is_file():
self.vendor = "raspberry-pi"
def _parse_spec(self, full_spec: str) -> str | None:
parts = full_spec.split(";", maxsplit=1)
@@ -109,6 +112,9 @@ class SysDepsParser:
elif req_var == "distro_id":
left_op: str | Tuple[int | str, ...] = self.distro_id
right_op = dep_parts[2].strip().strip("\"'")
elif req_var == "vendor":
left_op = self.vendor
right_op = dep_parts[2].strip().strip("\"'")
elif req_var == "distro_version":
if not self.distro_version:
logging.info(
@@ -0,0 +1,278 @@
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Dict, List
import pytest
from components.moonraker.utils import utils as moonraker_utils
from components.moonraker.utils.utils import (
backup_moonraker_db_dir,
backup_moonraker_dir,
create_example_moonraker_conf,
get_moonraker_status,
install_moonraker_packages,
load_sysdeps_json,
remove_polkit_rules,
)
class FakeMoonraker:
def __init__(self, suffix: str = "") -> None:
self.suffix = suffix
self.data_dir = Path(f"/tmp/moonraker{suffix}_data")
self.db_dir = self.data_dir.joinpath("database")
self.cfg_file = self.data_dir.joinpath("moonraker.conf")
self.base = type(
"Base",
(),
{
"cfg_dir": self.data_dir,
"comms_dir": self.data_dir.joinpath("comms"),
},
)()
@pytest.fixture
def fake_instance(tmp_path: Path) -> FakeMoonraker:
instance = FakeMoonraker("")
instance.data_dir = tmp_path / "moonraker_data"
instance.cfg_file = instance.data_dir / "moonraker.conf"
instance.db_dir = instance.data_dir / "database"
instance.base = type(
"Base",
(),
{
"cfg_dir": instance.data_dir,
"comms_dir": instance.data_dir / "comms",
},
)()
return instance
class TestGetMoonrakerStatus:
def test_delegates_to_get_install_status(self, monkeypatch: pytest.MonkeyPatch) -> None:
called: List[Any] = []
monkeypatch.setattr(
moonraker_utils,
"get_install_status",
lambda *args: called.append(args) or type("S", (), {"status": 0})(),
)
status = get_moonraker_status()
assert called
assert status.status == 0
class TestInstallMoonrakerPackages:
def test_parses_deps_json_when_present(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
deps_file = tmp_path / "moonraker_deps.json"
deps_file.write_text(json.dumps({"debian": ["pkg1", "pkg2"]}))
install_script = tmp_path / "install_moonraker.sh"
install_script.write_text("# dummy")
monkeypatch.setattr(moonraker_utils, "MOONRAKER_DEPS_JSON_FILE", deps_file)
monkeypatch.setattr(moonraker_utils, "MOONRAKER_INSTALL_SCRIPT", install_script)
deps: List[str] = []
monkeypatch.setattr(
moonraker_utils, "check_install_dependencies", lambda p: deps.extend(p)
)
class FakeParser:
def parse_dependencies(self, data):
return ["pkg1", "pkg2"]
monkeypatch.setattr(moonraker_utils, "SysDepsParser", FakeParser)
install_moonraker_packages()
assert "pkg1" in deps
assert "pkg2" in deps
def test_falls_back_to_install_script(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
deps_file = tmp_path / "missing.json"
install_script = tmp_path / "install_moonraker.sh"
install_script.write_text("apt-get install pkg3 pkg4\n")
monkeypatch.setattr(moonraker_utils, "MOONRAKER_DEPS_JSON_FILE", deps_file)
monkeypatch.setattr(moonraker_utils, "MOONRAKER_INSTALL_SCRIPT", install_script)
deps: List[str] = []
monkeypatch.setattr(
moonraker_utils, "check_install_dependencies", lambda p: deps.extend(p)
)
monkeypatch.setattr(
moonraker_utils,
"parse_packages_from_file",
lambda p: ["pkg3", "pkg4"],
)
install_moonraker_packages()
assert "pkg3" in deps
def test_raises_when_no_deps_found(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
deps_file = tmp_path / "missing.json"
install_script = tmp_path / "missing.sh"
monkeypatch.setattr(moonraker_utils, "MOONRAKER_DEPS_JSON_FILE", deps_file)
monkeypatch.setattr(moonraker_utils, "MOONRAKER_INSTALL_SCRIPT", install_script)
with pytest.raises(ValueError):
install_moonraker_packages()
class TestRemovePolkitRules:
def test_returns_false_when_moonraker_dir_missing(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
monkeypatch.setattr(moonraker_utils, "MOONRAKER_DIR", tmp_path / "missing")
assert remove_polkit_rules() is False
def test_returns_true_on_success(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
monkeypatch.setattr(moonraker_utils, "MOONRAKER_DIR", tmp_path)
monkeypatch.setattr(
moonraker_utils,
"run",
lambda *a, **k: type("R", (), {"returncode": 0})(),
)
assert remove_polkit_rules() is True
def test_returns_false_on_command_failure(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
monkeypatch.setattr(moonraker_utils, "MOONRAKER_DIR", tmp_path)
def fake_run(*a, **k):
raise moonraker_utils.CalledProcessError(1, cmd="clear")
monkeypatch.setattr(moonraker_utils, "run", fake_run)
assert remove_polkit_rules() is False
class TestCreateExampleMoonrakerConf:
def test_skips_when_config_already_exists(
self, monkeypatch: pytest.MonkeyPatch, fake_instance: FakeMoonraker
) -> None:
fake_instance.cfg_file.parent.mkdir(parents=True, exist_ok=True)
fake_instance.cfg_file.write_text("existing")
create_example_moonraker_conf(fake_instance, {})
# no changes expected
assert fake_instance.cfg_file.read_text() == "existing"
def test_creates_config_with_default_port(
self,
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
fake_instance: FakeMoonraker,
) -> None:
fake_instance.cfg_file.parent.mkdir(parents=True, exist_ok=True)
assets_dir = tmp_path / "assets"
assets_dir.mkdir()
template = assets_dir / "moonraker.conf"
template.write_text(
"[server]\nport: %{PORT}%\nklippy_uds_address: %{UDS}%\n"
"[authorization]\ntrusted_clients:\n %{CLIENTS}%\n"
)
monkeypatch.setattr(moonraker_utils, "MODULE_PATH", tmp_path)
monkeypatch.setattr(
moonraker_utils, "get_ipv4_addr", lambda: "192.168.1.10"
)
create_example_moonraker_conf(fake_instance, {})
content = fake_instance.cfg_file.read_text()
assert "192.168.0.0/16" in content
class TestBackupMoonrakerDir:
def test_backs_up_repository_and_environment(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
calls: List[Dict[str, Any]] = []
class FakeBackup:
def backup_directory(self, **kwargs):
calls.append(kwargs)
monkeypatch.setattr(moonraker_utils, "BackupService", FakeBackup)
monkeypatch.setattr(moonraker_utils, "MOONRAKER_DIR", tmp_path / "moonraker")
monkeypatch.setattr(moonraker_utils, "MOONRAKER_ENV_DIR", tmp_path / "env")
backup_moonraker_dir()
assert len(calls) == 2
class TestBackupMoonrakerDbDir:
def test_backs_up_db_for_each_instance(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
calls: List[Dict[str, Any]] = []
class FakeBackup:
def backup_directory(self, **kwargs):
calls.append(kwargs)
monkeypatch.setattr(moonraker_utils, "BackupService", FakeBackup)
monkeypatch.setattr(
moonraker_utils, "get_instances", lambda model: [FakeMoonraker("")]
)
backup_moonraker_db_dir()
assert len(calls) == 1
def test_falls_back_to_home_dirs(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
monkeypatch.setattr(Path, "home", lambda: tmp_path)
printer_data = tmp_path / "printer_data"
printer_data.mkdir()
printer_data.joinpath("database").mkdir()
calls: List[Dict[str, Any]] = []
class FakeBackup:
def backup_directory(self, **kwargs):
calls.append(kwargs)
monkeypatch.setattr(moonraker_utils, "BackupService", FakeBackup)
monkeypatch.setattr(moonraker_utils, "get_instances", lambda model: [])
backup_moonraker_db_dir()
assert len(calls) == 1
class TestLoadSysdepsJson:
def test_loads_valid_json(self, tmp_path: Path) -> None:
file = tmp_path / "deps.json"
file.write_text('{"debian": ["curl"]}')
result = load_sysdeps_json(file)
assert result == {"debian": ["curl"]}
def test_returns_empty_on_invalid_json(self, tmp_path: Path) -> None:
file = tmp_path / "deps.json"
file.write_text("not json")
result = load_sysdeps_json(file)
assert result == {}
+47 -15
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -14,8 +14,6 @@ from typing import Dict, List, Optional
from components.moonraker import (
MODULE_PATH,
MOONRAKER_BACKUP_DIR,
MOONRAKER_DB_BACKUP_DIR,
MOONRAKER_DEFAULT_PORT,
MOONRAKER_DEPS_JSON_FILE,
MOONRAKER_DIR,
@@ -25,9 +23,9 @@ from components.moonraker import (
from components.moonraker.moonraker import Moonraker
from components.moonraker.utils.sysdeps_parser import SysDepsParser
from components.webui_client.base_data import BaseWebClient
from core.backup_manager.backup_manager import BackupManager
from core.logger import Logger
from core.submodules.simple_config_parser.src.simple_config_parser.simple_config_parser import (
from core.services.backup_service import BackupService
from core.simple_config_parser.simple_config_parser import (
SimpleConfigParser,
)
from core.types.component_status import ComponentStatus
@@ -125,8 +123,8 @@ def create_example_moonraker_conf(
scp = SimpleConfigParser()
scp.read_file(target)
trusted_clients: List[str] = [
f" {'.'.join(ip)}\n",
*scp.getval("authorization", "trusted_clients"),
f"{'.'.join(ip)}",
*scp.getvals("authorization", "trusted_clients"),
]
scp.set_option("server", "port", str(port))
@@ -168,21 +166,55 @@ def create_example_moonraker_conf(
def backup_moonraker_dir() -> None:
bm = BackupManager()
bm.backup_directory("moonraker", source=MOONRAKER_DIR, target=MOONRAKER_BACKUP_DIR)
bm.backup_directory(
"moonraker-env", source=MOONRAKER_ENV_DIR, target=MOONRAKER_BACKUP_DIR
svc = BackupService()
svc.backup_directory(
source_path=MOONRAKER_DIR, backup_name="moonraker", target_path="moonraker"
)
svc.backup_directory(
source_path=MOONRAKER_ENV_DIR,
backup_name="moonraker-env",
target_path="moonraker",
)
def backup_moonraker_db_dir() -> None:
instances: List[Moonraker] = get_instances(Moonraker)
bm = BackupManager()
svc = BackupService()
if not instances:
# fallback: search for printer data directories in the user's home directory
Logger.print_info("No Moonraker instances found via systemd services.")
Logger.print_info(
"Attempting to find printer data directories in home directory..."
)
home_dir = Path.home()
printer_data_dirs = []
for pattern in ["printer_data", "printer_*_data"]:
for data_dir in home_dir.glob(pattern):
if data_dir.is_dir():
printer_data_dirs.append(data_dir)
if not printer_data_dirs:
Logger.print_info("Unable to find directory to backup!")
Logger.print_info("No printer data directories found in home directory.")
return
for data_dir in printer_data_dirs:
svc.backup_directory(
source_path=data_dir.joinpath("database"),
target_path=data_dir.name,
backup_name="database",
)
return
for instance in instances:
name = f"database-{instance.data_dir.name}"
bm.backup_directory(
name, source=instance.db_dir, target=MOONRAKER_DB_BACKUP_DIR
svc.backup_directory(
source_path=instance.db_dir,
target_path=f"{instance.data_dir.name}",
backup_name="database",
)
+12 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -8,5 +8,16 @@
# ======================================================================= #
from pathlib import Path
from typing import Callable, Dict
from components.webui_client.base_data import BaseWebClient
from components.webui_client.fluidd_data import FluiddData
from components.webui_client.mainsail_data import MainsailData
MODULE_PATH = Path(__file__).resolve().parent
# Shared registry of supported web clients
CLIENTS: Dict[str, Callable[[], BaseWebClient]] = {
"mainsail": MainsailData,
"fluidd": FluiddData,
}
+1 -3
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -34,7 +34,6 @@ class BaseWebClient(ABC):
display_name: str
client_dir: Path
config_file: Path
backup_dir: Path
repo_path: str
download_url: str
nginx_config: Path
@@ -52,6 +51,5 @@ class BaseWebClientConfig(ABC):
display_name: str
config_filename: str
config_dir: Path
backup_dir: Path
repo_url: str
config_section: str
@@ -1,91 +0,0 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from typing import List
from components.klipper.klipper import Klipper
from components.moonraker.moonraker import Moonraker
from components.webui_client.base_data import BaseWebClientConfig
from core.logger import Logger
from core.services.message_service import Message
from core.types.color import Color
from utils.config_utils import remove_config_section
from utils.fs_utils import run_remove_routines
from utils.instance_type import InstanceType
from utils.instance_utils import get_instances
def run_client_config_removal(
client_config: BaseWebClientConfig,
kl_instances: List[Klipper],
mr_instances: List[Moonraker],
) -> Message:
completion_msg = Message(
title=f"{client_config.display_name} Removal Process completed",
color=Color.GREEN,
)
Logger.print_status(f"Removing {client_config.display_name} ...")
if run_remove_routines(client_config.config_dir):
completion_msg.text.append(f"{client_config.display_name} removed")
completion_msg = remove_moonraker_config_section(
completion_msg, client_config, mr_instances
)
completion_msg = remove_printer_config_section(
completion_msg, client_config, kl_instances
)
if completion_msg.text:
completion_msg.text.insert(0, "The following actions were performed:")
else:
completion_msg.color = Color.YELLOW
completion_msg.centered = True
completion_msg.text = ["Nothing to remove."]
return completion_msg
def remove_cfg_symlink(client_config: BaseWebClientConfig, message: Message) -> Message:
instances: List[Klipper] = get_instances(Klipper)
kl_instances = []
for instance in instances:
cfg = instance.base.cfg_dir.joinpath(client_config.config_filename)
if run_remove_routines(cfg):
kl_instances.append(instance)
text = f"{client_config.display_name} removed from instance"
return update_msg(kl_instances, message, text)
def remove_printer_config_section(
message: Message, client_config: BaseWebClientConfig, kl_instances: List[Klipper]
) -> Message:
kl_section = client_config.config_section
kl_instances = remove_config_section(kl_section, kl_instances)
text = f"Klipper config section '{kl_section}' removed for instance"
return update_msg(kl_instances, message, text)
def remove_moonraker_config_section(
message: Message, client_config: BaseWebClientConfig, mr_instances: List[Moonraker]
) -> Message:
mr_section = f"update_manager {client_config.name}"
mr_instances = remove_config_section(mr_section, mr_instances)
text = f"Moonraker config section '{mr_section}' removed for instance"
return update_msg(mr_instances, message, text)
def update_msg(instances: List[InstanceType], message: Message, text: str) -> Message:
if not instances:
return message
instance_names = [i.service_file_path.stem for i in instances]
message.text.append(f"{text}: {', '.join(instance_names)}")
return message
@@ -1,126 +0,0 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
from typing import List
from components.klipper.klipper import Klipper
from components.moonraker.moonraker import Moonraker
from components.webui_client.base_data import BaseWebClient, BaseWebClientConfig
from components.webui_client.client_dialogs import (
print_client_already_installed_dialog,
)
from components.webui_client.client_utils import (
backup_client_config_data,
detect_client_cfg_conflict,
)
from core.instance_manager.instance_manager import InstanceManager
from core.logger import Logger
from core.settings.kiauh_settings import KiauhSettings
from utils.common import backup_printer_config_dir
from utils.config_utils import add_config_section, add_config_section_at_top
from utils.fs_utils import create_symlink
from utils.git_utils import git_clone_wrapper, git_pull_wrapper
from utils.input_utils import get_confirm
from utils.instance_utils import get_instances
def install_client_config(client_data: BaseWebClient, cfg_backup=True) -> None:
client_config: BaseWebClientConfig = client_data.client_config
display_name = client_config.display_name
if detect_client_cfg_conflict(client_data):
Logger.print_info("Another Client-Config is already installed! Skipped ...")
return
if client_config.config_dir.exists():
print_client_already_installed_dialog(display_name)
if get_confirm(f"Re-install {display_name}?", allow_go_back=True):
shutil.rmtree(client_config.config_dir)
else:
return
mr_instances: List[Moonraker] = get_instances(Moonraker)
kl_instances = get_instances(Klipper)
try:
download_client_config(client_config)
create_client_config_symlink(client_config, kl_instances)
if cfg_backup:
backup_printer_config_dir()
add_config_section(
section=f"update_manager {client_config.name}",
instances=mr_instances,
options=[
("type", "git_repo"),
("primary_branch", "master"),
("path", str(client_config.config_dir)),
("origin", str(client_config.repo_url)),
("managed_services", "klipper"),
],
)
add_config_section_at_top(client_config.config_section, kl_instances)
InstanceManager.restart_all(kl_instances)
except Exception as e:
Logger.print_error(f"{display_name} installation failed!\n{e}")
return
Logger.print_ok(f"{display_name} installation complete!", start="\n")
def download_client_config(client_config: BaseWebClientConfig) -> None:
try:
Logger.print_status(f"Downloading {client_config.display_name} ...")
repo = client_config.repo_url
target_dir = client_config.config_dir
git_clone_wrapper(repo, target_dir)
except Exception:
Logger.print_error(f"Downloading {client_config.display_name} failed!")
raise
def update_client_config(client: BaseWebClient) -> None:
client_config: BaseWebClientConfig = client.client_config
Logger.print_status(f"Updating {client_config.display_name} ...")
if not client_config.config_dir.exists():
Logger.print_info(
f"Unable to update {client_config.display_name}. Directory does not exist! Skipping ..."
)
return
settings = KiauhSettings()
if settings.kiauh.backup_before_update:
backup_client_config_data(client)
git_pull_wrapper(client_config.config_dir)
Logger.print_ok(f"Successfully updated {client_config.display_name}.")
Logger.print_info("Restart Klipper to reload the configuration!")
def create_client_config_symlink(
client_config: BaseWebClientConfig, klipper_instances: List[Klipper]
) -> None:
for instance in klipper_instances:
Logger.print_status(f"Create symlink for {client_config.config_filename} ...")
source = Path(client_config.config_dir, client_config.config_filename)
target = instance.base.cfg_dir
Logger.print_status(f"Linking {source} to {target}")
try:
create_symlink(source, target)
except subprocess.CalledProcessError:
Logger.print_error("Creating symlink failed!")
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -1,112 +0,0 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from typing import List
from components.klipper.klipper import Klipper
from components.moonraker.moonraker import Moonraker
from components.webui_client.base_data import (
BaseWebClient,
)
from components.webui_client.client_config.client_config_remove import (
run_client_config_removal,
)
from core.backup_manager.backup_manager import BackupManager
from core.constants import NGINX_SITES_AVAILABLE, NGINX_SITES_ENABLED
from core.logger import Logger
from core.services.message_service import Message
from core.types.color import Color
from utils.config_utils import remove_config_section
from utils.fs_utils import (
remove_with_sudo,
run_remove_routines,
)
from utils.instance_utils import get_instances
def run_client_removal(
client: BaseWebClient,
remove_client: bool,
remove_client_cfg: bool,
backup_config: bool,
) -> Message:
completion_msg = Message(
title=f"{client.display_name} Removal Process completed",
color=Color.GREEN,
)
mr_instances: List[Moonraker] = get_instances(Moonraker)
kl_instances: List[Klipper] = get_instances(Klipper)
if backup_config:
bm = BackupManager()
if bm.backup_file(client.config_file):
completion_msg.text.append(f"{client.config_file.name} backup created")
if remove_client:
client_name = client.name
if remove_client_dir(client):
completion_msg.text.append(f"{client.display_name} removed")
if remove_client_nginx_config(client_name):
completion_msg.text.append("● NGINX config removed")
if remove_client_nginx_logs(client, kl_instances):
completion_msg.text.append("● NGINX logs removed")
section = f"update_manager {client_name}"
handled_instances: List[Moonraker] = remove_config_section(
section, mr_instances
)
if handled_instances:
names = [i.service_file_path.stem for i in handled_instances]
completion_msg.text.append(
f"● Moonraker config section '{section}' removed for instance: {', '.join(names)}"
)
if remove_client_cfg:
cfg_completion_msg = run_client_config_removal(
client.client_config,
kl_instances,
mr_instances,
)
if cfg_completion_msg.color == Color.GREEN:
completion_msg.text.extend(cfg_completion_msg.text[1:])
if not completion_msg.text:
completion_msg.color = Color.YELLOW
completion_msg.centered = True
completion_msg.text.append("Nothing to remove.")
else:
completion_msg.text.insert(0, "The following actions were performed:")
return completion_msg
def remove_client_dir(client: BaseWebClient) -> bool:
Logger.print_status(f"Removing {client.display_name} ...")
return run_remove_routines(client.client_dir)
def remove_client_nginx_config(name: str) -> bool:
Logger.print_status(f"Removing NGINX config for {name.capitalize()} ...")
return remove_with_sudo(
[
NGINX_SITES_AVAILABLE.joinpath(name),
NGINX_SITES_ENABLED.joinpath(name),
]
)
def remove_client_nginx_logs(client: BaseWebClient, instances: List[Klipper]) -> bool:
Logger.print_status(f"Removing NGINX logs for {client.display_name} ...")
files = [client.nginx_access_log, client.nginx_error_log]
if instances:
for instance in instances:
files.append(instance.base.log_dir.joinpath(client.nginx_access_log.name))
files.append(instance.base.log_dir.joinpath(client.nginx_error_log.name))
return remove_with_sudo(files)
@@ -1,186 +0,0 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
import shutil
import tempfile
from pathlib import Path
from typing import List
from components.klipper.klipper import Klipper
from components.moonraker.moonraker import Moonraker
from components.webui_client import MODULE_PATH
from components.webui_client.base_data import (
BaseWebClient,
BaseWebClientConfig,
WebClientType,
)
from components.webui_client.client_config.client_config_setup import (
install_client_config,
)
from components.webui_client.client_dialogs import (
print_install_client_config_dialog,
print_moonraker_not_found_dialog,
)
from components.webui_client.client_utils import (
copy_common_vars_nginx_cfg,
copy_upstream_nginx_cfg,
create_nginx_cfg,
detect_client_cfg_conflict,
enable_mainsail_remotemode,
get_client_port_selection,
symlink_webui_nginx_log,
)
from core.instance_manager.instance_manager import InstanceManager
from core.logger import DialogType, Logger
from core.settings.kiauh_settings import KiauhSettings
from core.types.color import Color
from utils.common import backup_printer_config_dir, check_install_dependencies
from utils.config_utils import add_config_section
from utils.fs_utils import unzip
from utils.input_utils import get_confirm
from utils.instance_utils import get_instances
from utils.sys_utils import (
cmd_sysctl_service,
download_file,
get_ipv4_addr,
)
def install_client(
client: BaseWebClient,
settings: KiauhSettings,
reinstall: bool = False,
) -> None:
mr_instances: List[Moonraker] = get_instances(Moonraker)
enable_remotemode = False
if not mr_instances:
print_moonraker_not_found_dialog(client.display_name)
if not get_confirm(f"Continue {client.display_name} installation?"):
return
# if moonraker is not installed or multiple instances
# are installed we enable mainsails remote mode
if (
client.client == WebClientType.MAINSAIL
and not mr_instances
or len(mr_instances) > 1
):
enable_remotemode = True
kl_instances = get_instances(Klipper)
install_client_cfg = False
client_config: BaseWebClientConfig = client.client_config
if (
kl_instances
and not client_config.config_dir.exists()
and not detect_client_cfg_conflict(client)
):
print_install_client_config_dialog(client)
question = f"Download the recommended {client_config.display_name}?"
install_client_cfg = get_confirm(question, allow_go_back=False)
default_port: int = int(settings.get(client.name, "port"))
port: int = (
default_port if reinstall else get_client_port_selection(client, settings)
)
check_install_dependencies({"nginx"})
try:
download_client(client)
if enable_remotemode and client.client == WebClientType.MAINSAIL:
enable_mainsail_remotemode()
backup_printer_config_dir()
add_config_section(
section=f"update_manager {client.name}",
instances=mr_instances,
options=[
("type", "web"),
("channel", "stable"),
("repo", str(client.repo_path)),
("path", str(client.client_dir)),
],
)
InstanceManager.restart_all(mr_instances)
if install_client_cfg and kl_instances:
install_client_config(client, False)
copy_upstream_nginx_cfg()
copy_common_vars_nginx_cfg()
create_nginx_cfg(
display_name=client.display_name,
cfg_name=client.name,
template_src=MODULE_PATH.joinpath("assets/nginx_cfg"),
PORT=port,
ROOT_DIR=client.client_dir,
NAME=client.name,
)
if kl_instances:
symlink_webui_nginx_log(client, kl_instances)
cmd_sysctl_service("nginx", "restart")
except Exception as e:
Logger.print_error(e)
Logger.print_dialog(
DialogType.ERROR,
center_content=True,
content=[f"{client.display_name} installation failed!"],
)
return
# noinspection HttpUrlsUsage
Logger.print_dialog(
DialogType.CUSTOM,
custom_title=f"{client.display_name} installation complete!",
custom_color=Color.GREEN,
center_content=True,
content=[
f"Open {client.display_name} now on: http://{get_ipv4_addr()}{'' if port == 80 else f':{port}'}",
],
)
def download_client(client: BaseWebClient) -> None:
zipfile = f"{client.name.lower()}.zip"
target = Path().home().joinpath(zipfile)
try:
Logger.print_status(
f"Downloading {client.display_name} from {client.download_url} ..."
)
download_file(client.download_url, target, True)
Logger.print_ok("Download complete!")
Logger.print_status(f"Extracting {zipfile} ...")
unzip(target, client.client_dir)
target.unlink(missing_ok=True)
Logger.print_ok("OK!")
except Exception:
Logger.print_error(f"Downloading {client.display_name} failed!")
raise
def update_client(client: BaseWebClient) -> None:
Logger.print_status(f"Updating {client.display_name} ...")
if not client.client_dir.exists():
Logger.print_info(
f"Unable to update {client.display_name}. Directory does not exist! Skipping ..."
)
return
with tempfile.NamedTemporaryFile(suffix=".json") as tmp_file:
Logger.print_status(
f"Creating temporary backup of {client.config_file} as {tmp_file.name} ..."
)
shutil.copy(client.config_file, tmp_file.name)
download_client(client)
shutil.copy(tmp_file.name, client.config_file)
+81 -34
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -11,6 +11,7 @@ from __future__ import annotations
import json
import re
import shutil
from json import JSONDecodeError
from pathlib import Path
from subprocess import PIPE, CalledProcessError, run
from typing import List, get_args
@@ -19,20 +20,21 @@ from components.klipper.klipper import Klipper
from components.webui_client import MODULE_PATH
from components.webui_client.base_data import (
BaseWebClient,
BaseWebClientConfig,
WebClientType,
)
from components.webui_client.client_dialogs import print_client_port_select_dialog
from components.webui_client.fluidd_data import FluiddData
from components.webui_client.mainsail_data import MainsailData
from core.backup_manager.backup_manager import BackupManager
from core.constants import (
NGINX_CONFD,
NGINX_SITES_AVAILABLE,
NGINX_SITES_ENABLED,
)
from core.logger import Logger
from core.services.backup_service import BackupService
from core.settings.kiauh_settings import KiauhSettings, WebUiSettings
from core.submodules.simple_config_parser.src.simple_config_parser.simple_config_parser import (
from core.simple_config_parser.simple_config_parser import (
SimpleConfigParser,
)
from core.types.color import Color
@@ -77,10 +79,10 @@ def get_current_client_config() -> str:
installed = [c for c in clients if c.client_config.config_dir.exists()]
if not installed:
return Color.apply("-", Color.CYAN)
return str(Color.apply("-", Color.CYAN))
elif len(installed) == 1:
cfg = installed[0].client_config
return Color.apply(cfg.display_name, Color.CYAN)
return str(Color.apply(cfg.display_name, Color.CYAN))
# at this point, both client config folders exists, so we need to check
# which are actually included in the printer.cfg of all klipper instances
@@ -99,18 +101,18 @@ def get_current_client_config() -> str:
# if both are included in the same file, we have a potential conflict
if includes_mainsail and includes_fluidd:
return Color.apply("Conflict", Color.YELLOW)
return str(Color.apply("Conflict", Color.YELLOW))
if not mainsail_includes and not fluidd_includes:
# there are no includes at all, even though the client config folders exist
return Color.apply("-", Color.CYAN)
return str(Color.apply("-", Color.CYAN))
elif len(fluidd_includes) > len(mainsail_includes):
# there are more instances that include fluidd than mainsail
return Color.apply(fluidd.client_config.display_name, Color.CYAN)
return str(Color.apply(fluidd.client_config.display_name, Color.CYAN))
else:
# there are the same amount of non-conflicting includes for each config
# or more instances include mainsail than fluidd
return Color.apply(mainsail.client_config.display_name, Color.CYAN)
return str(Color.apply(mainsail.client_config.display_name, Color.CYAN))
def enable_mainsail_remotemode() -> None:
@@ -119,7 +121,7 @@ def enable_mainsail_remotemode() -> None:
with open(c_json, "r") as f:
config_data = json.load(f)
if config_data["instancesDB"] == "browser":
if config_data["instancesDB"] == "browser" or config_data["instancesDB"] == "json":
Logger.print_info("Remote mode already configured. Skipped ...")
return
@@ -154,15 +156,32 @@ def get_local_client_version(client: BaseWebClient) -> str | None:
if not client.client_dir.exists():
return None
if not relinfo_file.is_file() and not version_file.is_file():
return "n/a"
# try to get version from release_info.json first
if relinfo_file.is_file():
with open(relinfo_file, "r") as f:
return str(json.load(f)["version"])
else:
with open(version_file, "r") as f:
return f.readlines()[0]
try:
if relinfo_file.stat().st_size == 0:
raise JSONDecodeError("Empty file", "", 0)
with open(relinfo_file, "r", encoding="utf-8") as f:
data = json.load(f)
raw_version = data.get("version")
if raw_version is not None:
parsed = str(raw_version).strip()
if parsed:
return parsed
except (JSONDecodeError, OSError):
Logger.print_error("Invalid 'release_info.json'")
# fallback to .version file
if version_file.is_file():
try:
with open(version_file, "r") as f:
line = f.readline().strip()
return line or None
except OSError:
Logger.print_error("Unable to read '.version'")
return None
def get_remote_client_version(client: BaseWebClient) -> str | None:
@@ -175,26 +194,39 @@ def get_remote_client_version(client: BaseWebClient) -> str | None:
def backup_client_data(client: BaseWebClient) -> None:
name = client.name
version = ""
src = client.client_dir
dest = client.backup_dir
if src.joinpath(".version").exists():
with open(src.joinpath(".version"), "r") as v:
version = v.readlines()[0]
with open(src.joinpath(".version"), "r") as v:
version = v.readlines()[0]
bm = BackupManager()
bm.backup_directory(f"{name}-{version}", src, dest)
bm.backup_file(client.config_file, dest)
bm.backup_file(NGINX_SITES_AVAILABLE.joinpath(name), dest)
svc = BackupService()
target_path = svc.backup_root.joinpath(f"{client.client_dir.name}_{version}")
svc.backup_directory(
source_path=client.client_dir,
target_path=target_path,
backup_name=client.name,
)
svc.backup_file(
source_path=client.config_file,
target_path=target_path,
)
def backup_client_config_data(client: BaseWebClient) -> None:
client_config = client.client_config
name = client_config.name
source = client_config.config_dir
target = client_config.backup_dir
bm = BackupManager()
bm.backup_directory(name, source, target)
version = ""
src = client.client_dir
if src.joinpath(".version").exists():
with open(src.joinpath(".version"), "r") as v:
version = v.readlines()[0]
svc = BackupService()
target_path = svc.backup_root.joinpath(f"{client.client_dir.name}_{version}")
svc.backup_directory(
source_path=client.client_config.config_dir,
target_path=target_path,
backup_name=client.client_config.name,
)
def get_existing_clients() -> List[BaseWebClient]:
@@ -414,9 +446,9 @@ def get_client_port_selection(
while True:
_type = "Reconfigure" if reconfigure else "Configure"
question = f"{_type} {client.display_name} for port"
port_input = get_number_input(question, min_value=80, default=port)
port_input: int | None = get_number_input(question, min_value=80, default=port)
if port_input not in ports_in_use:
if port_input and port_input not in ports_in_use:
client_settings: WebUiSettings = settings[client.name]
client_settings.port = port_input
settings.save()
@@ -451,3 +483,18 @@ def set_listen_port(client: BaseWebClient, curr_port: int, new_port: int) -> Non
with open(config, "w") as f:
f.writelines(lines)
def create_client_config_symlink(
client_config: BaseWebClientConfig, klipper_instances: List[Klipper]
) -> None:
"""Symlink the client config file into every Klipper instance's config dir."""
for instance in klipper_instances:
Logger.print_status(f"Create symlink for {client_config.config_filename} ...")
source = Path(client_config.config_dir, client_config.config_filename)
target = instance.base.cfg_dir
Logger.print_status(f"Linking {source} to {target}")
try:
create_symlink(source, target)
except Exception:
Logger.print_error("Creating symlink failed!")
+1 -4
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -18,7 +18,6 @@ from components.webui_client.base_data import (
WebClientConfigType,
WebClientType,
)
from core.backup_manager import BACKUP_ROOT_DIR
from core.constants import NGINX_SITES_AVAILABLE
@@ -30,7 +29,6 @@ class FluiddConfigWeb(BaseWebClientConfig):
config_dir: Path = Path.home().joinpath("fluidd-config")
config_filename: str = "fluidd.cfg"
config_section: str = f"include {config_filename}"
backup_dir: Path = BACKUP_ROOT_DIR.joinpath("fluidd-config-backups")
repo_url: str = "https://github.com/fluidd-core/fluidd-config.git"
@@ -43,7 +41,6 @@ class FluiddData(BaseWebClient):
display_name: str = name.capitalize()
client_dir: Path = Path.home().joinpath("fluidd")
config_file: Path = client_dir.joinpath("config.json")
backup_dir: Path = BACKUP_ROOT_DIR.joinpath("fluidd-backups")
repo_path: str = "fluidd-core/fluidd"
nginx_config: Path = NGINX_SITES_AVAILABLE.joinpath("fluidd")
nginx_access_log: Path = Path("/var/log/nginx/fluidd-access.log")
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -18,7 +18,6 @@ from components.webui_client.base_data import (
WebClientConfigType,
WebClientType,
)
from core.backup_manager import BACKUP_ROOT_DIR
from core.constants import NGINX_SITES_AVAILABLE
@@ -30,7 +29,6 @@ class MainsailConfigWeb(BaseWebClientConfig):
config_dir: Path = Path.home().joinpath("mainsail-config")
config_filename: str = "mainsail.cfg"
config_section: str = f"include {config_filename}"
backup_dir: Path = BACKUP_ROOT_DIR.joinpath("mainsail-config-backups")
repo_url: str = "https://github.com/mainsail-crew/mainsail-config.git"
@@ -43,7 +41,6 @@ class MainsailData(BaseWebClient):
display_name: str = name.capitalize()
client_dir: Path = Path.home().joinpath("mainsail")
config_file: Path = client_dir.joinpath("config.json")
backup_dir: Path = BACKUP_ROOT_DIR.joinpath("mainsail-backups")
repo_path: str = "mainsail-crew/mainsail"
nginx_config: Path = NGINX_SITES_AVAILABLE.joinpath("mainsail")
nginx_access_log: Path = Path("/var/log/nginx/mainsail-access.log")
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -12,12 +12,14 @@ import textwrap
from typing import Type
from components.webui_client.base_data import BaseWebClient
from components.webui_client.client_setup import install_client
from components.webui_client.client_utils import (
get_client_port_selection,
get_nginx_listen_port,
set_listen_port,
)
from components.webui_client.services.web_client_setup_service import (
WebClientSetupService,
)
from core.logger import Logger
from core.menus import Option
from core.menus.base_menu import BaseMenu
@@ -65,7 +67,9 @@ class ClientInstallMenu(BaseMenu):
print(menu, end="")
def reinstall_client(self, **kwargs) -> None:
install_client(self.client, settings=self.settings, reinstall=True)
WebClientSetupService(self.client.name).install(
reinstall=True, interactive=True
)
def change_listen_port(self, **kwargs) -> None:
curr_port = self._get_current_port()
@@ -97,7 +101,7 @@ class ClientInstallMenu(BaseMenu):
self.message_service.set_message(message)
def _get_current_port(self) -> int:
curr_port = get_nginx_listen_port(self.client.nginx_config)
curr_port: int | None = get_nginx_listen_port(self.client.nginx_config)
if curr_port is None:
# if the port is not found in the config file we use
# the default port from the kiauh settings as fallback
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -11,8 +11,10 @@ from __future__ import annotations
import textwrap
from typing import Type
from components.webui_client import client_remove
from components.webui_client.base_data import BaseWebClient
from components.webui_client.services.web_client_setup_service import (
WebClientSetupService,
)
from core.menus import Option
from core.menus.base_menu import BaseMenu
from core.types.color import Color
@@ -100,13 +102,12 @@ class ClientRemoveMenu(BaseMenu):
print(Color.apply("Nothing selected ...", Color.RED))
return
completion_msg = client_remove.run_client_removal(
client=self.client,
WebClientSetupService(self.client.name).remove(
remove_client=self.remove_client,
remove_client_cfg=self.remove_client_cfg,
backup_config=self.backup_config_json,
interactive=True,
)
self.message_service.set_message(completion_msg)
self.remove_client = False
self.remove_client_cfg = False
@@ -0,0 +1,105 @@
# ======================================================================= #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
from pathlib import Path
from typing import Any, List
import components.webui_client.menus.client_install_menu as cim_module
import pytest
from components.webui_client.menus.client_install_menu import ClientInstallMenu
class _FakeClient:
def __init__(self, name: str = "mainsail") -> None:
self.name = name
self.display_name = name.capitalize()
self.nginx_config = Path("/tmp/nginx/mainsail")
def _build_menu(monkeypatch: pytest.MonkeyPatch, current_port: int | None = 80) -> ClientInstallMenu:
# Neutralise singletons / IO from BaseMenu and KiauhSettings.
monkeypatch.setattr(cim_module, "KiauhSettings", lambda: _FakeSettings())
monkeypatch.setattr(cim_module, "get_nginx_listen_port", lambda cfg: current_port)
return ClientInstallMenu(_FakeClient())
class _FakeSettings:
def __init__(self) -> None:
self._section = _FakeSection()
self.mainsail = self._section
self.fluidd = self._section
def save(self) -> None:
self._section.saved = True
def __getitem__(self, key):
return self._section
class _FakeSection:
port = 80
saved = False
class TestClientInstallMenu:
def test_options_cover_reinstall_and_port_change(self, monkeypatch) -> None:
menu = _build_menu(monkeypatch)
# BaseMenu may append a "back" footer option depending on the menu's
# footer type; the two install-specific entries must always be present.
assert {"1", "2"}.issubset(menu.options.keys())
def test_set_previous_menu_defaults_to_install_menu(self, monkeypatch) -> None:
menu = _build_menu(monkeypatch)
menu.set_previous_menu(None)
from core.menus.install_menu import InstallMenu
assert menu.previous_menu is InstallMenu
def test_get_current_port_uses_nginx_value(self, monkeypatch) -> None:
menu = _build_menu(monkeypatch, current_port=8080)
assert menu._get_current_port() == 8080
def test_get_current_port_falls_back_to_settings(self, monkeypatch) -> None:
menu = _build_menu(monkeypatch, current_port=None)
# FakeSettings._FakeSection.port == 80
assert menu._get_current_port() == 80
def test_reinstall_delegates_to_web_client_setup_service(self, monkeypatch) -> None:
menu = _build_menu(monkeypatch)
calls: List[Any] = []
class _FakeService:
def install(self, **kwargs) -> bool:
calls.append(kwargs)
return True
monkeypatch.setattr(cim_module, "WebClientSetupService", lambda name: _FakeService())
menu.reinstall_client()
assert calls
assert calls[0]["reinstall"] is True
assert calls[0]["interactive"] is True
def test_change_listen_port_persists_and_restarts_nginx(self, monkeypatch, tmp_path) -> None:
menu = _build_menu(monkeypatch)
captured: dict = {}
monkeypatch.setattr(cim_module, "get_client_port_selection", lambda *a, **k: 9090)
monkeypatch.setattr(cim_module, "cmd_sysctl_service", lambda svc, action: captured.setdefault("nginx", []).append(action))
monkeypatch.setattr(cim_module, "set_listen_port", lambda client, c, n: captured.setdefault("set_port", (c, n)))
monkeypatch.setattr(cim_module, "get_ipv4_addr", lambda: "127.0.0.1")
# Inject a fake message service to avoid the real MessageService.
menu.message_service = type("MS", (), {"set_message": lambda self, m: captured.setdefault("msg", m)})()
menu.change_listen_port()
assert captured["nginx"] == ["stop", "start"]
assert captured["set_port"] == (80, 9090)
assert menu.client_settings.port == 9090
@@ -0,0 +1,63 @@
# ======================================================================= #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import pytest
from components.webui_client.base_data import WebClientType
@dataclass
class FakeClientConfig:
name: str = "mainsail-config"
display_name: str = "Mainsail-Config"
config_filename: str = "mainsail.cfg"
config_section: str = "include mainsail.cfg"
repo_url: str = "https://github.com/mainsail-crew/mainsail-config.git"
config_dir: Path = Path("/tmp/mainsail-config")
@dataclass
class FakeWebClient:
name: str = "mainsail"
display_name: str = "Mainsail"
client: WebClientType = WebClientType.MAINSAIL
client_dir: Path = Path("/tmp/mainsail")
config_file: Path = Path("/tmp/mainsail/config.json")
repo_path: str = "mainsail-crew/mainsail"
nginx_config: Path = Path("/tmp/nginx/mainsail")
nginx_access_log: Path = Path("/tmp/log/mainsail-access.log")
nginx_error_log: Path = Path("/tmp/log/mainsail-error.log")
download_url: str = "https://example.com/mainsail.zip"
client_config: Any = field(default_factory=FakeClientConfig)
@pytest.fixture
def client() -> FakeWebClient:
return FakeWebClient()
@pytest.fixture
def reset_settings(monkeypatch: pytest.MonkeyPatch) -> None:
from core.settings.kiauh_settings import KiauhSettings
KiauhSettings._KiauhSettings__instance = None
KiauhSettings._KiauhSettings__initialized = False
@pytest.fixture
def settings(reset_settings) -> Any:
from core.settings.kiauh_settings import KiauhSettings
return KiauhSettings()
@@ -0,0 +1,415 @@
# ======================================================================= #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, List
import pytest
from components.webui_client.services.web_client_config_setup_service import (
WebClientConfigSetupService,
)
@pytest.fixture
def bind_client(client, monkeypatch: pytest.MonkeyPatch):
"""Make the service construct the per-test FakeWebClient instead of the real data class."""
monkeypatch.setattr(
WebClientConfigSetupService,
"CLIENTS",
{"mainsail": lambda: client, "fluidd": lambda: client},
)
return client
@pytest.fixture
def patched_install_deps(monkeypatch: pytest.MonkeyPatch) -> Dict[str, List[Any]]:
calls: Dict[str, List[Any]] = {
"download": [],
"symlink": [],
"backup_printer": [],
"add_section": [],
"add_section_at_top": [],
"restart": [],
}
module = "components.webui_client.services.web_client_config_setup_service"
monkeypatch.setattr(f"{module}.detect_client_cfg_conflict", lambda c: False)
monkeypatch.setattr(f"{module}.get_instances", lambda model: [])
monkeypatch.setattr(
f"{module}.git_clone_wrapper",
lambda repo, target: calls["download"].append((repo, str(target))),
)
monkeypatch.setattr(
f"{module}.create_client_config_symlink",
lambda cfg, kl: calls["symlink"].append((cfg.name, kl)),
)
class FakeBackup:
def backup_printer_config_dir(self) -> None:
calls["backup_printer"].append(True)
monkeypatch.setattr(f"{module}.BackupService", FakeBackup)
monkeypatch.setattr(
f"{module}.add_config_section",
lambda **kwargs: calls["add_section"].append(kwargs["section"]),
)
monkeypatch.setattr(
f"{module}.add_config_section_at_top",
lambda section, instances: calls["add_section_at_top"].append(section),
)
monkeypatch.setattr(
f"{module}.InstanceManager.restart_all",
staticmethod(lambda instances: calls["restart"].append(len(instances))),
)
return calls
class TestWebClientConfigSetupServiceConstruction:
def test_accepts_known_clients(self) -> None:
for name in ("mainsail", "fluidd"):
svc = WebClientConfigSetupService(name)
assert svc.name == name
def test_rejects_unknown_client(self) -> None:
with pytest.raises(ValueError):
WebClientConfigSetupService("unknown")
def test_clients_mapping_is_the_single_shared_source(self) -> None:
# there must be exactly one CLIENTS dict, imported from
# components.webui_client by both web-client services.
from components import webui_client
from components.webui_client.services.web_client_setup_service import (
WebClientSetupService,
)
assert webui_client.CLIENTS is WebClientConfigSetupService.CLIENTS
assert webui_client.CLIENTS is WebClientSetupService.CLIENTS
assert set(WebClientConfigSetupService.CLIENTS.keys()) == {"mainsail", "fluidd"}
class TestInstallClientConfig:
def test_installs_when_clean(
self, bind_client, patched_install_deps, tmp_path: Path
) -> None:
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
result = WebClientConfigSetupService("mainsail").install()
assert result is True
assert patched_install_deps["download"]
assert patched_install_deps["symlink"]
assert "update_manager mainsail-config" in patched_install_deps["add_section"]
def test_skips_when_conflict_detected(
self, bind_client, patched_install_deps, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
monkeypatch.setattr(f"{module}.detect_client_cfg_conflict", lambda c: True)
result = WebClientConfigSetupService("mainsail").install()
assert result is True
assert patched_install_deps["download"] == []
def test_interactive_reinstall_after_confirm(
self, bind_client, patched_install_deps, monkeypatch, tmp_path: Path
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
bind_client.client_config.config_dir.mkdir(parents=True, exist_ok=True)
removed: List[Path] = []
monkeypatch.setattr(f"{module}.shutil.rmtree", lambda p: removed.append(p))
monkeypatch.setattr(f"{module}.get_confirm", lambda *a, **k: True)
result = WebClientConfigSetupService("mainsail").install(interactive=True)
assert result is True
assert removed == [bind_client.client_config.config_dir]
assert patched_install_deps["download"]
def test_interactive_decline_reinstall_skips(
self, bind_client, patched_install_deps, monkeypatch, tmp_path: Path
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
bind_client.client_config.config_dir.mkdir(parents=True, exist_ok=True)
monkeypatch.setattr(
f"{module}.shutil.rmtree", lambda p: pytest.fail("no rmtree")
)
monkeypatch.setattr(f"{module}.get_confirm", lambda *a, **k: False)
result = WebClientConfigSetupService("mainsail").install(interactive=True)
assert result is True
assert patched_install_deps["download"] == []
def test_non_interactive_existing_dir_skips(
self, bind_client, patched_install_deps, monkeypatch, tmp_path: Path
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
bind_client.client_config.config_dir.mkdir(parents=True, exist_ok=True)
monkeypatch.setattr(
f"{module}.get_confirm",
lambda *a, **k: pytest.fail("should not prompt in headless mode"),
)
result = WebClientConfigSetupService("mainsail").install(interactive=False)
assert result is True
assert patched_install_deps["download"] == []
def test_install_failure_returns_false(
self, bind_client, patched_install_deps, monkeypatch, tmp_path: Path
) -> None:
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
module = "components.webui_client.services.web_client_config_setup_service"
monkeypatch.setattr(
f"{module}.git_clone_wrapper",
lambda *a, **k: (_ for _ in ()).throw(RuntimeError("boom")),
)
result = WebClientConfigSetupService("mainsail").install()
assert result is False
class TestUpdateClientConfig:
def test_update_skips_when_dir_missing(
self, bind_client, monkeypatch, tmp_path: Path
) -> None:
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
module = "components.webui_client.services.web_client_config_setup_service"
pulled: List[Any] = []
monkeypatch.setattr(
f"{module}.git_pull_wrapper", lambda *a, **k: pulled.append("pull")
)
result = WebClientConfigSetupService("mainsail").update()
assert result is True
assert pulled == []
def test_update_pulls_when_dir_exists(
self, bind_client, monkeypatch, tmp_path: Path
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
bind_client.client_config.config_dir.mkdir(parents=True, exist_ok=True)
pulled: List[Any] = []
monkeypatch.setattr(
f"{module}.git_pull_wrapper", lambda *a, **k: pulled.append("pull")
)
monkeypatch.setattr(f"{module}.backup_client_config_data", lambda c: None)
result = WebClientConfigSetupService("mainsail").update()
assert result is True
assert pulled == ["pull"]
def test_update_failure_returns_false(
self, bind_client, monkeypatch, tmp_path: Path
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
bind_client.client_config.config_dir.mkdir(parents=True, exist_ok=True)
monkeypatch.setattr(
f"{module}.git_pull_wrapper",
lambda *a, **k: (_ for _ in ()).throw(RuntimeError("boom")),
)
monkeypatch.setattr(f"{module}.backup_client_config_data", lambda c: None)
result = WebClientConfigSetupService("mainsail").update()
assert result is False
def test_update_non_interactive_omits_restart_hint(
self, bind_client, monkeypatch, tmp_path: Path
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
bind_client.client_config.config_dir.mkdir(parents=True, exist_ok=True)
monkeypatch.setattr(f"{module}.git_pull_wrapper", lambda *a, **k: None)
monkeypatch.setattr(f"{module}.backup_client_config_data", lambda c: None)
printed: List[str] = []
monkeypatch.setattr(
f"{module}.Logger.print_info", lambda msg, *a, **k: printed.append(str(msg))
)
WebClientConfigSetupService("mainsail").update(interactive=False)
assert not any("Restart Klipper" in m for m in printed)
def test_update_interactive_shows_restart_hint(
self, bind_client, monkeypatch, tmp_path: Path
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
bind_client.client_config.config_dir.mkdir(parents=True, exist_ok=True)
monkeypatch.setattr(f"{module}.git_pull_wrapper", lambda *a, **k: None)
monkeypatch.setattr(f"{module}.backup_client_config_data", lambda c: None)
printed: List[str] = []
monkeypatch.setattr(
f"{module}.Logger.print_info", lambda msg, *a, **k: printed.append(str(msg))
)
WebClientConfigSetupService("mainsail").update(interactive=True)
assert any("Restart Klipper" in m for m in printed)
class TestRemoveClientConfig:
def test_remove_signature_rejects_unused_interactive_parameter(
self, bind_client, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
monkeypatch.setattr(f"{module}.get_instances", lambda model: [])
monkeypatch.setattr(f"{module}.run_remove_routines", lambda p: True)
monkeypatch.setattr(f"{module}.remove_config_section", lambda s, i: i)
class FakeBackup:
def backup_moonraker_conf(self) -> None:
pass
def backup_printer_cfg(self) -> None:
pass
monkeypatch.setattr(f"{module}.BackupService", FakeBackup)
monkeypatch.setattr(
f"{module}.MessageService",
lambda: type("MS", (), {"set_message": lambda self, m: None})(),
)
with pytest.raises(TypeError):
WebClientConfigSetupService("mainsail").remove(interactive=True)
def test_remove_runs_dir_and_section_cleanup(
self, bind_client, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
removed: List[str] = []
sections: List[str] = []
monkeypatch.setattr(f"{module}.get_instances", lambda model: [])
monkeypatch.setattr(
f"{module}.run_remove_routines",
lambda p: removed.append(str(p)) or True,
)
monkeypatch.setattr(
f"{module}.remove_config_section",
lambda section, instances: sections.append(section) or instances,
)
class FakeBackup:
def backup_moonraker_conf(self) -> None:
pass
def backup_printer_cfg(self) -> None:
pass
monkeypatch.setattr(f"{module}.BackupService", FakeBackup)
monkeypatch.setattr(
f"{module}.MessageService",
lambda: type("MS", (), {"set_message": lambda self, m: None})(),
)
result = WebClientConfigSetupService("mainsail").remove()
assert result is True
assert any("mainsail-config" in p for p in removed)
def test_remove_failure_returns_false(self, bind_client, monkeypatch) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
monkeypatch.setattr(f"{module}.get_instances", lambda model: [])
monkeypatch.setattr(
f"{module}.run_remove_routines",
lambda p: (_ for _ in ()).throw(RuntimeError("boom")),
)
class FakeBackup:
def backup_moonraker_conf(self) -> None:
pass
def backup_printer_cfg(self) -> None:
pass
monkeypatch.setattr(f"{module}.BackupService", FakeBackup)
monkeypatch.setattr(
f"{module}.MessageService",
lambda: type("MS", (), {"set_message": lambda self, m: None})(),
)
result = WebClientConfigSetupService("mainsail").remove()
assert result is False
class TestRemoveConfig:
"""The config-removal operation mutates the filesystem and returns the
completion message. Its name must reflect that it does the removal, not
merely build a message."""
def test_old_build_removal_message_name_no_longer_exists(self) -> None:
assert not hasattr(WebClientConfigSetupService, "build_removal_message")
def test_remove_config_performs_destructive_removal_and_returns_message(
self, bind_client, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
removed: List[str] = []
monkeypatch.setattr(f"{module}.get_instances", lambda model: [])
monkeypatch.setattr(
f"{module}.run_remove_routines",
lambda p: removed.append(str(p)) or True,
)
monkeypatch.setattr(
f"{module}.remove_config_section",
lambda section, instances: instances,
)
class FakeBackup:
def backup_moonraker_conf(self) -> None:
pass
def backup_printer_cfg(self) -> None:
pass
monkeypatch.setattr(f"{module}.BackupService", FakeBackup)
message = WebClientConfigSetupService("mainsail").remove_config(
kl_instances=[], mr_instances=[], backup_config=False
)
assert removed # destructive removal actually ran
assert message.text # completion message populated
assert any("config" in line.lower() for line in message.text)
def test_remove_config_nothing_to_remove_message(
self, bind_client, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_config_setup_service"
monkeypatch.setattr(f"{module}.get_instances", lambda model: [])
monkeypatch.setattr(f"{module}.run_remove_routines", lambda p: False)
monkeypatch.setattr(
f"{module}.remove_config_section",
lambda section, instances: instances,
)
class FakeBackup:
def backup_moonraker_conf(self) -> None:
pass
def backup_printer_cfg(self) -> None:
pass
monkeypatch.setattr(f"{module}.BackupService", FakeBackup)
message = WebClientConfigSetupService("mainsail").remove_config(
kl_instances=[], mr_instances=[]
)
assert "Nothing to remove." in message.text
@@ -0,0 +1,530 @@
# ======================================================================= #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, List
import pytest
from components.webui_client.base_data import WebClientType
from components.webui_client.services.web_client_setup_service import (
WebClientSetupService,
)
@pytest.fixture
def bind_client(client, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
WebClientSetupService, "CLIENTS", {"mainsail": lambda: client, "fluidd": lambda: client}
)
return client
class FakeInstance:
def __init__(self, suffix: str = "") -> None:
self.suffix = suffix
self.service_file_path = Path(f"service-{suffix}.service")
self.base = type("Base", (), {"log_dir": Path(f"/tmp/log-{suffix}")})()
@pytest.fixture
def patch_install_deps(monkeypatch: pytest.MonkeyPatch) -> Dict[str, List[Any]]:
calls: Dict[str, List[Any]] = {
"download_client": [],
"enable_remotemode": [],
"backup_printer": [],
"add_config_section": [],
"restart_all": [],
"install_client_config": [],
"copy_upstream": [],
"copy_common_vars": [],
"create_nginx_cfg": [],
"symlink_logs": [],
"restart_nginx": [],
}
module = "components.webui_client.services.web_client_setup_service"
monkeypatch.setattr(f"{module}.get_instances", lambda model: [])
monkeypatch.setattr(f"{module}.check_install_dependencies", lambda packages: None)
monkeypatch.setattr(
f"{module}._download_client",
lambda client: calls["download_client"].append(client.name),
)
monkeypatch.setattr(
f"{module}.enable_mainsail_remotemode",
lambda: calls["enable_remotemode"].append(True),
)
class FakeBackup:
def backup_printer_config_dir(self) -> None:
calls["backup_printer"].append(True)
def backup_moonraker_conf(self) -> None:
calls["backup_printer"].append("moonraker_conf")
monkeypatch.setattr(f"{module}.BackupService", FakeBackup)
monkeypatch.setattr(
f"{module}.add_config_section",
lambda **kwargs: calls["add_config_section"].append(kwargs),
)
monkeypatch.setattr(
f"{module}.InstanceManager.restart_all",
staticmethod(lambda instances: calls["restart_all"].append(len(instances))),
)
monkeypatch.setattr(
f"{module}.WebClientConfigSetupService",
lambda name: type(
"FakeCfgSvc",
(),
{
"install": lambda self, cfg_backup=True, interactive=True: (
calls["install_client_config"].append((name, cfg_backup, interactive))
or True
)
},
)(),
)
monkeypatch.setattr(
f"{module}.copy_upstream_nginx_cfg", lambda: calls["copy_upstream"].append(True)
)
monkeypatch.setattr(
f"{module}.copy_common_vars_nginx_cfg",
lambda: calls["copy_common_vars"].append(True),
)
monkeypatch.setattr(
f"{module}.create_nginx_cfg",
lambda **kwargs: calls["create_nginx_cfg"].append(kwargs),
)
monkeypatch.setattr(
f"{module}.symlink_webui_nginx_log",
lambda client, instances: calls["symlink_logs"].append(
(client.name, len(instances))
),
)
monkeypatch.setattr(
f"{module}.cmd_sysctl_service",
lambda service, action: calls["restart_nginx"].append((service, action)),
)
return calls
class TestWebClientSetupServiceConstruction:
@pytest.mark.parametrize("name", ["mainsail", "fluidd"])
def test_accepts_known_clients(self, name: str) -> None:
svc = WebClientSetupService(name)
assert svc.name == name
def test_rejects_unknown_client(self) -> None:
with pytest.raises(ValueError):
WebClientSetupService("unknown")
class TestInstallClient:
def test_interactive_install_runs_all_steps(
self, bind_client, patch_install_deps, monkeypatch
) -> None:
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_client_port_selection",
lambda c, s, reconfigure=False: 80,
)
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_confirm",
lambda *a, **k: True,
)
result = WebClientSetupService("mainsail").install()
assert result is True
assert patch_install_deps["download_client"] == ["mainsail"]
assert patch_install_deps["create_nginx_cfg"]
assert patch_install_deps["restart_nginx"] == [("nginx", "restart")]
def test_headless_install_uses_explicit_port_and_cfg(
self, bind_client, patch_install_deps, monkeypatch, tmp_path: Path
) -> None:
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_confirm",
lambda *a, **k: pytest.fail("should not prompt in headless mode"),
)
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_client_port_selection",
lambda *a, **k: pytest.fail("should not select port interactively"),
)
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_instances",
lambda model: [FakeInstance()] if model.__name__ == "Klipper" else [],
)
bind_client.client_config.config_dir = tmp_path / "mainsail-config"
result = WebClientSetupService("mainsail").install(
interactive=False, port=8080, install_client_cfg=True, continue_without_moonraker=True
)
assert result is True
assert patch_install_deps["download_client"] == ["mainsail"]
assert patch_install_deps["install_client_config"] == [("mainsail", False, False)]
nginx_call = patch_install_deps["create_nginx_cfg"][0]
assert nginx_call["PORT"] == 8080
def test_reinstall_uses_default_port_without_prompting(
self, bind_client, patch_install_deps, monkeypatch
) -> None:
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_instances",
lambda model: [FakeInstance()] if model.__name__ == "Moonraker" else [],
)
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_client_port_selection",
lambda *a, **k: pytest.fail("should not prompt for port during reinstall"),
)
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_confirm",
lambda *a, **k: pytest.fail("should not prompt during reinstall"),
)
result = WebClientSetupService("mainsail").install(reinstall=True, interactive=True)
assert result is True
nginx_call = patch_install_deps["create_nginx_cfg"][0]
assert nginx_call["PORT"] == 80
def test_reinstall_explicit_port_overrides_default(
self, bind_client, patch_install_deps, monkeypatch
) -> None:
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_instances",
lambda model: [FakeInstance()] if model.__name__ == "Moonraker" else [],
)
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_client_port_selection",
lambda *a, **k: pytest.fail("should not prompt when port is explicit"),
)
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.get_confirm",
lambda *a, **k: pytest.fail("should not prompt during reinstall"),
)
result = WebClientSetupService("mainsail").install(
reinstall=True, interactive=True, port=9090
)
assert result is True
nginx_call = patch_install_deps["create_nginx_cfg"][0]
assert nginx_call["PORT"] == 9090
def test_headless_install_without_moonraker_returns_false(
self, bind_client, patch_install_deps
) -> None:
result = WebClientSetupService("mainsail").install(
interactive=False, continue_without_moonraker=False
)
assert result is False
assert patch_install_deps["download_client"] == []
def test_install_failure_returns_false(
self, bind_client, patch_install_deps, monkeypatch
) -> None:
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service._download_client",
lambda client: (_ for _ in ()).throw(RuntimeError("boom")),
)
result = WebClientSetupService("mainsail").install(
interactive=False, continue_without_moonraker=True
)
assert result is False
def test_headless_install_failure_does_not_show_error_dialog(
self, bind_client, patch_install_deps, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_setup_service"
monkeypatch.setattr(
f"{module}._download_client",
lambda client: (_ for _ in ()).throw(RuntimeError("boom")),
)
monkeypatch.setattr(
f"{module}.Logger.print_dialog",
lambda *a, **k: pytest.fail("should not show error dialog in headless mode"),
)
result = WebClientSetupService("mainsail").install(
interactive=False, continue_without_moonraker=True
)
assert result is False
def test_headless_install_does_not_show_completion_dialog(
self, bind_client, patch_install_deps, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_setup_service"
monkeypatch.setattr(
f"{module}.get_confirm",
lambda *a, **k: pytest.fail("should not prompt in headless mode"),
)
monkeypatch.setattr(
f"{module}.Logger.print_dialog",
lambda *a, **k: pytest.fail("should not show dialog in headless mode"),
)
result = WebClientSetupService("mainsail").install(
interactive=False, continue_without_moonraker=True
)
assert result is True
def test_interactive_install_shows_completion_dialog(
self, bind_client, patch_install_deps, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_setup_service"
monkeypatch.setattr(
f"{module}.get_confirm", lambda *a, **k: True
)
monkeypatch.setattr(
f"{module}.get_client_port_selection",
lambda c, s, reconfigure=False: 80,
)
dialog_calls: List[Any] = []
monkeypatch.setattr(
f"{module}.Logger.print_dialog",
lambda *a, **k: dialog_calls.append(k),
)
WebClientSetupService("mainsail").install(interactive=True)
assert dialog_calls
class TestUpdateClient:
def test_update_downloads_and_restores_config(
self, bind_client, monkeypatch
) -> None:
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service._download_client",
lambda c: None,
)
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service.shutil.copy",
lambda src, dst: None,
)
bind_client.client_dir.mkdir(parents=True, exist_ok=True)
bind_client.config_file.write_text("{}")
result = WebClientSetupService("mainsail").update()
assert result is True
def test_update_missing_dir_returns_true(
self, bind_client, monkeypatch, tmp_path: Path
) -> None:
bind_client.client_dir = tmp_path / "does-not-exist"
pulled: List[Any] = []
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service._download_client",
lambda c: pulled.append("download"),
)
result = WebClientSetupService("mainsail").update()
assert result is True
assert pulled == []
def test_update_failure_returns_false(
self, bind_client, monkeypatch
) -> None:
bind_client.client_dir.mkdir(parents=True, exist_ok=True)
bind_client.config_file.write_text("{}")
monkeypatch.setattr(
"components.webui_client.services.web_client_setup_service._download_client",
lambda c: (_ for _ in ()).throw(RuntimeError("boom")),
)
result = WebClientSetupService("mainsail").update()
assert result is False
def test_update_accepts_interactive_parameter(
self, bind_client, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_setup_service"
bind_client.client_dir.mkdir(parents=True, exist_ok=True)
bind_client.config_file.write_text("{}")
monkeypatch.setattr(f"{module}._download_client", lambda c: None)
monkeypatch.setattr(f"{module}.shutil.copy", lambda s, d: None)
result = WebClientSetupService("mainsail").update(interactive=False)
assert result is True
def test_update_headless_does_not_show_dialog(
self, bind_client, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_setup_service"
bind_client.client_dir.mkdir(parents=True, exist_ok=True)
bind_client.config_file.write_text("{}")
monkeypatch.setattr(f"{module}._download_client", lambda c: None)
monkeypatch.setattr(f"{module}.shutil.copy", lambda s, d: None)
monkeypatch.setattr(
f"{module}.Logger.print_dialog",
lambda *a, **k: pytest.fail("should not show dialog in headless update"),
)
result = WebClientSetupService("mainsail").update(interactive=False)
assert result is True
class TestRemoveClientHelpers:
"""Directly exercise the small removal helper methods so the destructive
remove path is covered beyond the integrated ``remove()`` test."""
def test_remove_client_dir_returns_run_remove_result(self, bind_client, monkeypatch) -> None:
module = "components.webui_client.services.web_client_setup_service"
monkeypatch.setattr(
f"{module}.run_remove_routines", lambda p: True
)
svc = WebClientSetupService("mainsail")
assert svc._remove_client_dir() is True
def test_remove_client_nginx_config_delegates_to_sudo(self, bind_client, monkeypatch) -> None:
module = "components.webui_client.services.web_client_setup_service"
removed: List[Any] = []
monkeypatch.setattr(
f"{module}.remove_with_sudo", lambda files: removed.append(files) or True
)
svc = WebClientSetupService("mainsail")
assert svc._remove_client_nginx_config("mainsail") is True
assert removed # files passed through
def test_remove_client_nginx_logs_appends_per_instance_paths(
self, bind_client, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_setup_service"
passed: List[Any] = []
monkeypatch.setattr(
f"{module}.remove_with_sudo", lambda files: passed.append(files) or True
)
class FakeKlipperInstance:
def __init__(self, suffix: str) -> None:
self.suffix = suffix
self.base = type("Base", (), {"log_dir": Path(f"/tmp/log-{suffix}")})()
svc = WebClientSetupService("mainsail")
result = svc._remove_client_nginx_logs(
svc.client, [FakeKlipperInstance("a"), FakeKlipperInstance("b")]
)
assert result is True
# 2 base log files + 2 per instance * 2 = 6 files total
assert len(passed[0]) == 6
class TestRemoteModeLogic:
@pytest.mark.parametrize(
"client_name, instance_count, expected",
[
("mainsail", 0, True),
("mainsail", 1, False),
("mainsail", 2, True),
("fluidd", 0, False),
("fluidd", 2, False),
],
)
def test_should_enable_remote_mode(
self, client_name: str, instance_count: int, expected: bool
) -> None:
svc = WebClientSetupService(client_name)
mr_instances = [FakeInstance(str(i)) for i in range(instance_count)]
result = svc._should_enable_remote_mode(mr_instances)
assert result is expected
def test_should_enable_remote_mode_rejects_non_mainsail(
self) -> None:
svc = WebClientSetupService("mainsail")
svc.client = type("NotMainsail", (), {"client": WebClientType.FLUIDD})()
assert svc._should_enable_remote_mode([]) is False
class TestRemoveClient:
def test_remove_client_and_config(
self, bind_client, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_setup_service"
removed_dir: List[str] = []
sections: List[str] = []
monkeypatch.setattr(f"{module}.get_instances", lambda model: [])
monkeypatch.setattr(
f"{module}.run_remove_routines",
lambda p: removed_dir.append(str(p)) or True,
)
monkeypatch.setattr(f"{module}.remove_with_sudo", lambda files: True)
class FakeBackup:
def backup_moonraker_conf(self) -> None:
pass
def backup_file(self, **kwargs) -> bool:
return True
monkeypatch.setattr(f"{module}.BackupService", FakeBackup)
monkeypatch.setattr(
f"{module}.remove_config_section",
lambda section, instances: sections.append(section) or instances,
)
build_called: List[Any] = []
monkeypatch.setattr(
f"{module}.WebClientConfigSetupService",
lambda name: type(
"FakeCfgSvc",
(),
{
"remove_config": lambda self, kl_instances, mr_instances, backup_config=True, svc=None: (
build_called.append(name) or type(
"Msg", (), {"color": 2, "text": ["x", "config removed"]}
)()
)
},
)(),
)
monkeypatch.setattr(
f"{module}.MessageService",
lambda: type("MS", (), {"set_message": lambda self, m: None})(),
)
result = WebClientSetupService("mainsail").remove(
remove_client=True, remove_client_cfg=True, backup_config=False
)
assert result is True
assert build_called == ["mainsail"]
assert "update_manager mainsail" in sections
def test_remove_failure_returns_false(
self, bind_client, monkeypatch
) -> None:
module = "components.webui_client.services.web_client_setup_service"
monkeypatch.setattr(f"{module}.get_instances", lambda model: [])
monkeypatch.setattr(
f"{module}.run_remove_routines",
lambda p: (_ for _ in ()).throw(RuntimeError("boom")),
)
monkeypatch.setattr(
f"{module}.MessageService",
lambda: type("MS", (), {"set_message": lambda self, m: None})(),
)
result = WebClientSetupService("mainsail").remove(
remove_client=True, remove_client_cfg=False, backup_config=False
)
assert result is False
@@ -0,0 +1,250 @@
# ======================================================================= #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
import shutil
import traceback
from typing import List
from components.klipper.klipper import Klipper
from components.moonraker.moonraker import Moonraker
from components.webui_client import CLIENTS
from components.webui_client.base_data import BaseWebClient, BaseWebClientConfig
from components.webui_client.client_dialogs import print_client_already_installed_dialog
from components.webui_client.client_utils import (
backup_client_config_data,
create_client_config_symlink,
detect_client_cfg_conflict,
)
from core.instance_manager.instance_manager import InstanceManager
from core.logger import Logger
from core.services.backup_service import BackupService
from core.services.message_service import Message, MessageService
from core.settings.kiauh_settings import KiauhSettings
from core.types.color import Color
from utils.config_utils import (
add_config_section,
add_config_section_at_top,
remove_config_section,
)
from utils.fs_utils import run_remove_routines
from utils.git_utils import git_clone_wrapper, git_pull_wrapper
from utils.input_utils import get_confirm
from utils.instance_utils import get_instances
class WebClientConfigSetupService:
"""Headless-capable service for installing, updating and removing web client configs."""
CLIENTS = CLIENTS
def __init__(self, name: str) -> None:
if name not in self.CLIENTS:
raise ValueError(f"Unknown web client: {name}")
self.name = name
self.client: BaseWebClient = self.CLIENTS[name]()
self.settings = KiauhSettings()
def install(
self,
cfg_backup: bool = True,
interactive: bool = True,
) -> bool:
"""Install the client config for this service's client.
Returns ``True`` on success or when the install is legitimately skipped
(conflict or already installed), and ``False`` when installation fails.
"""
client_config: BaseWebClientConfig = self.client.client_config
display_name = client_config.display_name
if detect_client_cfg_conflict(self.client):
Logger.print_info("Another Client-Config is already installed! Skipped ...")
return True
if client_config.config_dir.exists():
if interactive:
print_client_already_installed_dialog(display_name)
if get_confirm(f"Re-install {display_name}?", allow_go_back=True):
shutil.rmtree(client_config.config_dir)
else:
return True
else:
Logger.print_info(
f"{display_name} is already installed; "
"skipping non-interactive install."
)
return True
mr_instances: List[Moonraker] = get_instances(Moonraker)
kl_instances: List[Klipper] = get_instances(Klipper)
try:
self.__download_client_config(client_config)
create_client_config_symlink(client_config, kl_instances)
if cfg_backup:
BackupService().backup_printer_config_dir()
add_config_section(
section=f"update_manager {client_config.name}",
instances=mr_instances,
options=[
("type", "git_repo"),
("primary_branch", "master"),
("path", str(client_config.config_dir)),
("origin", str(client_config.repo_url)),
("managed_services", "klipper"),
],
)
add_config_section_at_top(client_config.config_section, kl_instances)
InstanceManager.restart_all(kl_instances)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error(f"{display_name} installation failed!")
return False
Logger.print_ok(f"{display_name} installation complete!", start="\n")
return True
def update(self, interactive: bool = True) -> bool:
"""Update the client config. Honors ``interactive`` to gate the
post-update "Restart Klipper" hint.
"""
client_config: BaseWebClientConfig = self.client.client_config
Logger.print_status(f"Updating {client_config.display_name} ...")
if not client_config.config_dir.exists():
Logger.print_info(
f"Unable to update {client_config.display_name}. "
"Directory does not exist! Skipping ..."
)
return True
if self.settings.kiauh.backup_before_update:
backup_client_config_data(self.client)
try:
git_pull_wrapper(client_config.config_dir)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error(f"Updating {client_config.display_name} failed!")
return False
Logger.print_ok(f"Successfully updated {client_config.display_name}.")
if interactive:
Logger.print_info("Restart Klipper to reload the configuration!")
return True
def remove(
self,
backup_config: bool = True,
) -> bool:
"""Remove the client config dir, symlinks and config sections.
Returns ``True`` on success and ``False`` if removal failed.
"""
client_config: BaseWebClientConfig = self.client.client_config
try:
message = self.remove_config(
kl_instances=get_instances(Klipper),
mr_instances=get_instances(Moonraker),
backup_config=backup_config,
)
MessageService().set_message(message)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error(f"Error while removing {client_config.display_name}!")
return False
return True
def remove_config(
self,
kl_instances: List[Klipper],
mr_instances: List[Moonraker],
backup_config: bool = True,
svc: BackupService | None = None,
) -> Message:
"""Remove the client config dir, its symlinks and config sections.
This method performs the actual (destructive) removal work and returns
the resulting completion ``Message``. It is named ``remove_config``
(not ``build_*``) so the call site obviously mutates the filesystem.
``WebClientSetupService.remove`` merges this message into the combined
client-removal message without double-setting it.
"""
client_config: BaseWebClientConfig = self.client.client_config
completion_msg = Message(
title=f"{client_config.display_name} Removal Process completed",
color=Color.GREEN,
)
Logger.print_status(f"Removing {client_config.display_name} ...")
if run_remove_routines(client_config.config_dir):
completion_msg.text.append(f"{client_config.display_name} removed")
if svc is None:
svc = BackupService()
svc.backup_moonraker_conf()
self.__remove_moonraker_config_section(
completion_msg, client_config, mr_instances
)
svc.backup_printer_cfg()
self.__remove_printer_config_section(
completion_msg, client_config, kl_instances
)
if completion_msg.text:
completion_msg.text.insert(0, "The following actions were performed:")
else:
completion_msg.color = Color.YELLOW
completion_msg.centered = True
completion_msg.text = ["Nothing to remove."]
return completion_msg
def __download_client_config(self, client_config: BaseWebClientConfig) -> None:
Logger.print_status(f"Downloading {client_config.display_name} ...")
git_clone_wrapper(client_config.repo_url, client_config.config_dir)
@staticmethod
def __update_msg(instances: list, message: Message, text: str) -> Message:
if not instances:
return message
instance_names = [i.service_file_path.stem for i in instances]
message.text.append(f"{text}: {', '.join(instance_names)}")
return message
def __remove_printer_config_section(
self,
message: Message,
client_config: BaseWebClientConfig,
kl_instances: List[Klipper],
) -> None:
kl_section = client_config.config_section
handled = remove_config_section(kl_section, kl_instances)
self.__update_msg(
handled,
message,
f"Klipper config section '{kl_section}' removed for instance",
)
def __remove_moonraker_config_section(
self,
message: Message,
client_config: BaseWebClientConfig,
mr_instances: List[Moonraker],
) -> None:
mr_section = f"update_manager {client_config.name}"
handled = remove_config_section(mr_section, mr_instances)
self.__update_msg(
handled,
message,
f"Moonraker config section '{mr_section}' removed for instance",
)
@@ -0,0 +1,365 @@
# ======================================================================= #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
import shutil
import tempfile
import traceback
from pathlib import Path
from typing import List
from components.klipper.klipper import Klipper
from components.moonraker.moonraker import Moonraker
from components.webui_client import CLIENTS, MODULE_PATH
from components.webui_client.base_data import BaseWebClient, WebClientType
from components.webui_client.client_dialogs import (
print_install_client_config_dialog,
print_moonraker_not_found_dialog,
)
from components.webui_client.client_utils import (
copy_common_vars_nginx_cfg,
copy_upstream_nginx_cfg,
create_nginx_cfg,
detect_client_cfg_conflict,
enable_mainsail_remotemode,
get_client_port_selection,
symlink_webui_nginx_log,
)
from components.webui_client.services.web_client_config_setup_service import (
WebClientConfigSetupService,
)
from core.constants import NGINX_SITES_AVAILABLE, NGINX_SITES_ENABLED
from core.instance_manager.instance_manager import InstanceManager
from core.logger import DialogType, Logger
from core.services.backup_service import BackupService
from core.services.message_service import Message, MessageService
from core.settings.kiauh_settings import KiauhSettings
from core.types.color import Color
from utils.common import check_install_dependencies
from utils.config_utils import add_config_section, remove_config_section
from utils.fs_utils import remove_with_sudo, run_remove_routines, unzip
from utils.input_utils import get_confirm
from utils.instance_utils import get_instances
from utils.sys_utils import cmd_sysctl_service, download_file, get_ipv4_addr
class WebClientSetupService:
"""Headless-capable service for installing, updating and removing web clients."""
CLIENTS = CLIENTS
def __init__(self, name: str) -> None:
if name not in self.CLIENTS:
raise ValueError(f"Unknown web client: {name}")
self.name = name
self.client: BaseWebClient = self.CLIENTS[name]()
self.settings = KiauhSettings()
def install(
self,
reinstall: bool = False,
interactive: bool = True,
port: int | None = None,
install_client_cfg: bool | None = None,
continue_without_moonraker: bool = False,
) -> bool:
"""Install the web client.
When called from the TUI, choices are prompted interactively. The CLI
passes explicit values and ``interactive=False``.
Returns ``True`` on success and ``False`` when the installation could
not be completed.
"""
mr_instances: List[Moonraker] = get_instances(Moonraker)
enable_remotemode = False
if not mr_instances:
if interactive:
print_moonraker_not_found_dialog(self.client.display_name)
if not get_confirm(
f"Continue {self.client.display_name} installation?"
):
return False
elif not continue_without_moonraker:
Logger.print_info(
f"Moonraker not installed; skipping {self.client.display_name} installation."
)
return False
enable_remotemode = self._should_enable_remote_mode(mr_instances)
kl_instances: List[Klipper] = get_instances(Klipper)
install_cfg = False
client_config = self.client.client_config
if (
kl_instances
and not client_config.config_dir.exists()
and not detect_client_cfg_conflict(self.client)
):
if interactive:
print_install_client_config_dialog(self.client)
question = f"Download the recommended {client_config.display_name}?"
install_cfg = get_confirm(question, allow_go_back=False)
else:
install_cfg = bool(install_client_cfg)
default_port: int = int(self.settings.get(self.client.name, "port"))
if port is not None:
resolved_port = port
elif interactive and not reinstall:
resolved_port = get_client_port_selection(self.client, self.settings)
else:
resolved_port = default_port
check_install_dependencies({"nginx"})
try:
_download_client(self.client)
if enable_remotemode and self.client.client == WebClientType.MAINSAIL:
enable_mainsail_remotemode()
BackupService().backup_printer_config_dir()
add_config_section(
section=f"update_manager {self.client.name}",
instances=mr_instances,
options=[
("persistent_files", ["config.json"]),
("type", "web"),
("channel", "stable"),
("repo", str(self.client.repo_path)),
("path", str(self.client.client_dir)),
],
)
InstanceManager.restart_all(mr_instances)
if install_cfg and kl_instances:
WebClientConfigSetupService(self.name).install(
cfg_backup=False, interactive=interactive
)
copy_upstream_nginx_cfg()
copy_common_vars_nginx_cfg()
create_nginx_cfg(
display_name=self.client.display_name,
cfg_name=self.client.name,
template_src=MODULE_PATH.joinpath("assets/nginx_cfg"),
PORT=resolved_port,
ROOT_DIR=self.client.client_dir,
NAME=self.client.name,
)
if kl_instances:
symlink_webui_nginx_log(self.client, kl_instances)
cmd_sysctl_service("nginx", "restart")
except Exception:
Logger.print_error(traceback.format_exc())
if interactive:
Logger.print_dialog(
DialogType.ERROR,
center_content=True,
content=[f"{self.client.display_name} installation failed!"],
)
return False
webui_url: str = f"http://{get_ipv4_addr()}{'' if resolved_port == 80 else f':{resolved_port}'}"
if interactive:
Logger.print_dialog(
DialogType.CUSTOM,
custom_title=f"{self.client.display_name} installation complete!",
custom_color=Color.GREEN,
center_content=True,
content=[f"Open {self.client.display_name} now on: {webui_url}"],
)
else:
Logger.print_info(
f"Installation of {self.client.display_name} complete! URL: {webui_url}"
)
return True
def _should_enable_remote_mode(self, mr_instances: List[Moonraker]) -> bool:
"""Return whether Mainsail remote mode should be enabled.
Remote mode is required when Mainsail is installed without a local
Moonraker instance or when more than one Moonraker instance exists.
"""
return self.client.client == WebClientType.MAINSAIL and (
not mr_instances or len(mr_instances) > 1
)
def update(self, interactive: bool = True) -> bool:
"""Update the web client. Returns ``True`` on success, ``False`` on failure."""
Logger.print_status(f"Updating {self.client.display_name} ...")
if not self.client.client_dir.exists():
Logger.print_info(
f"Unable to update {self.client.display_name}. "
"Directory does not exist! Skipping ..."
)
return True
try:
with tempfile.NamedTemporaryFile(suffix=".json") as tmp_file:
Logger.print_status(
f"Creating temporary backup of {self.client.config_file} "
f"as {tmp_file.name} ..."
)
shutil.copy(self.client.config_file, tmp_file.name)
_download_client(self.client)
shutil.copy(tmp_file.name, self.client.config_file)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error(f"Updating {self.client.display_name} failed!")
return False
return True
def remove(
self,
remove_client: bool = False,
remove_client_cfg: bool = False,
backup_config: bool = True,
interactive: bool = True,
) -> bool:
"""Remove the web client and (optionally) its config.
Returns ``True`` on success and ``False`` if removal failed.
"""
try:
message = self._build_removal_message(
remove_client=remove_client,
remove_client_cfg=remove_client_cfg,
backup_config=backup_config,
interactive=interactive,
)
MessageService().set_message(message)
except Exception:
Logger.print_error(traceback.format_exc())
Logger.print_error(f"Error while removing {self.client.display_name}!")
return False
return True
def _build_removal_message(
self,
remove_client: bool,
remove_client_cfg: bool,
backup_config: bool,
interactive: bool,
) -> Message:
completion_msg = Message(
title=f"{self.client.display_name} Removal Process completed",
color=Color.GREEN,
)
mr_instances: List[Moonraker] = get_instances(Moonraker)
kl_instances: List[Klipper] = get_instances(Klipper)
svc = BackupService()
if backup_config:
version = ""
src = self.client.client_dir
if src.joinpath(".version").exists():
with open(src.joinpath(".version"), "r") as v:
version = v.readlines()[0]
target_path = svc.backup_root.joinpath(
f"{self.client.client_dir.name}_{version}"
)
success = svc.backup_file(
source_path=self.client.config_file,
target_path=target_path,
)
if success:
completion_msg.text.append(
f"{self.client.config_file.name} backup created"
)
if remove_client:
if self._remove_client_dir():
completion_msg.text.append(f"{self.client.display_name} removed")
if self._remove_client_nginx_config(self.client.name):
completion_msg.text.append("● NGINX config removed")
if self._remove_client_nginx_logs(self.client, kl_instances):
completion_msg.text.append("● NGINX logs removed")
svc.backup_moonraker_conf()
section = f"update_manager {self.client.name}"
handled_instances = remove_config_section(section, mr_instances)
if handled_instances:
names = [i.service_file_path.stem for i in handled_instances]
completion_msg.text.append(
f"● Moonraker config section '{section}' removed for "
f"instance: {', '.join(names)}"
)
if remove_client_cfg:
cfg_svc = WebClientConfigSetupService(self.name)
cfg_message = cfg_svc.remove_config(
kl_instances=kl_instances,
mr_instances=mr_instances,
backup_config=backup_config,
svc=svc,
)
if cfg_message.color == Color.GREEN:
completion_msg.text.extend(cfg_message.text[1:])
if not completion_msg.text:
completion_msg.color = Color.YELLOW
completion_msg.centered = True
completion_msg.text.append("Nothing to remove.")
else:
completion_msg.text.insert(0, "The following actions were performed:")
return completion_msg
def _remove_client_dir(self) -> bool:
Logger.print_status(f"Removing {self.client.display_name} ...")
return bool(run_remove_routines(self.client.client_dir))
def _remove_client_nginx_config(self, name: str) -> bool:
Logger.print_status(f"Removing NGINX config for {name.capitalize()} ...")
return bool(
remove_with_sudo([
NGINX_SITES_AVAILABLE.joinpath(name),
NGINX_SITES_ENABLED.joinpath(name),
])
)
def _remove_client_nginx_logs(
self, client: BaseWebClient, instances: List[Klipper]
) -> bool:
Logger.print_status(f"Removing NGINX logs for {client.display_name} ...")
files = [client.nginx_access_log, client.nginx_error_log]
if instances:
for instance in instances:
files.append(
instance.base.log_dir.joinpath(client.nginx_access_log.name)
)
files.append(
instance.base.log_dir.joinpath(client.nginx_error_log.name)
)
return bool(remove_with_sudo(files))
def _download_client(client: BaseWebClient) -> None:
zipfile = f"{client.name.lower()}.zip"
target = Path().home().joinpath(zipfile)
try:
Logger.print_status(
f"Downloading {client.display_name} from {client.download_url} ..."
)
download_file(client.download_url, target, True)
Logger.print_ok("Download complete!")
Logger.print_status(f"Extracting {zipfile} ...")
unzip(target, client.client_dir)
target.unlink(missing_ok=True)
Logger.print_ok("OK!")
except Exception:
Logger.print_error(f"Downloading {client.display_name} failed!")
raise
@@ -0,0 +1,49 @@
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import pytest
from components.webui_client.base_data import WebClientType
@dataclass
class FakeClientConfig:
name: str = "mainsail-config"
display_name: str = "Mainsail-Config"
config_dir: Path = Path("/tmp/mainsail-config")
config_filename: str = "mainsail.cfg"
config_section: str = "include mainsail.cfg"
repo_url: str = "https://github.com/mainsail-crew/mainsail-config.git"
@dataclass
class FakeWebClient:
name: str = "mainsail"
display_name: str = "Mainsail"
client: WebClientType = WebClientType.MAINSAIL
client_dir: Path = Path("/tmp/mainsail")
config_file: Path = Path("/tmp/mainsail/config.json")
repo_path: str = "mainsail-crew/mainsail"
nginx_config: Path = Path("/tmp/nginx/mainsail")
nginx_access_log: Path = Path("/tmp/log/mainsail-access.log")
nginx_error_log: Path = Path("/tmp/log/mainsail-error.log")
download_url: str = "https://example.com/mainsail.zip"
client_config: Any = field(default_factory=FakeClientConfig)
@pytest.fixture
def client() -> FakeWebClient:
return FakeWebClient()
@pytest.fixture
def settings(monkeypatch: pytest.MonkeyPatch) -> Any:
from core.settings.kiauh_settings import KiauhSettings
KiauhSettings._KiauhSettings__instance = None
KiauhSettings._KiauhSettings__initialized = False
return KiauhSettings()
@@ -0,0 +1,348 @@
from __future__ import annotations
from pathlib import Path
from typing import Any, List
import pytest
from components.webui_client import client_utils
from components.webui_client.base_data import WebClientType
from components.webui_client.client_utils import (
backup_client_config_data,
backup_client_data,
create_client_config_symlink,
detect_client_cfg_conflict,
get_client_status,
get_current_client_config,
get_download_url,
get_local_client_version,
get_next_free_port,
get_nginx_listen_port,
get_remote_client_version,
read_ports_from_nginx_configs,
set_listen_port,
)
class TestGetLocalClientVersion:
def test_returns_none_when_client_dir_missing(self, client) -> None:
client.client_dir = Path("/does/not/exist")
assert get_local_client_version(client) is None
def test_reads_release_info_json(self, client, tmp_path: Path) -> None:
client.client_dir = tmp_path
release = tmp_path / "release_info.json"
release.write_text('{"version": "v2.0.0"}')
assert get_local_client_version(client) == "v2.0.0"
def test_falls_back_to_version_file(self, client, tmp_path: Path) -> None:
client.client_dir = tmp_path
(tmp_path / ".version").write_text("v1.2.3\n")
assert get_local_client_version(client) == "v1.2.3"
def test_returns_none_for_empty_version_file(self, client, tmp_path: Path) -> None:
client.client_dir = tmp_path
(tmp_path / ".version").write_text("")
assert get_local_client_version(client) is None
class TestGetRemoteClientVersion:
def test_returns_tag_when_available(self, monkeypatch, client) -> None:
monkeypatch.setattr(
client_utils, "get_latest_remote_tag", lambda repo: "v3.0.0"
)
assert get_remote_client_version(client) == "v3.0.0"
def test_returns_none_when_tag_empty(self, monkeypatch, client) -> None:
monkeypatch.setattr(client_utils, "get_latest_remote_tag", lambda repo: "")
assert get_remote_client_version(client) is None
def test_returns_none_on_error(self, monkeypatch, client) -> None:
monkeypatch.setattr(
client_utils,
"get_latest_remote_tag",
lambda repo: (_ for _ in ()).throw(RuntimeError("network")),
)
assert get_remote_client_version(client) is None
class TestGetDownloadUrl:
def test_returns_stable_url_when_not_unstable(self, monkeypatch, client) -> None:
class FakeSettings:
def get(self, name, key):
return False
monkeypatch.setattr(client_utils, "KiauhSettings", FakeSettings)
url = get_download_url("https://example.com/repo", client)
assert "latest/download" in url
def test_returns_unstable_url_when_available(self, monkeypatch, client) -> None:
class FakeSettings:
def get(self, name, key):
return True
monkeypatch.setattr(client_utils, "KiauhSettings", FakeSettings)
monkeypatch.setattr(
client_utils, "get_latest_unstable_tag", lambda repo: "v9.9.9"
)
url = get_download_url("https://example.com/repo", client)
assert "v9.9.9" in url
class TestDetectClientCfgConflict:
def test_mainsail_conflicts_with_fluidd_installed(
self, monkeypatch, client
) -> None:
def fake_status(c):
code = 2 if c.client == WebClientType.FLUIDD else 0
return type("S", (), {"status": code})()
monkeypatch.setattr(client_utils, "get_client_config_status", fake_status)
client.client = WebClientType.MAINSAIL
assert detect_client_cfg_conflict(client) is True
def test_fluidd_conflicts_with_mainsail_installed(
self, monkeypatch, client
) -> None:
def fake_status(c):
code = 2 if c.client == WebClientType.MAINSAIL else 0
return type("S", (), {"status": code})()
monkeypatch.setattr(client_utils, "get_client_config_status", fake_status)
client.client = WebClientType.FLUIDD
assert detect_client_cfg_conflict(client) is True
class TestGetNextFreePort:
def test_returns_lowest_unused_port(self) -> None:
assert get_next_free_port([80, 81]) == 82
def test_starts_at_80(self) -> None:
assert get_next_free_port([]) == 80
class TestNginxPortParsing:
def test_parses_plain_listen_port(self, tmp_path: Path) -> None:
cfg = tmp_path / "site"
cfg.write_text("server {\n listen 8080;\n}\n")
assert get_nginx_listen_port(cfg) == 8080
def test_parses_listen_port_with_host(self, tmp_path: Path) -> None:
cfg = tmp_path / "site"
cfg.write_text("server {\n listen 127.0.0.1:9090;\n}\n")
assert get_nginx_listen_port(cfg) == 9090
def test_returns_none_when_no_listen(self, tmp_path: Path) -> None:
cfg = tmp_path / "site"
cfg.write_text("server {\n}\n")
assert get_nginx_listen_port(cfg) is None
def test_reads_all_configs_in_enabled_dir(
self, monkeypatch, tmp_path: Path
) -> None:
sites = tmp_path / "sites-enabled"
sites.mkdir()
(sites / "a").write_text("listen 1000;")
(sites / "b").write_text("listen 2000;")
monkeypatch.setattr(client_utils, "NGINX_SITES_ENABLED", sites)
ports = read_ports_from_nginx_configs()
assert ports == [1000, 2000]
def test_returns_empty_when_enabled_dir_missing(self, monkeypatch) -> None:
monkeypatch.setattr(client_utils, "NGINX_SITES_ENABLED", Path("/missing"))
assert read_ports_from_nginx_configs() == []
class TestSetListenPort:
def test_replaces_port_in_config(
self, client, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
client.name = "mainsail"
monkeypatch.setattr(client_utils, "NGINX_SITES_AVAILABLE", tmp_path)
cfg = tmp_path / "mainsail"
cfg.write_text("server {\n listen 80;\n}\n")
set_listen_port(client, 80, 8080)
assert "listen 8080" in cfg.read_text()
class TestCreateClientConfigSymlink:
def test_creates_symlink_per_instance(
self, monkeypatch, client, tmp_path: Path
) -> None:
client.client_config.config_dir = tmp_path / "cfg"
client.client_config.config_filename = "mainsail.cfg"
called: List[Any] = []
monkeypatch.setattr(
client_utils, "create_symlink", lambda s, t: called.append((s, t))
)
class FakeInstance:
base = type("Base", (), {"cfg_dir": tmp_path / "printer"})()
create_client_config_symlink(client.client_config, [FakeInstance()])
assert len(called) == 1
def test_symlink_failure_logs_error_and_continues(
self, monkeypatch, client, tmp_path: Path
) -> None:
client.client_config.config_dir = tmp_path / "cfg"
client.client_config.config_filename = "mainsail.cfg"
attempt: List[Any] = []
def flaky_create_symlink(source, target) -> None:
attempt.append(target)
if len(attempt) == 1:
raise RuntimeError("permission denied")
monkeypatch.setattr(client_utils, "create_symlink", flaky_create_symlink)
errors: List[str] = []
monkeypatch.setattr(
client_utils.Logger,
"print_error",
lambda msg, *a, **k: errors.append(str(msg)),
)
class FakeInstance:
def __init__(self, cfg: Path) -> None:
self.base = type("Base", (), {"cfg_dir": cfg})()
create_client_config_symlink(
client.client_config,
[FakeInstance(tmp_path / "a"), FakeInstance(tmp_path / "b")],
)
assert len(attempt) == 2 # failure did not abort the loop
assert any("symlink" in m.lower() for m in errors)
class TestBackupClientData:
def test_backs_up_client_dir_and_config_file(
self, monkeypatch, client, tmp_path: Path
) -> None:
client.client_dir = tmp_path / "mainsail"
client.client_dir.mkdir()
(client.client_dir / ".version").write_text("v1\n")
client.config_file = client.client_dir / "config.json"
client.config_file.write_text("{}")
calls: List[str] = []
class FakeBackup:
backup_root = tmp_path / "backups"
def backup_directory(self, **kwargs):
calls.append("dir")
def backup_file(self, **kwargs):
calls.append("file")
monkeypatch.setattr(client_utils, "BackupService", FakeBackup)
backup_client_data(client)
assert "dir" in calls
assert "file" in calls
class TestBackupClientConfigData:
def test_backs_up_config_dir(self, monkeypatch, client, tmp_path: Path) -> None:
client.client_dir = tmp_path / "mainsail"
client.client_dir.mkdir()
(client.client_dir / ".version").write_text("v1\n")
client.client_config.config_dir = tmp_path / "mainsail-config"
calls: List[str] = []
class FakeBackup:
backup_root = tmp_path / "backups"
def backup_directory(self, **kwargs):
calls.append("dir")
monkeypatch.setattr(client_utils, "BackupService", FakeBackup)
backup_client_config_data(client)
assert "dir" in calls
class TestGetClientStatus:
def test_sets_status_not_installed_when_dir_missing(
self, monkeypatch, client, tmp_path: Path
) -> None:
client.client_dir = tmp_path / "missing"
monkeypatch.setattr(
client_utils,
"get_install_status",
lambda *args, **kwargs: type(
"S", (), {"status": 2, "local": None, "remote": None}
)(),
)
status = get_client_status(client)
assert status.status == 0
class TestGetCurrentClientConfig:
def test_returns_dash_when_no_config_dirs(self, monkeypatch) -> None:
monkeypatch.setattr(
client_utils,
"MainsailData",
lambda: type(
"M",
(),
{
"client_config": type(
"C", (), {"config_dir": Path("/no/mainsail")}
)()
},
)(),
)
monkeypatch.setattr(
client_utils,
"FluiddData",
lambda: type(
"F",
(),
{"client_config": type("C", (), {"config_dir": Path("/no/fluidd")})()},
)(),
)
result = get_current_client_config()
assert "-" in result
def test_returns_single_installed_name(self, monkeypatch, tmp_path: Path) -> None:
cfg_dir = tmp_path / "mainsail-config"
cfg_dir.mkdir()
monkeypatch.setattr(
client_utils,
"MainsailData",
lambda: type(
"M",
(),
{
"client_config": type(
"C",
(),
{"config_dir": cfg_dir, "display_name": "Mainsail-Config"},
)()
},
)(),
)
monkeypatch.setattr(
client_utils,
"FluiddData",
lambda: type(
"F",
(),
{"client_config": type("C", (), {"config_dir": Path("/no/fluidd")})()},
)(),
)
result = get_current_client_config()
assert "Mainsail-Config" in result
+25
View File
@@ -0,0 +1,25 @@
# ======================================================================= #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
import pytest
@pytest.fixture(autouse=True)
def silence_logger(monkeypatch: pytest.MonkeyPatch) -> None:
"""Suppress logger output so tests produce clean, assertion-focused output."""
for name in (
"print_info",
"print_ok",
"print_warn",
"print_error",
"print_status",
"print_dialog",
):
monkeypatch.setattr(f"core.logger.Logger.{name}", lambda *a, **k: None)
+182
View File
@@ -0,0 +1,182 @@
# ======================================================================= #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
from typing import Any, List, Protocol, Sequence, cast, runtime_checkable
# --------------------------------------------------------------------------- #
# Singleton backends #
# --------------------------------------------------------------------------- #
# There is exactly ONE ``command_runner`` and ONE ``filesystem`` global in the
# whole project, owned by this module. They are assigned (with explicit type
# annotations) at the bottom of this file, AFTER the default implementations
# are defined. ``utils.fs_utils`` and ``utils.sys_utils`` delegate to these
# singletons via the wrapper functions below, so tests patch a single place —
# ``core.backends.command_runner`` / ``core.backends.filesystem`` — instead of
# per-module duplicates
def run(cmd: str | List[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
"""Run a command through the shared command runner."""
return command_runner.run(cmd, **kwargs)
def check_output(cmd: str | List[str], **kwargs: Any) -> str | bytes:
"""Run a command and return its output through the shared command runner."""
return command_runner.check_output(cmd, **kwargs)
def call(cmd: str | List[str], **kwargs: Any) -> int:
"""Run a command and return its exit code through the shared command runner."""
return command_runner.call(cmd, **kwargs)
def popen(cmd: str | List[str], **kwargs: Any) -> subprocess.Popen:
"""Start a process through the shared command runner."""
return command_runner.popen(cmd, **kwargs)
@runtime_checkable
class CommandRunner(Protocol):
"""Pluggable backend for executing system commands."""
def run(
self,
cmd: str | Sequence[str],
**kwargs: Any,
) -> subprocess.CompletedProcess: ...
def check_output(
self,
cmd: str | Sequence[str],
**kwargs: Any,
) -> str | bytes: ...
def call(
self,
cmd: str | Sequence[str],
**kwargs: Any,
) -> int: ...
def popen(
self,
cmd: str | Sequence[str],
**kwargs: Any,
) -> subprocess.Popen: ...
class SubprocessRunner:
"""Default command runner backed by the standard subprocess module."""
def run(
self,
cmd: str | Sequence[str],
**kwargs: Any,
) -> subprocess.CompletedProcess[str]:
return subprocess.run(cmd, **kwargs)
def check_output(
self,
cmd: str | Sequence[str],
**kwargs: Any,
) -> str | bytes:
return cast("str | bytes", subprocess.check_output(cmd, **kwargs))
def call(
self,
cmd: str | Sequence[str],
**kwargs: Any,
) -> int:
return subprocess.call(cmd, **kwargs)
def popen(
self,
cmd: str | Sequence[str],
**kwargs: Any,
) -> subprocess.Popen:
return subprocess.Popen(cmd, **kwargs)
@runtime_checkable
class FilesystemBackend(Protocol):
"""Pluggable backend for filesystem operations."""
def exists(self, path: Path) -> bool: ...
def is_dir(self, path: Path) -> bool: ...
def is_file(self, path: Path) -> bool: ...
def is_symlink(self, path: Path) -> bool: ...
def mkdir(
self, path: Path, *, parents: bool = False, exist_ok: bool = False
) -> None: ...
def unlink(self, path: Path) -> None: ...
def rmtree(self, path: Path) -> None: ...
def read_text(self, path: Path) -> str: ...
def write_text(self, path: Path, content: str) -> None: ...
def copy(self, source: Path, target: Path) -> None: ...
def home(self) -> Path: ...
class LocalFilesystemBackend:
"""Default filesystem backend backed by the local filesystem."""
def exists(self, path: Path) -> bool:
return path.exists()
def is_dir(self, path: Path) -> bool:
return path.is_dir()
def is_file(self, path: Path) -> bool:
return path.is_file()
def is_symlink(self, path: Path) -> bool:
return path.is_symlink()
def mkdir(
self, path: Path, *, parents: bool = False, exist_ok: bool = False
) -> None:
path.mkdir(parents=parents, exist_ok=exist_ok)
def unlink(self, path: Path) -> None:
path.unlink()
def rmtree(self, path: Path) -> None:
shutil.rmtree(path)
def read_text(self, path: Path) -> str:
return path.read_text()
def write_text(self, path: Path, content: str) -> None:
path.write_text(content)
def copy(self, source: Path, target: Path) -> None:
if source.is_dir():
shutil.copytree(source, target)
else:
shutil.copy2(source, target)
def home(self) -> Path:
return Path.home()
command_runner: CommandRunner = SubprocessRunner()
filesystem: FilesystemBackend = LocalFilesystemBackend()
+101
View File
@@ -0,0 +1,101 @@
from __future__ import annotations
import subprocess
from pathlib import Path
import pytest
from core import backends
from core.backends import LocalFilesystemBackend, SubprocessRunner
from tests.helpers.fake_backends import FakeCommandRunner, FakeFilesystemBackend
from utils import fs_utils, sys_utils
class TestSubprocessRunner:
def test_run_executes_command(self) -> None:
runner = SubprocessRunner()
result = runner.run(["true"])
assert result.returncode == 0
def test_check_output_returns_stdout(self) -> None:
runner = SubprocessRunner()
output = runner.check_output(["echo", "hello"], text=True)
assert "hello" in output
class TestCommandRunnerInjection:
def test_sys_utils_uses_injected_runner(self, monkeypatch) -> None:
fake = FakeCommandRunner({
("some", "cmd"): subprocess.CompletedProcess(["some", "cmd"], 0, "", "")
})
monkeypatch.setattr(backends, "command_runner", fake)
sys_utils.run(["some", "cmd"], check=True)
assert fake.calls[0][0] == ["some", "cmd"]
assert fake.calls[0][1].get("check") is True
def test_cmd_sysctl_service_records_command(self, monkeypatch) -> None:
expected_cmd = ["sudo", "systemctl", "start", "klipper.service"]
fake = FakeCommandRunner({
tuple(expected_cmd): subprocess.CompletedProcess(expected_cmd, 0, "", "")
})
monkeypatch.setattr(backends, "command_runner", fake)
sys_utils.cmd_sysctl_service("klipper.service", "start")
assert fake.calls[0][0] == expected_cmd
@pytest.mark.parametrize("module", [sys_utils, fs_utils])
def test_single_shared_command_runner_registry(self, monkeypatch, module) -> None:
# there is only ONE ``command_runner`` global to patch.
# Patching ``core.backends.command_runner`` must affect every wrapper
# (sys_utils.run, fs_utils.run, enum helpers) — no per-module duplicates.
fake = FakeCommandRunner({
("shared", "cmd"): subprocess.CompletedProcess(["shared", "cmd"], 0, "", "")
})
monkeypatch.setattr(backends, "command_runner", fake)
module.run(["shared", "cmd"], check=True)
assert fake.calls[0][0] == ["shared", "cmd"]
class TestLocalFilesystemBackend:
def test_write_and_read_text(self, tmp_path: Path) -> None:
fs = LocalFilesystemBackend()
target = tmp_path / "test.txt"
fs.write_text(target, "hello")
assert fs.read_text(target) == "hello"
def test_mkdir_and_exists(self, tmp_path: Path) -> None:
fs = LocalFilesystemBackend()
target = tmp_path / "new_dir"
assert not fs.exists(target)
fs.mkdir(target)
assert fs.exists(target)
assert fs.is_dir(target)
class TestFilesystemBackendInjection:
def test_create_folders_uses_injected_fs(self, monkeypatch) -> None:
fake = FakeFilesystemBackend()
monkeypatch.setattr(backends, "filesystem", fake)
fs_utils.create_folders([Path("/tmp/a"), Path("/tmp/b")])
assert fake.exists(Path("/tmp/a"))
assert fake.exists(Path("/tmp/b"))
def test_run_remove_routines_uses_injected_fs(self, monkeypatch) -> None:
fake = FakeFilesystemBackend()
fake.add_file(Path("/tmp/file.txt"), "x")
monkeypatch.setattr(backends, "filesystem", fake)
assert fs_utils.run_remove_routines(Path("/tmp/file.txt")) is True
assert not fake.exists(Path("/tmp/file.txt"))
def test_run_remove_routines_skips_missing_file(self, monkeypatch) -> None:
fake = FakeFilesystemBackend()
monkeypatch.setattr(backends, "filesystem", fake)
assert fs_utils.run_remove_routines(Path("/tmp/missing")) is False
-108
View File
@@ -1,108 +0,0 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
import shutil
from pathlib import Path
from typing import List
from core.backup_manager import BACKUP_ROOT_DIR
from core.logger import Logger
from utils.common import get_current_date
class BackupManagerException(Exception):
pass
# noinspection PyUnusedLocal
# noinspection PyMethodMayBeStatic
class BackupManager:
def __init__(self, backup_root_dir: Path = BACKUP_ROOT_DIR):
self._backup_root_dir: Path = backup_root_dir
self._ignore_folders: List[str] = []
@property
def backup_root_dir(self) -> Path:
return self._backup_root_dir
@backup_root_dir.setter
def backup_root_dir(self, value: Path):
self._backup_root_dir = value
@property
def ignore_folders(self) -> List[str]:
return self._ignore_folders
@ignore_folders.setter
def ignore_folders(self, value: List[str]):
self._ignore_folders = value
def backup_file(
self, file: Path, target: Path | None = None, custom_filename=None
) -> bool:
Logger.print_status(f"Creating backup of {file} ...")
if not file.exists():
Logger.print_info("File does not exist! Skipping ...")
return False
target = self.backup_root_dir if target is None else target
if Path(file).is_file():
date = get_current_date().get("date")
time = get_current_date().get("time")
filename = f"{file.stem}-{date}-{time}{file.suffix}"
filename = custom_filename if custom_filename is not None else filename
try:
Path(target).mkdir(exist_ok=True)
shutil.copyfile(file, target.joinpath(filename))
Logger.print_ok("Backup successful!")
return True
except OSError as e:
Logger.print_error(f"Unable to backup '{file}':\n{e}")
return False
else:
Logger.print_info(f"File '{file}' not found ...")
return False
def backup_directory(
self, name: str, source: Path, target: Path | None = None
) -> Path | None:
Logger.print_status(f"Creating backup of {name} in {target} ...")
if source is None or not Path(source).exists():
Logger.print_info("Source directory does not exist! Skipping ...")
return None
target = self.backup_root_dir if target is None else target
try:
date = get_current_date().get("date")
time = get_current_date().get("time")
backup_target = target.joinpath(f"{name.lower()}-{date}-{time}")
shutil.copytree(
source,
backup_target,
ignore=self.ignore_folders_func,
ignore_dangling_symlinks=True,
)
Logger.print_ok("Backup successful!")
return backup_target
except OSError as e:
Logger.print_error(f"Unable to backup directory '{source}':\n{e}")
raise BackupManagerException(f"Unable to backup directory '{source}':\n{e}")
def ignore_folders_func(self, dirpath, filenames) -> List[str]:
return (
[f for f in filenames if f in self._ignore_folders]
if self._ignore_folders
else []
)
+365
View File
@@ -0,0 +1,365 @@
# ======================================================================= #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
import argparse
import sys
from typing import Callable, Dict, List, Tuple
from components.klipper.services.klipper_setup_service import KlipperSetupService
from components.moonraker.services.moonraker_setup_service import MoonrakerSetupService
from components.webui_client.services.web_client_config_setup_service import (
WebClientConfigSetupService,
)
from components.webui_client.services.web_client_setup_service import (
WebClientSetupService,
)
# A dispatcher receives the parsed argparse namespace and the parser (so it can
# raise ``parser.error`` for invalid input) and returns the CLI exit code.
Dispatcher = Callable[[argparse.Namespace, argparse.ArgumentParser], int]
def _add_klipper_install(sub: argparse._SubParsersAction) -> None:
p = sub.add_parser("klipper", help="Install Klipper")
p.add_argument(
"--count", type=int, default=None, help="Number of instances to install"
)
p.add_argument(
"--name", action="append", default=[], help="Custom instance name(s)"
)
p.add_argument(
"--create-example-cfg", action="store_true", help="Create example printer.cfg"
)
p.add_argument(
"--match-moonraker",
action="store_true",
help="Match Klipper instance count to existing Moonraker instances",
)
def _add_moonraker_install(sub: argparse._SubParsersAction) -> None:
p = sub.add_parser("moonraker", help="Install Moonraker")
p.add_argument(
"--klipper-suffix",
action="append",
default=[],
help="Klipper suffix to set up Moonraker for (can be repeated)",
)
p.add_argument(
"--create-example-cfg",
action="store_true",
help="Create example moonraker.conf",
)
def _add_web_client_install(sub: argparse._SubParsersAction) -> None:
for name in ("mainsail", "fluidd"):
p = sub.add_parser(name, help=f"Install {name.capitalize()}")
p.add_argument("--port", type=int, default=None, help="Listen port")
p.add_argument(
"--install-config",
action="store_true",
help="Install the recommended client config",
)
p.add_argument(
"--continue-without-moonraker",
action="store_true",
help="Allow installation even if Moonraker is not installed",
)
sub.add_parser("mainsail-config", help="Install the Mainsail client config")
sub.add_parser("fluidd-config", help="Install the Fluidd client config")
def _add_klipper_remove(sub: argparse._SubParsersAction) -> None:
p = sub.add_parser("klipper", help="Remove Klipper")
p.add_argument("--service", action="store_true", help="Remove Klipper services")
p.add_argument("--dir", action="store_true", help="Remove Klipper local repository")
p.add_argument(
"--env", action="store_true", help="Remove Klipper Python environment"
)
p.add_argument(
"--all",
action="store_true",
help="Remove every installed Klipper instance (destructive)",
)
p.add_argument(
"--instance",
action="append",
default=[],
help="Klipper instance suffix to remove (repeatable)",
)
def _add_moonraker_remove(sub: argparse._SubParsersAction) -> None:
p = sub.add_parser("moonraker", help="Remove Moonraker")
p.add_argument("--service", action="store_true", help="Remove Moonraker services")
p.add_argument(
"--dir", action="store_true", help="Remove Moonraker local repository"
)
p.add_argument(
"--env", action="store_true", help="Remove Moonraker Python environment"
)
p.add_argument(
"--polkit", action="store_true", help="Remove Moonraker policykit rules"
)
p.add_argument(
"--all",
action="store_true",
help="Remove every installed Moonraker instance (destructive)",
)
p.add_argument(
"--instance",
action="append",
default=[],
help="Moonraker instance suffix to remove (repeatable)",
)
def _add_web_client_remove(sub: argparse._SubParsersAction) -> None:
for name in ("mainsail", "fluidd"):
p = sub.add_parser(name, help=f"Remove {name.capitalize()}")
p.add_argument("--client", action="store_true", help="Remove the web client")
p.add_argument("--config", action="store_true", help="Remove the client config")
p.add_argument("--no-backup", action="store_true", help="Skip config backup")
def _add_klipper_update(sub: argparse._SubParsersAction) -> None:
p = sub.add_parser("klipper", help="Update Klipper")
p.add_argument("--backup", action="store_true", help="Backup before updating")
def _add_moonraker_update(sub: argparse._SubParsersAction) -> None:
sub.add_parser("moonraker", help="Update Moonraker")
def _add_web_client_update(sub: argparse._SubParsersAction) -> None:
for name in ("mainsail", "fluidd"):
sub.add_parser(name, help=f"Update {name.capitalize()}")
sub.add_parser("mainsail-config", help="Update the Mainsail client config")
sub.add_parser("fluidd-config", help="Update the Fluidd client config")
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="kiauh")
subparsers = parser.add_subparsers(dest="command")
install = subparsers.add_parser("install", help="Install a component")
install_sub = install.add_subparsers(dest="component", required=True)
_add_klipper_install(install_sub)
_add_moonraker_install(install_sub)
_add_web_client_install(install_sub)
remove = subparsers.add_parser("remove", help="Remove a component")
remove_sub = remove.add_subparsers(dest="component", required=True)
_add_klipper_remove(remove_sub)
_add_moonraker_remove(remove_sub)
_add_web_client_remove(remove_sub)
update = subparsers.add_parser("update", help="Update a component")
update_sub = update.add_subparsers(dest="component", required=True)
_add_klipper_update(update_sub)
_add_moonraker_update(update_sub)
_add_web_client_update(update_sub)
return parser
# --------------------------------------------------------------------------- #
# Command handlers: one callable per (command, component) pair. #
# Adding a new component is a matter of registering a handler here instead of #
# extending the previous long if/elif chain. #
# --------------------------------------------------------------------------- #
def _install_klipper(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
if args.count is not None and args.name and args.count != len(args.name):
parser.error("--count must match the number of --name values")
service = KlipperSetupService()
custom_names = {i: name for i, name in enumerate(args.name)} if args.name else None
result = service.install(
count=args.count,
custom_names=custom_names,
create_example_cfg=args.create_example_cfg,
match_moonraker=args.match_moonraker,
interactive=False,
)
return 0 if result else 1
def _remove_klipper(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
if not (args.service or args.dir or args.env):
parser.error(
"specify at least one of --service, --dir, --env for 'remove klipper'"
)
if args.service and not (args.all or args.instance):
# refuse to silently wipe every Klipper instance.
parser.error(
"removing Klipper services is destructive; pass --all or "
"--instance <suffix> (repeatable) to select what to remove"
)
service = KlipperSetupService()
result = service.remove(
remove_service=args.service,
remove_dir=args.dir,
remove_env=args.env,
remove_all=args.all,
instance_suffixes=args.instance or None,
interactive=False,
)
return 0 if result else 1
def _update_klipper(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
service = KlipperSetupService()
if args.backup:
service.settings.kiauh.backup_before_update = True
result = service.update(interactive=False)
return 0 if result else 1
def _install_moonraker(
args: argparse.Namespace, parser: argparse.ArgumentParser
) -> int:
service = MoonrakerSetupService()
result = service.install(
klipper_suffixes=args.klipper_suffix or None,
create_example_cfg=args.create_example_cfg,
interactive=False,
)
return 0 if result else 1
def _remove_moonraker(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
if not (args.service or args.dir or args.env or args.polkit):
parser.error(
"specify at least one of --service, --dir, --env, --polkit "
"for 'remove moonraker'"
)
if args.service and not (args.all or args.instance):
# refuse to silently wipe every Moonraker instance.
parser.error(
"removing Moonraker services is destructive; pass --all or "
"--instance <suffix> (repeatable) to select what to remove"
)
service = MoonrakerSetupService()
result = service.remove(
remove_service=args.service,
remove_dir=args.dir,
remove_env=args.env,
remove_polkit=args.polkit,
remove_all=args.all,
instance_suffixes=args.instance or None,
interactive=False,
)
return 0 if result else 1
def _update_moonraker(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
service = MoonrakerSetupService()
result = service.update(interactive=False)
return 0 if result else 1
def _install_web_client(
args: argparse.Namespace, parser: argparse.ArgumentParser
) -> int:
service = WebClientSetupService(args.component)
result = service.install(
port=args.port,
install_client_cfg=args.install_config,
continue_without_moonraker=args.continue_without_moonraker,
interactive=False,
)
return 0 if result else 1
def _install_web_client_config(
args: argparse.Namespace, parser: argparse.ArgumentParser
) -> int:
client_name = args.component.replace("-config", "")
result = WebClientConfigSetupService(client_name).install(interactive=False)
return 0 if result else 1
def _remove_web_client(
args: argparse.Namespace, parser: argparse.ArgumentParser
) -> int:
if not (args.client or args.config):
parser.error(
f"specify at least one of --client, --config for 'remove {args.component}'"
)
service = WebClientSetupService(args.component)
result = service.remove(
remove_client=args.client,
remove_client_cfg=args.config,
backup_config=not args.no_backup,
interactive=False,
)
return 0 if result else 1
def _update_web_client(
args: argparse.Namespace, parser: argparse.ArgumentParser
) -> int:
result = WebClientSetupService(args.component).update()
return 0 if result else 1
def _update_web_client_config(
args: argparse.Namespace, parser: argparse.ArgumentParser
) -> int:
client_name = args.component.replace("-config", "")
result = WebClientConfigSetupService(client_name).update(interactive=False)
return 0 if result else 1
# Dispatch registry: (command, component) -> handler. Keeping this as a module
# constant (not a closure) keeps ``run_cli`` trivial and lets tests assert which
# combinations are actually supported.
DISPATCH: Dict[Tuple[str, str], Dispatcher] = {
("install", "klipper"): _install_klipper,
("remove", "klipper"): _remove_klipper,
("update", "klipper"): _update_klipper,
("install", "moonraker"): _install_moonraker,
("remove", "moonraker"): _remove_moonraker,
("update", "moonraker"): _update_moonraker,
("install", "mainsail"): _install_web_client,
("install", "fluidd"): _install_web_client,
("remove", "mainsail"): _remove_web_client,
("remove", "fluidd"): _remove_web_client,
("update", "mainsail"): _update_web_client,
("update", "fluidd"): _update_web_client,
("install", "mainsail-config"): _install_web_client_config,
("install", "fluidd-config"): _install_web_client_config,
("update", "mainsail-config"): _update_web_client_config,
("update", "fluidd-config"): _update_web_client_config,
}
def run_cli(argv: List[str] | None = None) -> int:
"""Run a headless CLI command.
Returns 0 on success, -1 if no command was provided (-> fall back to TUI),
and a positive exit code when a command reports failure.
"""
parser = build_parser()
args = parser.parse_args(argv)
if not args.command:
return -1
handler = DISPATCH.get((args.command, args.component))
if handler is None:
parser.error(f"Unsupported command: {args.command} {args.component}")
return handler(args, parser)
def main() -> None:
sys.exit(run_cli())
+517
View File
@@ -0,0 +1,517 @@
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, List, Set
import core.cli as cli_module
import pytest
from core.cli import run_cli
class FakeKlipperService:
def __init__(self) -> None:
self.calls: List[Dict[str, Any]] = []
self.results: Dict[str, bool] = {}
self.settings = type(
"Settings",
(),
{
"kiauh": type(
"KiauhSettingsSection", (), {"backup_before_update": False}
)()
},
)()
def install(self, **kwargs: Any) -> bool:
self.calls.append({"method": "install", "kwargs": kwargs})
return self.results.get("install", True)
def remove(self, **kwargs: Any) -> bool:
self.calls.append({"method": "remove", "kwargs": kwargs})
return self.results.get("remove", True)
def update(self, **kwargs: Any) -> bool:
self.calls.append({"method": "update", "kwargs": kwargs})
return self.results.get("update", True)
class FakeMoonrakerService:
def __init__(self) -> None:
self.calls: List[Dict[str, Any]] = []
self.results: Dict[str, bool] = {}
def install(self, **kwargs: Any) -> bool:
self.calls.append({"method": "install", "kwargs": kwargs})
return self.results.get("install", True)
def remove(self, **kwargs: Any) -> bool:
self.calls.append({"method": "remove", "kwargs": kwargs})
return self.results.get("remove", True)
def update(self, **kwargs: Any) -> bool:
self.calls.append({"method": "update", "kwargs": kwargs})
return self.results.get("update", True)
class FakeWebClientService:
def __init__(self) -> None:
self.install_calls: List[Dict[str, Any]] = []
self.remove_calls: List[Dict[str, Any]] = []
self.update_calls: List[str] = []
self.results: Dict[str, bool] = {}
def install(self, **kwargs: Any) -> bool:
self.install_calls.append(kwargs)
return self.results.get("install", True)
def remove(self, **kwargs: Any) -> bool:
self.remove_calls.append(kwargs)
return self.results.get("remove", True)
def update(self) -> bool:
self.update_calls.append("update")
return self.results.get("update", True)
class FakeWebClientConfigService:
def __init__(self) -> None:
self.install_calls: List[Dict[str, Any]] = []
self.update_calls: List[Dict[str, Any]] = []
self.results: Dict[str, bool] = {}
def install(self, **kwargs: Any) -> bool:
self.install_calls.append(kwargs)
return self.results.get("install", True)
def update(self, **kwargs: Any) -> bool:
self.update_calls.append(kwargs)
return self.results.get("update", True)
@pytest.fixture
def fake_service(monkeypatch: pytest.MonkeyPatch) -> FakeKlipperService:
fake = FakeKlipperService()
monkeypatch.setattr("core.cli.KlipperSetupService", lambda: fake)
return fake
@pytest.fixture
def fake_moonraker_service(monkeypatch: pytest.MonkeyPatch) -> FakeMoonrakerService:
fake = FakeMoonrakerService()
monkeypatch.setattr("core.cli.MoonrakerSetupService", lambda: fake)
return fake
@pytest.fixture
def fake_web_client_service(monkeypatch: pytest.MonkeyPatch) -> FakeWebClientService:
fake = FakeWebClientService()
monkeypatch.setattr("core.cli.WebClientSetupService", lambda name: fake)
return fake
@pytest.fixture
def fake_web_client_config_service(
monkeypatch: pytest.MonkeyPatch,
) -> FakeWebClientConfigService:
fake = FakeWebClientConfigService()
monkeypatch.setattr("core.cli.WebClientConfigSetupService", lambda name: fake)
return fake
class TestCliDispatch:
def test_no_args_returns_tui_signal(self) -> None:
assert run_cli([]) == -1
def test_install_klipper(self, fake_service: FakeKlipperService) -> None:
rc = run_cli(["install", "klipper", "--count", "2"])
assert rc == 0
assert fake_service.calls == [
{
"method": "install",
"kwargs": {
"count": 2,
"custom_names": None,
"create_example_cfg": False,
"match_moonraker": False,
"interactive": False,
},
}
]
def test_install_klipper_default_count_is_none(
self, fake_service: FakeKlipperService
) -> None:
rc = run_cli(["install", "klipper"])
assert rc == 0
assert fake_service.calls[0]["kwargs"]["count"] is None
def test_install_klipper_with_names(self, fake_service: FakeKlipperService) -> None:
rc = run_cli(["install", "klipper", "--name", "a", "--name", "b"])
assert rc == 0
assert fake_service.calls[0]["kwargs"]["custom_names"] == {0: "a", 1: "b"}
assert fake_service.calls[0]["kwargs"]["count"] is None
def test_install_klipper_count_and_name_mismatch_rejected(self) -> None:
with pytest.raises(SystemExit):
run_cli([
"install",
"klipper",
"--count",
"3",
"--name",
"a",
"--name",
"b",
])
def test_install_klipper_with_flags(self, fake_service: FakeKlipperService) -> None:
rc = run_cli([
"install",
"klipper",
"--create-example-cfg",
"--match-moonraker",
])
assert rc == 0
kwargs = fake_service.calls[0]["kwargs"]
assert kwargs["create_example_cfg"] is True
assert kwargs["match_moonraker"] is True
assert kwargs["interactive"] is False
def test_install_klipper_failure_returns_nonzero(
self, fake_service: FakeKlipperService
) -> None:
fake_service.results["install"] = False
assert run_cli(["install", "klipper"]) == 1
def test_remove_klipper(self, fake_service: FakeKlipperService) -> None:
rc = run_cli(["remove", "klipper", "--service", "--all", "--dir", "--env"])
assert rc == 0
assert fake_service.calls == [
{
"method": "remove",
"kwargs": {
"remove_service": True,
"interactive": False,
"remove_dir": True,
"remove_env": True,
"remove_all": True,
"instance_suffixes": None,
},
}
]
def test_remove_klipper_failure_returns_nonzero(
self, fake_service: FakeKlipperService
) -> None:
fake_service.results["remove"] = False
assert run_cli(["remove", "klipper", "--service", "--all"]) == 1
def test_remove_klipper_no_flags_is_rejected(
self, fake_service: FakeKlipperService
) -> None:
# a remove with no removal flags must not silently succeed
with pytest.raises(SystemExit):
run_cli(["remove", "klipper"])
assert fake_service.calls == []
def test_remove_klipper_service_without_explicit_intent_is_rejected(
self, fake_service: FakeKlipperService
) -> None:
# `--service` alone must NOT silently wipe all instances.
# The user must pass `--all` (or `--instance <suffix>`).
with pytest.raises(SystemExit):
run_cli(["remove", "klipper", "--service"])
assert fake_service.calls == []
def test_remove_klipper_with_instance_suffix(
self, fake_service: FakeKlipperService
) -> None:
rc = run_cli([
"remove",
"klipper",
"--service",
"--instance",
"a",
"--instance",
"b",
])
assert rc == 0
assert fake_service.calls[0]["kwargs"]["instance_suffixes"] == ["a", "b"]
assert fake_service.calls[0]["kwargs"]["remove_all"] is False
def test_update_klipper(self, fake_service: FakeKlipperService) -> None:
rc = run_cli(["update", "klipper"])
assert rc == 0
assert fake_service.calls == [
{"method": "update", "kwargs": {"interactive": False}}
]
def test_update_klipper_with_backup_flag(
self, fake_service: FakeKlipperService
) -> None:
rc = run_cli(["update", "klipper", "--backup"])
assert rc == 0
assert fake_service.settings.kiauh.backup_before_update is True
def test_update_klipper_failure_returns_nonzero(
self, fake_service: FakeKlipperService
) -> None:
fake_service.results["update"] = False
assert run_cli(["update", "klipper"]) == 1
class TestMoonrakerCliDispatch:
def test_install_moonraker_default(
self, fake_moonraker_service: FakeMoonrakerService
) -> None:
rc = run_cli(["install", "moonraker"])
assert rc == 0
assert fake_moonraker_service.calls == [
{
"method": "install",
"kwargs": {
"klipper_suffixes": None,
"create_example_cfg": False,
"interactive": False,
},
}
]
def test_install_moonraker_with_suffixes(
self, fake_moonraker_service: FakeMoonrakerService
) -> None:
rc = run_cli([
"install",
"moonraker",
"--klipper-suffix",
"a",
"--klipper-suffix",
"b",
])
assert rc == 0
assert fake_moonraker_service.calls[0]["kwargs"]["klipper_suffixes"] == [
"a",
"b",
]
def test_install_moonraker_failure_returns_nonzero(
self, fake_moonraker_service: FakeMoonrakerService
) -> None:
fake_moonraker_service.results["install"] = False
assert run_cli(["install", "moonraker"]) == 1
def test_remove_moonraker(
self, fake_moonraker_service: FakeMoonrakerService
) -> None:
rc = run_cli([
"remove",
"moonraker",
"--service",
"--all",
"--dir",
"--env",
"--polkit",
])
assert rc == 0
assert fake_moonraker_service.calls == [
{
"method": "remove",
"kwargs": {
"remove_service": True,
"remove_dir": True,
"remove_env": True,
"remove_polkit": True,
"interactive": False,
"remove_all": True,
"instance_suffixes": None,
},
}
]
def test_remove_moonraker_service_without_explicit_intent_is_rejected(
self, fake_moonraker_service: FakeMoonrakerService
) -> None:
# `--service` alone must NOT silently wipe all instances.
with pytest.raises(SystemExit):
run_cli(["remove", "moonraker", "--service"])
assert fake_moonraker_service.calls == []
def test_update_moonraker(
self, fake_moonraker_service: FakeMoonrakerService
) -> None:
rc = run_cli(["update", "moonraker"])
assert rc == 0
assert fake_moonraker_service.calls == [
{"method": "update", "kwargs": {"interactive": False}}
]
def test_remove_moonraker_no_flags_is_rejected(
self, fake_moonraker_service: FakeMoonrakerService
) -> None:
# a remove with no removal flags must not silently succeed
with pytest.raises(SystemExit):
run_cli(["remove", "moonraker"])
assert fake_moonraker_service.calls == []
class TestWebClientCliDispatch:
def test_install_mainsail(
self, fake_web_client_service: FakeWebClientService
) -> None:
rc = run_cli([
"install",
"mainsail",
"--port",
"8080",
"--install-config",
"--continue-without-moonraker",
])
assert rc == 0
assert fake_web_client_service.install_calls == [
{
"port": 8080,
"install_client_cfg": True,
"continue_without_moonraker": True,
"interactive": False,
}
]
def test_install_fluidd_default(
self, fake_web_client_service: FakeWebClientService
) -> None:
rc = run_cli(["install", "fluidd"])
assert rc == 0
assert fake_web_client_service.install_calls == [
{
"port": None,
"install_client_cfg": False,
"continue_without_moonraker": False,
"interactive": False,
}
]
def test_install_client_config_runs_non_interactively(
self, fake_web_client_config_service: FakeWebClientConfigService
) -> None:
rc = run_cli(["install", "mainsail-config"])
assert rc == 0
assert fake_web_client_config_service.install_calls == [{"interactive": False}]
def test_install_web_client_failure_returns_nonzero(
self, fake_web_client_service: FakeWebClientService
) -> None:
fake_web_client_service.results["install"] = False
assert run_cli(["install", "mainsail"]) == 1
def test_remove_mainsail_no_flags_is_rejected(
self, fake_web_client_service: FakeWebClientService
) -> None:
# a remove with no removal flags must not silently succeed
with pytest.raises(SystemExit):
run_cli(["remove", "mainsail"])
assert fake_web_client_service.remove_calls == []
def test_remove_mainsail_with_client_and_config(
self, fake_web_client_service: FakeWebClientService
) -> None:
rc = run_cli(["remove", "mainsail", "--client", "--config"])
assert rc == 0
assert fake_web_client_service.remove_calls == [
{
"remove_client": True,
"remove_client_cfg": True,
"backup_config": True,
"interactive": False,
}
]
def test_remove_fluidd_no_backup(
self, fake_web_client_service: FakeWebClientService
) -> None:
rc = run_cli(["remove", "fluidd", "--client", "--no-backup"])
assert rc == 0
assert fake_web_client_service.remove_calls == [
{
"remove_client": True,
"remove_client_cfg": False,
"backup_config": False,
"interactive": False,
}
]
def test_update_mainsail(
self, fake_web_client_service: FakeWebClientService
) -> None:
rc = run_cli(["update", "mainsail"])
assert rc == 0
assert fake_web_client_service.update_calls == ["update"]
def test_update_fluidd_config_runs_non_interactively(
self, fake_web_client_config_service: FakeWebClientConfigService
) -> None:
rc = run_cli(["update", "fluidd-config"])
assert rc == 0
assert fake_web_client_config_service.update_calls == [{"interactive": False}]
class TestDispatchRegistry:
"""``run_cli`` must use a dispatch registry instead of a long
if/elif chain, and the registry must cover every (command, component) pair
the argument parser can produce."""
_EXPECTED: Set[tuple] = {
("install", "klipper"),
("remove", "klipper"),
("update", "klipper"),
("install", "moonraker"),
("remove", "moonraker"),
("update", "moonraker"),
("install", "mainsail"),
("install", "fluidd"),
("remove", "mainsail"),
("remove", "fluidd"),
("update", "mainsail"),
("update", "fluidd"),
("install", "mainsail-config"),
("install", "fluidd-config"),
("update", "mainsail-config"),
("update", "fluidd-config"),
}
def test_dispatch_registry_exists_and_covers_every_pair(self) -> None:
dispatch = getattr(cli_module, "DISPATCH", None)
assert dispatch is not None, "run_cli must expose a DISPATCH registry"
assert set(dispatch.keys()) == self._EXPECTED
for handler in dispatch.values():
assert callable(handler)
def test_subparser_helpers_are_typed_not_any(self) -> None:
# the ``_add_*`` helpers must accept ``argparse._SubParsersAction``, not ``Any``.
import inspect
for name in dir(cli_module):
if not name.startswith("_add_"):
continue
func = getattr(cli_module, name)
if not inspect.isfunction(func):
continue
hints = inspect.signature(func).parameters.get("sub")
assert hints is not None
assert hints.annotation is not Any, f"{name} must not type ``sub`` as Any"
assert "SubParsersAction" in str(hints.annotation), (
f"{name} must type ``sub`` as an argparse SubParsersAction"
)
class TestPackaging:
def test_pyproject_metadata_allows_editable_dev_install(self) -> None:
project_root = Path(__file__).resolve().parents[4]
import subprocess as sp
result = sp.run(
["python", "-m", "pip", "install", "--dry-run", "-e", ".[dev]"],
cwd=project_root,
capture_output=True,
text=True,
)
assert result.returncode == 0, result.stderr
+1 -4
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -11,8 +11,6 @@ import os
import pwd
from pathlib import Path
from core.backup_manager import BACKUP_ROOT_DIR
# global dependencies
GLOBAL_DEPS = ["git", "wget", "curl", "unzip", "dfu-util", "python3-virtualenv"]
@@ -24,7 +22,6 @@ CURRENT_USER = pwd.getpwuid(os.getuid())[0]
# dirs
SYSTEMD = Path("/etc/systemd/system")
PRINTER_DATA_BACKUP_DIR = BACKUP_ROOT_DIR.joinpath("printer-data-backups")
NGINX_SITES_AVAILABLE = Path("/etc/nginx/sites-available")
NGINX_SITES_ENABLED = Path("/etc/nginx/sites-enabled")
NGINX_CONFD = Path("/etc/nginx/conf.d")
+1 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+4 -3
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -16,8 +16,9 @@ from typing import List
from utils.fs_utils import get_data_dir
SUFFIX_BLACKLIST: List[str] = ["None", "mcu", "obico", "bambu", "companion"]
# suffixes that are not allowed to be used for instances
# because they would cause conflicts with other components or are reserved
SUFFIX_BLACKLIST: List[str] = ["None", "mcu", "obico", "bambu", "companion", "hmi"]
@dataclass(repr=True)
class BaseInstance:
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -0,0 +1,109 @@
from __future__ import annotations
import subprocess
from pathlib import Path
from typing import List
import pytest
from core.instance_manager.instance_manager import InstanceManager
from tests.helpers.fake_backends import FakeCommandRunner
class FakeInstance:
def __init__(self, name: str, log_dir: Path | None = None) -> None:
self.service_file_path = Path(f"/etc/systemd/system/{name}.service")
self.log_file_name = "klipper.log"
self.base = type("Base", (), {"log_dir": log_dir})()
def _runner_for(*commands: List[str]) -> FakeCommandRunner:
"""Return a strict FakeCommandRunner with success responses for commands."""
responses = {
tuple(cmd): subprocess.CompletedProcess(
args=cmd, returncode=0, stdout="", stderr=""
)
for cmd in commands
}
return FakeCommandRunner(responses)
class TestInstanceManager:
def test_start_records_command(self, monkeypatch: pytest.MonkeyPatch) -> None:
cmd = ["sudo", "systemctl", "start", "klipper.service"]
fake = _runner_for(cmd)
monkeypatch.setattr("core.backends.command_runner", fake)
instance = FakeInstance("klipper")
InstanceManager.start(instance)
assert fake.calls[0][0] == cmd
def test_stop_records_command(self, monkeypatch: pytest.MonkeyPatch) -> None:
cmd = ["sudo", "systemctl", "stop", "klipper.service"]
fake = _runner_for(cmd)
monkeypatch.setattr("core.backends.command_runner", fake)
instance = FakeInstance("klipper")
InstanceManager.stop(instance)
assert fake.calls[0][0] == cmd
def test_restart_records_command(self, monkeypatch: pytest.MonkeyPatch) -> None:
cmd = ["sudo", "systemctl", "restart", "klipper.service"]
fake = _runner_for(cmd)
monkeypatch.setattr("core.backends.command_runner", fake)
instance = FakeInstance("klipper")
InstanceManager.restart(instance)
assert fake.calls[0][0] == cmd
def test_enable_records_command(self, monkeypatch: pytest.MonkeyPatch) -> None:
cmd = ["sudo", "systemctl", "enable", "klipper.service"]
fake = _runner_for(cmd)
monkeypatch.setattr("core.backends.command_runner", fake)
instance = FakeInstance("klipper")
InstanceManager.enable(instance)
assert fake.calls[0][0] == cmd
def test_disable_records_command(self, monkeypatch: pytest.MonkeyPatch) -> None:
cmd = ["sudo", "systemctl", "disable", "klipper.service"]
fake = _runner_for(cmd)
monkeypatch.setattr("core.backends.command_runner", fake)
instance = FakeInstance("klipper")
InstanceManager.disable(instance)
assert fake.calls[0][0] == cmd
def test_start_all_iterates_instances(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
commands = [
["sudo", "systemctl", "start", "klipper-1.service"],
["sudo", "systemctl", "start", "klipper-2.service"],
]
fake = _runner_for(*commands)
monkeypatch.setattr("core.backends.command_runner", fake)
instances = [FakeInstance("klipper-1"), FakeInstance("klipper-2")]
InstanceManager.start_all(instances)
recorded = [call[0] for call in fake.calls]
assert recorded == commands
def test_stop_all_iterates_instances(self, monkeypatch: pytest.MonkeyPatch) -> None:
commands = [
["sudo", "systemctl", "stop", "klipper-a.service"],
["sudo", "systemctl", "stop", "klipper-b.service"],
]
fake = _runner_for(*commands)
monkeypatch.setattr("core.backends.command_runner", fake)
instances = [FakeInstance("klipper-a"), FakeInstance("klipper-b")]
InstanceManager.stop_all(instances)
recorded = [call[0] for call in fake.calls]
assert recorded == commands
+1 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+1 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+1 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+4 -4
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -25,8 +25,8 @@ from components.webui_client.fluidd_data import FluiddData
from components.webui_client.mainsail_data import MainsailData
from core.menus import Option
from core.menus.base_menu import BaseMenu
from core.services.backup_service import BackupService
from core.types.color import Color
from utils.common import backup_printer_config_dir
# noinspection PyUnusedLocal
@@ -58,7 +58,7 @@ class BackupMenu(BaseMenu):
def print_menu(self) -> None:
line1 = Color.apply(
"INFO: Backups are located in '~/kiauh-backups'", Color.YELLOW
"INFO: Backups are located in '~/kiauh_backups'", Color.YELLOW
)
menu = textwrap.dedent(
f"""
@@ -86,7 +86,7 @@ class BackupMenu(BaseMenu):
backup_moonraker_dir()
def backup_printer_config(self, **kwargs) -> None:
backup_printer_config_dir()
BackupService().backup_printer_config_dir()
def backup_moonraker_db(self, **kwargs) -> None:
backup_moonraker_db_dir()
+1 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+11 -10
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -15,16 +15,17 @@ from components.crowsnest.crowsnest import install_crowsnest
from components.klipper.services.klipper_setup_service import KlipperSetupService
from components.klipperscreen.klipperscreen import install_klipperscreen
from components.moonraker.services.moonraker_setup_service import MoonrakerSetupService
from components.webui_client.client_config.client_config_setup import (
install_client_config,
)
from components.webui_client.client_setup import install_client
from components.webui_client.fluidd_data import FluiddData
from components.webui_client.mainsail_data import MainsailData
from components.webui_client.menus.client_install_menu import ClientInstallMenu
from components.webui_client.services.web_client_config_setup_service import (
WebClientConfigSetupService,
)
from components.webui_client.services.web_client_setup_service import (
WebClientSetupService,
)
from core.menus import Option
from core.menus.base_menu import BaseMenu
from core.settings.kiauh_settings import KiauhSettings
from core.types.color import Color
@@ -87,20 +88,20 @@ class InstallMenu(BaseMenu):
if client.client_dir.exists():
ClientInstallMenu(client, self.__class__).run()
else:
install_client(client, settings=KiauhSettings())
WebClientSetupService("mainsail").install()
def install_mainsail_config(self, **kwargs) -> None:
install_client_config(MainsailData())
WebClientConfigSetupService("mainsail").install()
def install_fluidd(self, **kwargs) -> None:
client: FluiddData = FluiddData()
if client.client_dir.exists():
ClientInstallMenu(client, self.__class__).run()
else:
install_client(client, settings=KiauhSettings())
WebClientSetupService("fluidd").install()
def install_fluidd_config(self, **kwargs) -> None:
install_client_config(FluiddData())
WebClientConfigSetupService("fluidd").install()
def install_klipperscreen(self, **kwargs) -> None:
install_klipperscreen()
+3 -3
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -95,8 +95,8 @@ class MainMenu(BaseMenu):
status_data: ComponentStatus = status_fn(*args)
code: int = status_data.status
status: StatusText = StatusMap[code]
owner: str = trunc_string(status_data.owner, 23)
repo: str = trunc_string(status_data.repo, 23)
owner: str = trunc_string(status_data.owner, 23) if status_data.owner else '-'
repo: str = trunc_string(status_data.repo, 23) if status_data.repo else '-'
instance_count: int = status_data.instances
count_txt: str = ""
+1 -1
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
+95 -12
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -10,14 +10,17 @@ from __future__ import annotations
from typing import List, Literal, Type
from core.logger import Logger
from core.logger import DialogType, Logger
from core.menus import Option
from core.menus.base_menu import BaseMenu
from core.settings.kiauh_settings import KiauhSettings, Repository
from core.types.color import Color
from procedures.switch_repo import run_switch_repo_routine
from utils.input_utils import get_confirm, get_number_input, get_string_input
# noinspection PyUnusedLocal
# noinspection PyMethodMayBeStatic
class RepoSelectMenu(BaseMenu):
def __init__(
self,
@@ -48,26 +51,27 @@ class RepoSelectMenu(BaseMenu):
def set_options(self) -> None:
self.options = {}
if not self.repos:
return
for idx, repo in enumerate(self.repos, start=1):
self.options[str(idx)] = Option(
method=self.select_repository, opt_data=repo
)
if self.repos:
for idx, repo in enumerate(self.repos, start=1):
self.options[str(idx)] = Option(
method=self.select_repository, opt_data=repo
)
self.options["a"] = Option(method=self.add_repository)
self.options["r"] = Option(method=self.remove_repository)
self.options["b"] = Option(method=self.go_back)
def print_menu(self) -> None:
menu = "╟───────────────────────────────────────────────────────╢\n"
menu += "║ Available Repositories: ║\n"
menu += "╟───────────────────────────────────────────────────────╢\n"
for idx, repo in enumerate(self.repos, start=1):
url = f"● Repo: {repo.url.replace('.git', '')}"
branch = f"└► Branch: {repo.branch}"
menu += f"{idx}) {Color.apply(url, Color.CYAN):<59}\n"
menu += f"{Color.apply(branch, Color.CYAN):<59}\n"
menu += "╟───────────────────────────────────────────────────────╢\n"
menu += "║ A) Add repository ║\n"
menu += "║ R) Remove repository ║\n"
menu += "╟───────────────────────────────────────────────────────╢\n"
print(menu, end="")
@@ -77,3 +81,82 @@ class RepoSelectMenu(BaseMenu):
f"Switching to {self.name.capitalize()}'s new source repository ..."
)
run_switch_repo_routine(self.name, repo.url, repo.branch)
def add_repository(self, **kwargs) -> None:
while True:
Logger.print_dialog(
DialogType.CUSTOM,
custom_title="Enter the repository URL",
content=[
"NOTE: There is no input validation in place, "
"please check your input for correctness",
],
)
url = get_string_input("Repository URL", allow_special_chars=True).strip()
Logger.print_dialog(
DialogType.CUSTOM,
custom_title="Enter the branch name",
content=[ "Press Enter to use the default branch (master)." ],
center_content=False,
)
branch = get_string_input("Branch", allow_special_chars=True, default="master").strip()
Logger.print_dialog(
DialogType.CUSTOM,
custom_title="Summary",
content=[
f"● URL: {url}",
f"● Branch: {branch}",
],
)
confirm = get_confirm("Save repository")
if confirm:
repo = Repository(url, branch)
if self.name == "klipper":
self.settings.klipper.repositories.append(repo)
self.settings.save()
self.repos = self.settings.klipper.repositories
else:
self.settings.moonraker.repositories.append(repo)
self.settings.save()
self.repos = self.settings.moonraker.repositories
Logger.print_ok("Repository added and saved.")
# Refresh menu to show new repo immediately and update options
self.set_options()
self.run()
break
else:
Logger.print_info("Operation cancelled by user.")
break
def remove_repository(self, **kwargs) -> None:
repos = self.repos
if not repos:
Logger.print_info("No repositories configured.")
return
repo_lines = [f"{idx}) {repo.url} [{repo.branch}]" for idx, repo in enumerate(repos, start=1)]
Logger.print_dialog(
DialogType.CUSTOM,
custom_title="Available Repositories",
content=[*repo_lines],
)
idx = get_number_input("Select the repository to remove", 1, len(repos))
removed = repos.pop(idx - 1)
if self.name == "klipper":
self.settings.klipper.repositories = repos
self.settings.save()
self.repos = self.settings.klipper.repositories
else:
self.settings.moonraker.repositories = repos
self.settings.save()
self.repos = self.settings.moonraker.repositories
Logger.print_ok(f"Removed repository: {removed.url} [{removed.branch}]")
# Refresh menu to show updated repo list and options
self.set_options()
self.run()
def go_back(self, **kwargs) -> None:
from core.menus.settings_menu import SettingsMenu
SettingsMenu().run()
+5 -13
View File
@@ -1,5 +1,5 @@
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
@@ -100,11 +100,11 @@ class SettingsMenu(BaseMenu):
def trim_repo_url(repo: str) -> str:
return repo.replace(".git", "").replace("https://", "").replace("git@", "")
if not klipper_status.repo == "-":
if klipper_status.repo:
url = trim_repo_url(klipper_status.repo_url)
self.kl_repo_url = Color.apply(url, Color.CYAN)
self.kl_branch = Color.apply(klipper_status.branch, Color.CYAN)
if not moonraker_status.repo == "-":
if moonraker_status.repo:
url = trim_repo_url(moonraker_status.repo_url)
self.mr_repo_url = Color.apply(url, Color.CYAN)
self.mr_branch = Color.apply(moonraker_status.branch, Color.CYAN)
@@ -117,20 +117,12 @@ class SettingsMenu(BaseMenu):
)
def switch_klipper_repo(self, **kwargs) -> None:
name = "Klipper"
repos = self.settings.klipper.repositories
if not repos:
self._warn_no_repos(name)
return
RepoSelectMenu(name.lower(), repos=repos, previous_menu=self.__class__).run()
RepoSelectMenu("klipper", repos=repos, previous_menu=self.__class__).run()
def switch_moonraker_repo(self, **kwargs) -> None:
name = "Moonraker"
repos = self.settings.moonraker.repositories
if not repos:
self._warn_no_repos(name)
return
RepoSelectMenu(name.lower(), repos=repos, previous_menu=self.__class__).run()
RepoSelectMenu("moonraker", repos=repos, previous_menu=self.__class__).run()
def toggle_mainsail_release(self, **kwargs) -> None:
self.mainsail_unstable = not self.mainsail_unstable
+94
View File
@@ -0,0 +1,94 @@
from __future__ import annotations
from typing import List, Type
import pytest
from core.menus import FooterType, Option
from core.menus.base_menu import (
BaseMenu,
MenuTitleStyle,
PostInitCaller,
print_back_footer,
print_back_help_footer,
print_blank_footer,
print_header,
print_quit_footer,
)
class ConcreteMenu(BaseMenu, metaclass=PostInitCaller):
title = "Concrete"
footer_type = FooterType.BACK
def set_previous_menu(self, previous_menu: Type[BaseMenu] | None) -> None:
self.previous_menu = previous_menu
def set_options(self) -> None:
self.options = {
"1": Option(method=lambda **k: None),
}
def print_menu(self) -> None:
pass
@pytest.fixture
def concrete(monkeypatch: pytest.MonkeyPatch) -> ConcreteMenu:
monkeypatch.setattr("core.menus.base_menu.print_header", lambda: None)
return ConcreteMenu()
class TestBaseMenuHelpers:
def test_print_header_outputs_banner(self, capsys) -> None:
print_header()
captured = capsys.readouterr()
assert "KIAUH" in captured.out
def test_print_quit_footer(self, capsys) -> None:
print_quit_footer()
assert "Quit" in capsys.readouterr().out
def test_print_back_footer(self, capsys) -> None:
print_back_footer()
assert "Back" in capsys.readouterr().out
def test_print_back_help_footer(self, capsys) -> None:
print_back_help_footer()
out = capsys.readouterr().out
assert "Back" in out
assert "Help" in out
def test_print_blank_footer(self, capsys) -> None:
print_blank_footer()
assert "" in capsys.readouterr().out
class TestBaseMenuLifecycle:
def test_direct_instantiation_raises(self) -> None:
with pytest.raises(NotImplementedError):
BaseMenu()
def test_options_include_back_for_back_footer(self, concrete: ConcreteMenu) -> None:
assert "b" in concrete.options
def test_go_back_does_nothing_without_previous_menu(
self, concrete: ConcreteMenu
) -> None:
concrete.previous_menu = None
# should not raise
concrete._BaseMenu__go_back()
def test_exit_calls_system_exit(self, monkeypatch: pytest.MonkeyPatch) -> None:
exits: List[int] = []
monkeypatch.setattr("core.menus.base_menu.sys.exit", lambda c: exits.append(c))
menu = ConcreteMenu()
menu._BaseMenu__exit()
assert exits == [0]
class TestMenuTitleStyle:
def test_style_values(self) -> None:
assert MenuTitleStyle.PLAIN.value == "plain"
assert MenuTitleStyle.STYLED.value == "styled"
+161
View File
@@ -0,0 +1,161 @@
# ======================================================================= #
# Copyright (C) 2020 - 2026 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://github.com/dw-0/kiauh #
# #
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
from __future__ import annotations
from typing import Any, List
import core.menus.install_menu as install_menu_module
import pytest
from core.menus.install_menu import InstallMenu
@pytest.fixture
def menu(monkeypatch: pytest.MonkeyPatch) -> InstallMenu:
# Avoid the heavyweight singleton setup services loading real instances.
monkeypatch.setattr(install_menu_module, "KlipperSetupService", lambda: object())
monkeypatch.setattr(install_menu_module, "MoonrakerSetupService", lambda: object())
return InstallMenu()
def _fake_data(client_dir_exists: bool) -> Any:
return type(
"Client",
(),
{
"client_dir": type(
"P",
(),
{"exists": lambda self: client_dir_exists},
)(),
},
)()
class TestInstallMenuWiring:
def test_options_expose_every_install_entry(self, menu: InstallMenu) -> None:
for key in ("1", "2", "3", "4", "5", "6", "7", "8"):
assert key in menu.options
def test_set_previous_menu_defaults_to_main_menu(
self, menu: InstallMenu, monkeypatch
) -> None:
# importing MainMenu here avoids an import cycle in the module under test
from core.menus.main_menu import MainMenu
menu.set_previous_menu(None)
assert menu.previous_menu is MainMenu
def test_install_mainsail_when_absent_calls_setup_service(
self, menu: InstallMenu, monkeypatch
) -> None:
calls: List[Any] = []
monkeypatch.setattr(
install_menu_module, "MainsailData", lambda: _fake_data(False)
)
monkeypatch.setattr(
install_menu_module,
"WebClientSetupService",
lambda name: type(
"S", (), {"install": lambda self: calls.append(name) or True}
)(),
)
menu.install_mainsail()
assert calls == ["mainsail"]
def test_install_mainsail_when_present_opens_client_install_menu(
self, menu: InstallMenu, monkeypatch
) -> None:
opened: List[Any] = []
monkeypatch.setattr(
install_menu_module, "MainsailData", lambda: _fake_data(True)
)
class _FakeClientInstallMenu:
def __init__(self, client, previous_menu) -> None:
opened.append((client, previous_menu))
def run(self) -> None:
pass
monkeypatch.setattr(
install_menu_module, "ClientInstallMenu", _FakeClientInstallMenu
)
menu.install_mainsail()
assert len(opened) == 1
def test_install_fluidd_when_absent_calls_setup_service(
self, menu: InstallMenu, monkeypatch
) -> None:
calls: List[Any] = []
monkeypatch.setattr(
install_menu_module, "FluiddData", lambda: _fake_data(False)
)
monkeypatch.setattr(
install_menu_module,
"WebClientSetupService",
lambda name: type(
"S", (), {"install": lambda self: calls.append(name) or True}
)(),
)
menu.install_fluidd()
assert calls == ["fluidd"]
def test_install_mainsail_config_delegates_to_config_service(
self, menu: InstallMenu, monkeypatch
) -> None:
calls: List[Any] = []
monkeypatch.setattr(
install_menu_module,
"WebClientConfigSetupService",
lambda name: type(
"S", (), {"install": lambda self: calls.append(name) or True}
)(),
)
menu.install_mainsail_config()
assert calls == ["mainsail"]
def test_install_fluidd_config_delegates_to_config_service(
self, menu: InstallMenu, monkeypatch
) -> None:
calls: List[Any] = []
monkeypatch.setattr(
install_menu_module,
"WebClientConfigSetupService",
lambda name: type(
"S", (), {"install": lambda self: calls.append(name) or True}
)(),
)
menu.install_fluidd_config()
assert calls == ["fluidd"]
def test_install_klipperscreen_and_crowsnest_delegates(
self, menu: InstallMenu, monkeypatch
) -> None:
calls: List[str] = []
monkeypatch.setattr(
install_menu_module, "install_klipperscreen", lambda: calls.append("ks")
)
monkeypatch.setattr(
install_menu_module, "install_crowsnest", lambda: calls.append("cn")
)
menu.install_klipperscreen()
menu.install_crowsnest()
assert calls == ["ks", "cn"]
@@ -0,0 +1,69 @@
from __future__ import annotations
from typing import Any, Dict, List
import pytest
from core.menus.main_menu import MainMenu
@pytest.fixture
def fake_menu(monkeypatch: pytest.MonkeyPatch):
"""Provide an isolated fake menu class and a call log for each test."""
calls: List[Dict[str, Any]] = []
class FakeMenu:
def __init__(self, **kwargs: Any) -> None:
calls.append(kwargs)
def run(self) -> None:
pass
yield FakeMenu, calls
@pytest.fixture
def reset_main_menu(monkeypatch: pytest.MonkeyPatch) -> None:
# silence status fetching during menu construction if any
monkeypatch.setattr(
"core.menus.main_menu.MainMenu._fetch_status", lambda self: None
)
@pytest.mark.parametrize(
"option_key, target",
[
("1", "InstallMenu"),
("2", "UpdateMenu"),
("3", "RemoveMenu"),
("4", "AdvancedMenu"),
("5", "BackupMenu"),
("s", "SettingsMenu"),
("e", "ExtensionsMenu"),
],
)
def test_main_menu_routes_to_submenu(
option_key: str,
target: str,
monkeypatch: pytest.MonkeyPatch,
reset_main_menu,
fake_menu,
) -> None:
fake_menu_cls, calls = fake_menu
monkeypatch.setattr(f"core.menus.main_menu.{target}", fake_menu_cls)
menu = MainMenu()
option = menu.options[option_key]
option.method(opt_index=option.opt_index, opt_data=option.opt_data)
assert len(calls) == 1
assert calls[0].get("previous_menu") is MainMenu
def test_main_menu_quit_exits(monkeypatch: pytest.MonkeyPatch, reset_main_menu) -> None:
exits: List[int] = []
monkeypatch.setattr("core.menus.main_menu.sys.exit", lambda code: exits.append(code))
menu = MainMenu()
menu.options["q"].method()
assert exits == [0]

Some files were not shown because too many files have changed in this diff Show More