34 Commits

Author SHA1 Message Date
f4c7b2e18f chore(pr): add rollback tests and update test descriptions #3
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 2s
CI / build (push) Successful in 6s
Auto Changelog & Release / release (push) Has been skipped
Auto Changelog & Release / changelog-only (push) Successful in 5s
- Add tests for rollback behavior in `writeUnitFiles` on errors
- Simulate file write and delete failures in test scenarios
- Log rollback failures when file deletion is not possible
- Update all test descriptions and comments to English
- Add `testing/mock.ts` dependency in `deno.lock`

This change adds comprehensive tests for the `writeUnitFiles` function to verify that files are properly rolled back if errors occur during their creation. The tests simulate failures when writing `.service` or `.timer` files, as well as when file deletion is blocked, and check that the function responds by cleaning up as expected or logging rollback failures. All test comments and descriptions have been updated to English for clarity. The `testing/mock.ts` dependency was added to enable function stubbing in tests.

#2

Merged from test/fail-write-and-rollback into main
2025-05-30 11:21:41 +02:00
84a883fd8f chore(changelog): update unreleased changelog 2025-05-30 09:21:20 +00:00
e5f9f2c45a chore(changelog): update unreleased changelog
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 2s
Auto Changelog & Release / release (push) Has been skipped
CI / build (pull_request) Successful in 6s
Auto Changelog & Release / changelog-only (push) Successful in 7s
2025-05-30 11:21:10 +02:00
f3c46e1222 chore(deps): update deno.lock with new dependency
- Adds a new dependency to deno.lock for testing utilities
2025-05-30 11:21:10 +02:00
c4f4614a2d test(fs): update test descriptions and comments to English
- Translate all test descriptions and inline comments from German to English
2025-05-30 11:21:10 +02:00
6039d236eb test(fs): add rollback tests for writeUnitFiles errors
- Add tests to verify rollback behavior when file writing fails
- Simulate various error scenarios to ensure proper cleanup
- Log rollback failures when file deletion is prohibited
2025-05-30 11:21:10 +02:00
333341d3fd chore(pr): add default merge message template
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 3s
CI / build (push) Successful in 7s
Auto Changelog & Release / release (push) Has been skipped
Auto Changelog & Release / changelog-only (push) Successful in 6s
- Introduces a template for merge messages in pull requests
- Standardizes format with placeholders for PR details
2025-05-30 11:20:46 +02:00
38afcf210e chore(changelog): update changelog for v0.4.1
All checks were successful
Upload Assets / upload-assets (amd64, linux) (release) Successful in 28s
Upload Assets / upload-assets (arm64, linux) (release) Successful in 29s
2025-05-28 16:34:22 +00:00
28b18dc994 chore(version): bump version to 0.4.1
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 3s
Auto Changelog & Release / changelog-only (push) Has been skipped
CI / build (push) Successful in 7s
Auto Changelog & Release / release (push) Successful in 7s
2025-05-28 18:34:09 +02:00
ede012317b chore(changelog): update unreleased changelog 2025-05-28 16:34:01 +00:00
a22c156dd3 fix(tasks): add read permissions to build scripts
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 3s
CI / build (push) Successful in 6s
Auto Changelog & Release / release (push) Has been skipped
Auto Changelog & Release / changelog-only (push) Successful in 6s
- Allow read permissions in build scripts for both amd64 and arm64 targets
- Ensure compatibility with files required during the build process
2025-05-28 18:33:47 +02:00
d648d5a3f1 chore(changelog): update changelog for v0.4.0
All checks were successful
Upload Assets / upload-assets (amd64, linux) (release) Successful in 28s
Upload Assets / upload-assets (arm64, linux) (release) Successful in 27s
2025-05-28 16:17:26 +00:00
bb51982f6e chore(version): bump to 0.4.0
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 3s
Auto Changelog & Release / changelog-only (push) Has been skipped
CI / build (push) Successful in 6s
Auto Changelog & Release / release (push) Successful in 13s
2025-05-28 18:17:07 +02:00
3416610486 chore(changelog): update unreleased changelog 2025-05-28 16:15:06 +00:00
54d71ba3f0 style(i18n): add missing newline at EOF in JSON files
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 2s
CI / build (push) Successful in 7s
Auto Changelog & Release / release (push) Has been skipped
Auto Changelog & Release / changelog-only (push) Successful in 6s
- Ensures JSON files adhere to standard formatting by adding a newline
  at the end of the file.
2025-05-28 18:14:51 +02:00
c02da70902 feat(vscode): enable Deno support and configure JSON formatting
- Enables Deno integration in VS Code settings
- Sets the default JSON formatter to Deno's extension
- Activates format-on-save for improved workflow
2025-05-28 18:14:51 +02:00
9ad407e531 feat(ci): add CI workflow with format, lint, and test steps
- Introduces a CI workflow triggered on push, pull requests, and manual dispatch
- Includes steps for code formatting, linting, and testing using Deno
- Fails the workflow if any of the steps do not succeed
2025-05-28 18:14:51 +02:00
07730e5761 feat(tasks): add formatting, linting, and CI tasks
- Introduces new tasks for code formatting and linting
- Adds a CI task combining formatting, linting, and testing
2025-05-28 18:14:51 +02:00
1f79c1a15a chore(changelog): update unreleased changelog 2025-05-28 16:10:19 +00:00
440130f782 feat(tasks): include localization files in build commands
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 3s
Auto Changelog & Release / release (push) Has been skipped
Auto Changelog & Release / changelog-only (push) Successful in 6s
- Add German and English localization files to build outputs
- Ensure compiled binaries include required resources for i18n support
2025-05-28 18:10:04 +02:00
2a13ee2539 refactor(cli): integrate i18n support across commands
- Centralize CLI text strings using the i18n module for localization
- Refactor `createCommand` and `createCli` to improve modularity
- Update logging and error messages to use translated strings
2025-05-28 18:09:52 +02:00
8efbee1ba9 test(i18n): add unit tests for localization functions
- Add tests for `loadLocale` to verify translations load correctly
- Add tests for `t` to ensure fallback behavior for missing keys
- Add tests for `getCurrentLanguage` to validate language detection logic
2025-05-28 18:09:24 +02:00
bd5ea80aff feat(i18n): add German and English translations for CLI tool
- Introduce localization files for German and English languages
- Provide translations for CLI tool options and error messages
2025-05-28 18:09:16 +02:00
c9b4c8bd71 feat(i18n): add i18n module for localization support
- Introduce functions to initialize and load locale files dynamically
- Add support for translation keys with placeholder replacements
- Default to English if locale files are missing or not found
- Determine system language using environment variables
2025-05-28 18:09:04 +02:00
dfa92d8069 chore(vscode): update folder listener with i18n directory
- Adds the /src/i18n directory to the folder listener configuration
- Ensures changes in the i18n folder are tracked as part of the setup
2025-05-28 18:08:37 +02:00
ef052e9f66 chore(changelog): update changelog for v0.3.1
All checks were successful
Upload Assets / upload-assets (arm64, linux) (release) Successful in 29s
Upload Assets / upload-assets (amd64, linux) (release) Successful in 43s
2025-05-28 12:40:53 +00:00
c53576a700 chore(version): bump version to 0.3.1
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 3s
Auto Changelog & Release / changelog-only (push) Has been skipped
Auto Changelog & Release / release (push) Successful in 8s
2025-05-28 14:40:42 +02:00
3d74ec37e4 chore(changelog): update unreleased changelog 2025-05-28 12:40:16 +00:00
c4855ed3fb style(workflows): fix formatting and whitespace issues
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 3s
Auto Changelog & Release / release (push) Has been skipped
Auto Changelog & Release / changelog-only (push) Successful in 7s
- Standardize quotes in branch matching patterns
- Remove unnecessary trailing whitespace
- Add export of author and committer dates for consistent tags
- Ensure proper environment variable alignment
2025-05-28 14:39:42 +02:00
07ee03b6be chore(version): bump version to 0.3.0
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 3s
Auto Changelog & Release / changelog-only (push) Has been skipped
Auto Changelog & Release / release (push) Successful in 8s
2025-05-28 14:26:02 +02:00
fb2a62d984 docs(readme): expand CLI option descriptions for clarity
- Add detailed explanations for each CLI option in README files
- Improve consistency and formatting for better readability
- Highlight supported features and usage comprehensively
2025-05-28 14:26:02 +02:00
113103f368 feat(cli): add options for user, home, and working directory
- Add `--run-as` option to specify user for system-wide timers
- Add `--home` option to set the HOME environment variable
- Add `--cwd` option to define the working directory
- Update tests to validate new options and behavior
2025-05-28 14:26:02 +02:00
f112002249 chore(changelog): update unreleased changelog 2025-05-26 15:27:10 +00:00
0c1d8be79f chore(workflows): consolidate release sync into upload workflow
All checks were successful
Auto Changelog & Release / detect-version-change (push) Successful in 3s
Auto Changelog & Release / release (push) Has been skipped
Auto Changelog & Release / changelog-only (push) Successful in 6s
- Remove separate workflow for syncing releases to GitHub
- Integrate release sync steps into the upload-assets workflow
- Simplify workflow management and reduce duplication
2025-05-26 17:27:00 +02:00
26 changed files with 690 additions and 115 deletions

View File

@@ -0,0 +1,5 @@
chore(pr): ${PullRequestTitle} ${PullRequestReference}
${PullRequestDescription}
Merged from ${HeadBranch} into ${BaseBranch}

46
.gitea/workflows/ci.yml Normal file
View File

@@ -0,0 +1,46 @@
name: CI
on:
workflow_dispatch:
push:
branches:
- main
pull_request:
types:
- opened
- synchronize
- reopened
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: denoland/setup-deno@v1
with:
deno-version: v2.x
- name: Format
id: format
continue-on-error: true
run: deno task fmt
- name: Lint
id: lint
continue-on-error: true
run: deno task lint
- name: Test
id: test
continue-on-error: true
run: deno task test
- name: Fail if any step failed
if: |
steps.format.outcome != 'success' ||
steps.lint.outcome != 'success' ||
steps.test.outcome != 'success'
run: |
echo "::error::One or more steps failed"
exit 1

View File

@@ -4,7 +4,7 @@ on:
push:
branches:
- main
- '**'
- "**"
jobs:
detect-version-change:
@@ -125,7 +125,7 @@ jobs:
if: steps.restore-cliff.outputs.cache-hit != 'true'
run: |
cargo install git-cliff --version "${{ steps.cliff_version.outputs.version }}" --features gitea
- name: Generate changelog for release and tag
id: generate-changelog
run: |
@@ -152,7 +152,6 @@ jobs:
echo "changelog_body_path=$BODY" >> $GITHUB_OUTPUT
- name: Commit updated CHANGELOG
run: |
git add CHANGELOG.md
@@ -169,12 +168,14 @@ jobs:
if git rev-parse "v$VERSION" >/dev/null 2>&1; then
echo "Tag v$VERSION already exists, skipping tag creation."
else
export GIT_AUTHOR_DATE="$(date --iso-8601=seconds)"
export GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
git tag -a "v$VERSION" -F "${{ steps.generate-changelog.outputs.changelog_body_path }}" --cleanup=verbatim
git push origin "v$VERSION"
fi
- name: Create Gitea release
env:
env:
RELEASE_PUBLISH_TOKEN: ${{ secrets.RELEASE_PUBLISH_TOKEN }}
run: |
VERSION=${{ steps.version.outputs.value }}

View File

@@ -1,28 +0,0 @@
name: Sync Release to GitHub
on:
workflow_dispatch:
inputs:
tag:
description: "Release tag to synchronize"
required: false
type: string
release:
types: [published, edited]
jobs:
sync-github:
runs-on: ubuntu-22.04
steps:
- name: Run Releases Sync Action
uses: https://git.0xmax42.io/actions/releases-sync@main
with:
gitea_token: ${{ secrets.RELEASE_PUBLISH_TOKEN }}
gitea_url: https://git.0xmax42.io
gitea_owner: maxp
gitea_repo: systemd-timer
tag_name: ${{ inputs.tag || github.event.release.tag_name }}
github_token: ${{ secrets.SYNC_GITHUB_TOKEN }}
github_owner: 0xmax42
github_repo: systemd-timer

View File

@@ -42,3 +42,15 @@ jobs:
- name: Upload SHA256 for ${{ matrix.target }}-${{ matrix.arch }}
run: .gitea/scripts/upload-asset.sh ./dist/systemd-timer-${{ matrix.target }}-${{ matrix.arch }}.sha256 systemd-timer-${{ matrix.target }}-${{ matrix.arch }}.sha256
- name: Run Releases Sync Action
uses: https://git.0xmax42.io/actions/releases-sync@main
with:
gitea_token: ${{ secrets.RELEASE_PUBLISH_TOKEN }}
gitea_url: https://git.0xmax42.io
gitea_owner: maxp
gitea_repo: systemd-timer
tag_name: ${{ github.event.release.tag_name }}
github_token: ${{ secrets.SYNC_GITHUB_TOKEN }}
github_owner: 0xmax42
github_repo: systemd-timer

10
.vscode/settings.json vendored
View File

@@ -10,6 +10,12 @@
"peacock.color": "#c75c5c",
"exportall.config.folderListener": [
"/src/utils",
"/src/types"
]
"/src/types",
"/src/i18n"
],
"deno.enable": true,
"[json]": {
"editor.defaultFormatter": "denoland.vscode-deno"
},
"editor.formatOnSave": true
}

View File

@@ -2,6 +2,64 @@
All notable changes to this project will be documented in this file.
## [unreleased]
### 🧪 Testing
- *(fs)* Update test descriptions and comments to English - ([c4f4614](https://git.0xmax42.io/maxp/systemd-timer/commit/c4f4614a2daee68f9b33b9676106214c65a1a427))
- *(fs)* Add rollback tests for writeUnitFiles errors - ([6039d23](https://git.0xmax42.io/maxp/systemd-timer/commit/6039d236eb7de449ce22b1d9ea718389a3e2261d))
## [0.4.1](https://git.0xmax42.io/maxp/systemd-timer/compare/v0.4.0..v0.4.1) - 2025-05-28
### 🐛 Bug Fixes
- *(tasks)* Add read permissions to build scripts - ([a22c156](https://git.0xmax42.io/maxp/systemd-timer/commit/a22c156dd3d2cf4a24f0eed699f7dfabfae3837a))
## [0.4.0](https://git.0xmax42.io/maxp/systemd-timer/compare/v0.3.1..v0.4.0) - 2025-05-28
### 🚀 Features
- *(vscode)* Enable Deno support and configure JSON formatting - ([c02da70](https://git.0xmax42.io/maxp/systemd-timer/commit/c02da709028e1fbb175d5091fbd9d3ed2940cdcd))
- *(ci)* Add CI workflow with format, lint, and test steps - ([9ad407e](https://git.0xmax42.io/maxp/systemd-timer/commit/9ad407e531270445d9657402fa3e826a7dabd880))
- *(tasks)* Add formatting, linting, and CI tasks - ([07730e5](https://git.0xmax42.io/maxp/systemd-timer/commit/07730e576180be3f6a16b0fda6c6554a86844eee))
- *(tasks)* Include localization files in build commands - ([440130f](https://git.0xmax42.io/maxp/systemd-timer/commit/440130f782b1fc51053164410ead29397b867892))
- *(i18n)* Add German and English translations for CLI tool - ([bd5ea80](https://git.0xmax42.io/maxp/systemd-timer/commit/bd5ea80aff5092118920ea897af6c3f5f9fb2a3b))
- *(i18n)* Add i18n module for localization support - ([c9b4c8b](https://git.0xmax42.io/maxp/systemd-timer/commit/c9b4c8bd71029976fe900b40a2297b52200a216b))
### 🚜 Refactor
- *(cli)* Integrate i18n support across commands - ([2a13ee2](https://git.0xmax42.io/maxp/systemd-timer/commit/2a13ee2539d96d161a9ee398629fa79822d856f2))
### 🎨 Styling
- *(i18n)* Add missing newline at EOF in JSON files - ([54d71ba](https://git.0xmax42.io/maxp/systemd-timer/commit/54d71ba3f00ced25313036d9f10f6fb01feba52a))
### 🧪 Testing
- *(i18n)* Add unit tests for localization functions - ([8efbee1](https://git.0xmax42.io/maxp/systemd-timer/commit/8efbee1ba9b4fc564f5a32fcbc101ff256c5555b))
### ⚙️ Miscellaneous Tasks
- *(vscode)* Update folder listener with i18n directory - ([dfa92d8](https://git.0xmax42.io/maxp/systemd-timer/commit/dfa92d80694b5b104c26e131d1ee7c5cf69ad94c))
## [0.3.1](https://git.0xmax42.io/maxp/systemd-timer/compare/v0.2.3..v0.3.1) - 2025-05-28
### 🚀 Features
- *(cli)* Add options for user, home, and working directory - ([113103f](https://git.0xmax42.io/maxp/systemd-timer/commit/113103f368ead3014165cc708f016a04749f59be))
### 📚 Documentation
- *(readme)* Expand CLI option descriptions for clarity - ([fb2a62d](https://git.0xmax42.io/maxp/systemd-timer/commit/fb2a62d984615caa4035fd5c1e8e64d245499e47))
### 🎨 Styling
- *(workflows)* Fix formatting and whitespace issues - ([c4855ed](https://git.0xmax42.io/maxp/systemd-timer/commit/c4855ed3fbc0ada208690f90932710983daef392))
### ⚙️ Miscellaneous Tasks
- *(workflows)* Consolidate release sync into upload workflow - ([0c1d8be](https://git.0xmax42.io/maxp/systemd-timer/commit/0c1d8be79f0cc331db9029beb46384659f465f6e))
## [0.2.3](https://git.0xmax42.io/maxp/systemd-timer/compare/v0.2.2..v0.2.3) - 2025-05-26
### 🚀 Features

View File

@@ -12,13 +12,17 @@ Ein einfaches CLI-Tool zum schnellen Erzeugen von systemd `.service` und `.timer
- Unterstützt `--user` Timer (für `~/.config/systemd/user/`)
- Optionales Logging (`StandardOutput/StandardError`)
- Unterstützt:
- `--calendar`
- `--exec`
- `--after`
- `--environment`
- `--output`
- `--dry-run`
- Getestet und typisiert mit Deno + Cliffy
- `--calendar`: Zeitplan für den Timer (systemd `OnCalendar`)
- `--exec`: Auszuführendes Kommando (`ExecStart`)
- `--description`: Beschreibung für die Unit
- `--after`: `After=`-Abhängigkeiten in der Service-Unit
- `--environment`: Beliebige `Environment=KEY=VALUE` Einträge
- `--output`: Zielverzeichnis für die generierten Unit-Dateien
- `--run-as`: Setzt `User=` in der Service-Unit (nur systemweite Timer)
- `--home`: Setzt `Environment=HOME=…`
- `--cwd`: Arbeitsverzeichnis des Prozesses (`WorkingDirectory`)
- `--dry-run`: Gibt nur die generierten Inhalte aus, ohne sie zu schreiben
- Getestet und typisiert mit **Deno** + **Cliffy**
---

View File

@@ -13,14 +13,17 @@ A simple CLI tool for quickly generating systemd `.service` and `.timer` units
* Supports `--user` timers (for `~/.config/systemd/user/`)
* Optional logging (`StandardOutput/StandardError`)
* Supports:
* `--calendar`
* `--exec`
* `--after`
* `--environment`
* `--output`
* `--dry-run`
* Tested and typed with Deno + Cliffy
* `--calendar`: Timer schedule (systemd `OnCalendar`)
* `--exec`: Command to execute (`ExecStart`)
* `--description`: Description for the unit
* `--after`: `After=` dependencies in the service unit
* `--environment`: Arbitrary `Environment=KEY=VALUE` entries
* `--output`: Target directory for the generated unit files
* `--run-as`: Sets `User=` in the service unit (only for system-level timers)
* `--home`: Sets `Environment=HOME=…`
* `--cwd`: Working directory for the process (`WorkingDirectory`)
* `--dry-run`: Outputs unit content without writing to disk
* Tested and fully typed with **Deno** + **Cliffy**
---

View File

@@ -1 +1 @@
0.2.3
0.4.1

View File

@@ -2,8 +2,11 @@
"tasks": {
"start": "deno run -A src/mod.ts",
"test": "deno test -A --coverage **/__tests__/*.test.ts",
"build:amd64": "deno compile --target x86_64-unknown-linux-gnu --include=VERSION --allow-env --allow-write --output dist/systemd-timer-linux-amd64 src/mod.ts",
"build:arm64": "deno compile --target aarch64-unknown-linux-gnu --include=VERSION --allow-env --allow-write --output dist/systemd-timer-linux-arm64 src/mod.ts"
"fmt": "deno fmt --check",
"lint": "deno lint",
"ci": "deno task fmt && deno task lint && deno task test", // For local CI checks
"build:amd64": "deno compile --target x86_64-unknown-linux-gnu --include VERSION --include src/i18n/de.json --include src/i18n/en.json --allow-env --allow-write --allow-read --output dist/systemd-timer-linux-amd64 src/mod.ts",
"build:arm64": "deno compile --target aarch64-unknown-linux-gnu --include VERSION --include src/i18n/de.json --include src/i18n/en.json --allow-env --allow-write --allow-read --output dist/systemd-timer-linux-arm64 src/mod.ts"
},
"compilerOptions": {},
"fmt": {

3
deno.lock generated
View File

@@ -168,7 +168,8 @@
"https://deno.land/std@0.224.0/path/windows/relative.ts": "3e1abc7977ee6cc0db2730d1f9cb38be87b0ce4806759d271a70e4997fc638d7",
"https://deno.land/std@0.224.0/path/windows/resolve.ts": "8dae1dadfed9d46ff46cc337c9525c0c7d959fb400a6308f34595c45bdca1972",
"https://deno.land/std@0.224.0/path/windows/to_file_url.ts": "40e560ee4854fe5a3d4d12976cef2f4e8914125c81b11f1108e127934ced502e",
"https://deno.land/std@0.224.0/path/windows/to_namespaced_path.ts": "4ffa4fb6fae321448d5fe810b3ca741d84df4d7897e61ee29be961a6aac89a4c"
"https://deno.land/std@0.224.0/path/windows/to_namespaced_path.ts": "4ffa4fb6fae321448d5fe810b3ca741d84df4d7897e61ee29be961a6aac89a4c",
"https://deno.land/std@0.224.0/testing/mock.ts": "a963181c2860b6ba3eb60e08b62c164d33cf5da7cd445893499b2efda20074db"
},
"workspace": {
"dependencies": [

View File

@@ -1,39 +1,54 @@
import { Command } from '@cliffy/command';
import { generateUnitFiles } from '../templates/unit-generator.ts';
import { TimerOptions } from '../types/options.ts';
import { t } from '../i18n/mod.ts';
export const createCommand = new Command()
.description('Erzeugt eine systemd .service und .timer Unit')
.option(
'--name <name:string>',
'Name der Unit-Dateien (optional, wird sonst aus dem Exec generiert)',
)
.option(
'--exec <cmd:string>',
'Kommando, das durch systemd ausgeführt werden soll',
{ required: true },
)
.option('--calendar <time:string>', 'OnCalendar-Ausdruck für den Timer', {
required: true,
})
.option('--description <desc:string>', 'Beschreibung des Timers')
.option('--user', 'Erstellt die Unit als User-Timer')
.option('--output <dir:string>', 'Zielverzeichnis der Unit-Dateien')
.option(
'--after <target:string>',
'Optionales After= für die Service-Unit',
{ collect: true },
)
.option(
'--environment <env:string>',
'Environment-Variablen im Format KEY=VALUE',
{ collect: true },
)
.option(
'--logfile <file:string>',
'Dateipfad für Log-Ausgabe (stdout/stderr)',
)
.option('--dry-run', 'Gibt die Unit-Dateien nur aus, ohne sie zu schreiben')
.action(async (options: TimerOptions) => {
await generateUnitFiles(options);
});
export function createCommand() {
return new Command()
.description(t('cli_create_description'))
.option(
'--name <name:string>',
t('option_name'),
)
.option(
'--exec <cmd:string>',
t('option_exec'),
{ required: true },
)
.option('--calendar <time:string>', t('option_calendar'), {
required: true,
})
.option('--description <desc:string>', t('option_description'))
.option('--user', t('option_user'))
.option(
'--run-as <user:string>',
t('option_run_as'),
)
.option(
'--home <path:string>',
t('option_home'),
)
.option(
'--cwd <path:string>',
t('option_cwd'),
)
.option('--output <dir:string>', t('option_output'))
.option(
'--after <target:string>',
t('option_after'),
{ collect: true },
)
.option(
'--environment <env:string>',
t('option_environment'),
{ collect: true },
)
.option(
'--logfile <file:string>',
t('option_logfile'),
)
.option('--dry-run', t('option_dry_run'))
.action(async (options: TimerOptions) => {
await generateUnitFiles(options);
});
}

View File

@@ -1,10 +1,12 @@
import { Command } from '@cliffy/command';
import { createCommand } from './create.ts';
import { getVersion } from '../utils/mod.ts';
import { t } from '../i18n/mod.ts';
import { createCommand } from './mod.ts';
await new Command()
.name('systemd-timer')
.version(await getVersion())
.description('CLI Tool zum Erzeugen von systemd .timer und .service Units')
.command('create', createCommand)
.parse(Deno.args);
export async function createCli() {
return new Command()
.name('systemd-timer')
.version(await getVersion())
.description(t('cli_description'))
.command('create', createCommand());
}

2
src/cli/mod.ts Normal file
View File

@@ -0,0 +1,2 @@
export { createCommand } from './create.ts';
export { createCli } from './main.ts';

View File

@@ -0,0 +1,32 @@
import { assertEquals } from 'https://deno.land/std@0.224.0/assert/mod.ts';
import { getCurrentLanguage, loadLocale, t } from '../mod.ts';
Deno.test('loadLocale lade Deutsche Übersetzung', async () => {
await loadLocale('de');
assertEquals(
t('error_write_units'),
'Fehler beim Schreiben der Units:',
);
assertEquals(
t('unit_written_service', { path: '/tmp/service' }),
'Service Unit geschrieben in: /tmp/service',
);
});
Deno.test('t gibt den Schlüssel zurück, wenn dieser nicht gefunden wird', () => {
const result = t('non_existent_key');
assertEquals(result, 'non_existent_key');
});
Deno.test('getCurrentLanguage gibt die Fallback Sprache zurück', () => {
Deno.env.delete('SYSTEMD_TIMER_LANG');
Deno.env.delete('LC_ALL');
Deno.env.delete('LC_MESSAGES');
Deno.env.delete('LANG');
assertEquals(getCurrentLanguage(), 'en');
});
Deno.test('getCurrentLanguage nutz die `SYSTEMD_TIMER_LANG`, wenn gesetzt', () => {
Deno.env.set('SYSTEMD_TIMER_LANG', 'de_DE.UTF-8');
assertEquals(getCurrentLanguage(), 'de');
});

22
src/i18n/de.json Normal file
View File

@@ -0,0 +1,22 @@
{
"cli_description": "CLI-Tool zum Erzeugen von systemd .timer und .service Units",
"cli_create_description": "Erzeugt eine systemd .service und .timer Unit",
"option_name": "Name der Unit-Dateien (optional, wird sonst aus dem Exec generiert)",
"option_exec": "Kommando, das durch systemd ausgeführt werden soll",
"option_calendar": "OnCalendar-Ausdruck für den Timer",
"option_description": "Beschreibung des Timers",
"option_user": "Erstellt die Unit als User-Timer",
"option_run_as": "Führe den systemweiten Timer als bestimmter Benutzer aus (setzt User= in der Service-Unit)",
"option_home": "HOME-Variable für den Service setzen",
"option_cwd": "Arbeitsverzeichnis (WorkingDirectory) für den Service-Prozess",
"option_output": "Zielverzeichnis der Unit-Dateien",
"option_after": "Optionales After= für die Service-Unit",
"option_environment": "Environment-Variablen im Format KEY=VALUE",
"option_logfile": "Dateipfad für Log-Ausgabe (stdout/stderr)",
"option_dry_run": "Gibt die Unit-Dateien nur aus, ohne sie zu schreiben",
"unit_written_service": "Service Unit geschrieben in: {path}",
"unit_written_timer": "Timer Unit geschrieben in: {path}",
"hint_header": "\nℹ️ Hinweis:",
"error_write_units": "Fehler beim Schreiben der Units:",
"rollback_failed": "Rollback fehlgeschlagen:"
}

22
src/i18n/en.json Normal file
View File

@@ -0,0 +1,22 @@
{
"cli_description": "CLI tool for generating systemd .timer and .service units",
"cli_create_description": "Generates a systemd .service and .timer unit",
"option_name": "Name of the unit files (optional, otherwise derived from the exec command)",
"option_exec": "Command to be executed by systemd",
"option_calendar": "OnCalendar expression for the timer",
"option_description": "Description of the timer",
"option_user": "Creates the unit as a user timer",
"option_run_as": "Runs the system-wide timer as a specific user (sets User= in the service unit)",
"option_home": "Sets the HOME variable for the service",
"option_cwd": "Working directory (WorkingDirectory) for the service process",
"option_output": "Target directory for the unit files",
"option_after": "Optional After= directive for the service unit",
"option_environment": "Environment variables in the format KEY=VALUE",
"option_logfile": "File path for log output (stdout/stderr)",
"option_dry_run": "Only outputs the unit files without writing them",
"unit_written_service": "Service unit written to: {path}",
"unit_written_timer": "Timer unit written to: {path}",
"hint_header": "\nℹ️ Note:",
"error_write_units": "Error while writing unit files:",
"rollback_failed": "Rollback failed:"
}

74
src/i18n/i18n.ts Normal file
View File

@@ -0,0 +1,74 @@
/**
* Initializes the i18n module by loading
* the appropriate locale file based on the system language.
*/
export async function initI18n(): Promise<void> {
await loadLocale(getCurrentLanguage());
}
/**
* Contains the loaded translations for the current language.
* The keys represent i18n identifiers, the values are the localized strings.
*/
let translations: Record<string, string> = {};
/**
* Loads the translation file for the specified locale.
*
* Expects a JSON file in the same directory named like `de.json` or `en.json`.
* Falls back to English ('en') if the specified file does not exist.
*
* @param locale - The language code (e.g., 'de', 'en') to load
* @returns Promise that resolves once the translations have been loaded
*/
export async function loadLocale(locale: string): Promise<void> {
try {
const localeUrl = new URL(`./${locale}.json`, import.meta.url);
const file = await Deno.readTextFile(localeUrl);
translations = JSON.parse(file);
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
console.warn(
`Locale '${locale}' not found – falling back to 'en'.`,
);
if (locale !== 'en') {
await loadLocale('en');
}
} else {
console.error('Error loading translation file:', err);
}
}
}
/**
* Translates a given key using the loaded translation data.
* Replaces placeholders in the format `{variable}` with the provided values.
*
* @param key - The i18n key (e.g., 'timer_created')
* @param vars - Optional replacements for placeholders in the string
* @returns The translated string, or the key itself if no translation is found
*/
export function t(key: string, vars: Record<string, string> = {}): string {
let text = translations[key] ?? key;
for (const [k, v] of Object.entries(vars)) {
text = text.replace(`{${k}}`, v);
}
return text;
}
/**
* Determines the current language from the system environment.
*
* Priority: SYSTEMD_TIMER_LANG > LC_ALL > LC_MESSAGES > LANG.
*
* @returns The language code (e.g., 'de', 'en'), defaults to 'en'
*/
export function getCurrentLanguage(): string {
return (
Deno.env.get('SYSTEMD_TIMER_LANG') ??
Deno.env.get('LC_ALL') ??
Deno.env.get('LC_MESSAGES') ??
Deno.env.get('LANG') ??
'en'
).split('.')[0].split('_')[0].toLowerCase();
}

1
src/i18n/mod.ts Normal file
View File

@@ -0,0 +1 @@
export { getCurrentLanguage, initI18n, loadLocale, t } from './i18n.ts';

View File

@@ -1,5 +1,8 @@
import './cli/main.ts';
import { createCli } from './cli/mod.ts';
import { initI18n } from './i18n/mod.ts';
// ────────────────────────────────────────────────
// Entry Point for CLI
// Delegates to src/cli/main.ts, which registers all CLI commands
await initI18n();
await (await createCli()).parse(Deno.args);

View File

@@ -1,4 +1,5 @@
import {
assert,
assertStringIncludes,
} from 'https://deno.land/std@0.224.0/assert/mod.ts';
import { TimerOptions } from '../../types/mod.ts';
@@ -53,3 +54,63 @@ Deno.test('generateUnits berücksichtigt environment und logfile', () => {
assertStringIncludes(serviceUnit, 'StandardOutput=append:/var/log/job.log');
assertStringIncludes(serviceUnit, 'StandardError=append:/var/log/job.log');
});
Deno.test('generateUnits berücksichtigt runAs', () => {
const opts: TimerOptions = {
exec: '/bin/true',
calendar: 'daily',
runAs: 'myuser',
};
const { serviceUnit } = generateUnits('job', opts);
assertStringIncludes(serviceUnit, 'User=myuser');
});
Deno.test('generateUnits berücksichtigt home', () => {
const opts: TimerOptions = {
exec: '/bin/true',
calendar: 'daily',
home: '/home/myuser',
};
const { serviceUnit } = generateUnits('job', opts);
assertStringIncludes(serviceUnit, 'Environment=HOME=/home/myuser');
});
Deno.test('generateUnits berücksichtigt cwd', () => {
const opts: TimerOptions = {
exec: '/bin/true',
calendar: 'daily',
cwd: '/srv/app',
};
const { serviceUnit } = generateUnits('job', opts);
assertStringIncludes(serviceUnit, 'WorkingDirectory=/srv/app');
});
Deno.test('generateUnits verwendet default.target bei User-Timern', () => {
const opts: TimerOptions = {
exec: '/bin/true',
calendar: 'daily',
user: true,
};
const { timerUnit } = generateUnits('job', opts);
assertStringIncludes(timerUnit, 'WantedBy=default.target');
});
Deno.test('generateUnits ignoriert runAs bei --user', () => {
const opts = {
exec: '/bin/true',
calendar: 'daily',
user: true,
runAs: 'should-not-appear',
};
const { serviceUnit } = generateUnits('job', opts);
assert(
!serviceUnit.includes('User=should-not-appear'),
'User= sollte bei --user nicht enthalten sein',
);
});

View File

@@ -1,3 +1,4 @@
import { t } from '../i18n/mod.ts';
import { TimerOptions } from '../types/mod.ts';
import { deriveNameFromExec, writeUnitFiles } from '../utils/mod.ts';
@@ -21,13 +22,13 @@ export async function generateUnitFiles(options: TimerOptions): Promise<void> {
if (result) {
const { servicePath, timerPath } = result;
console.log(`Service Unit geschrieben in: ${servicePath}`);
console.log(`Timer Unit geschrieben in: ${timerPath}`);
console.log(t('unit_written_service', { path: servicePath }));
console.log(t('unit_written_timer', { path: timerPath }));
} else {
return;
}
console.log(`\nℹ️ Hinweis:`);
console.log(t('hint_header'));
if (options.user) {
console.log(` systemctl --user daemon-reload`);
@@ -51,14 +52,18 @@ export function generateUnits(name: string, options: TimerOptions): {
`[Service]`,
`Type=oneshot`,
`ExecStart=${options.exec}`,
...(options.cwd ? [`WorkingDirectory=${options.cwd}`] : []),
...(options.environment?.map((e) => `Environment=${e}`) ?? []),
...(options.home ? [`Environment=HOME=${options.home}`] : []),
...(options.logfile
? [
`StandardOutput=append:${options.logfile}`,
`StandardError=append:${options.logfile}`,
]
: []),
...(options.runAs && !options.user ? [`User=${options.runAs}`] : []),
];
if (options.logfile) {
unitParts.push(`StandardOutput=append:${options.logfile}`);
unitParts.push(`StandardError=append:${options.logfile}`);
}
const serviceUnit = unitParts.join('\n');
const timerParts = [
@@ -70,7 +75,7 @@ export function generateUnits(name: string, options: TimerOptions): {
`Persistent=true`,
``,
`[Install]`,
`WantedBy=timers.target`,
`WantedBy=${options.user ? 'default.target' : 'timers.target'}`,
];
const timerUnit = timerParts.join('\n');

View File

@@ -4,6 +4,9 @@ export interface TimerOptions {
calendar: string;
description?: string;
user?: boolean;
runAs?: string;
home?: string;
cwd?: string;
output?: string;
after?: string[];
environment?: string[];

View File

@@ -3,11 +3,13 @@ import {
assertExists,
assertStringIncludes,
} from 'https://deno.land/std@0.224.0/assert/mod.ts';
import { stub } from 'https://deno.land/std@0.224.0/testing/mock.ts';
import { exists } from 'https://deno.land/std@0.224.0/fs/mod.ts';
import { join } from 'https://deno.land/std@0.224.0/path/mod.ts';
import { resolveUnitTargetPath, writeUnitFiles } from '../mod.ts';
import { TimerOptions } from '../../types/options.ts';
Deno.test('writeUnitFiles schreibt .service und .timer korrekt', async () => {
Deno.test('writeUnitFiles: writes .service and .timer files correctly', async () => {
const tmp = await Deno.makeTempDir({ prefix: 'test-units-' });
const options = {
@@ -26,15 +28,15 @@ Deno.test('writeUnitFiles schreibt .service und .timer korrekt', async () => {
options as TimerOptions,
) as { servicePath: string; timerPath: string };
// Überprüfe Pfade
// Check file paths
assertEquals(servicePath, join(tmp, 'test-backup.service'));
assertEquals(timerPath, join(tmp, 'test-backup.timer'));
// Existieren Dateien?
// Check if files exist
assertExists(await Deno.stat(servicePath));
assertExists(await Deno.stat(timerPath));
// Enthält die Datei den erwarteten Inhalt?
// Check if file contents match expectations
const readService = await Deno.readTextFile(servicePath);
const readTimer = await Deno.readTextFile(timerPath);
@@ -42,18 +44,237 @@ Deno.test('writeUnitFiles schreibt .service und .timer korrekt', async () => {
assertStringIncludes(readTimer, 'OnCalendar=daily');
});
Deno.test('resolveUnitTargetPath mit --output', () => {
Deno.test('resolveUnitTargetPath: with --output', () => {
const result = resolveUnitTargetPath({ output: '/tmp/units', user: false });
assertEquals(result, '/tmp/units');
});
Deno.test('resolveUnitTargetPath mit --user ohne output', () => {
Deno.test('resolveUnitTargetPath: with --user and no output', () => {
Deno.env.set('HOME', '/home/maxp');
const result = resolveUnitTargetPath({ output: undefined, user: true });
assertEquals(result, '/home/maxp/.config/systemd/user');
});
Deno.test('resolveUnitTargetPath ohne output und ohne user', () => {
Deno.test('resolveUnitTargetPath: with no output and no user', () => {
const result = resolveUnitTargetPath({ output: undefined, user: false });
assertEquals(result, '/etc/systemd/system');
});
Deno.test('writeUnitFiles: error writing .timer file triggers rollback', async () => {
const tmp = await Deno.makeTempDir();
const options: TimerOptions = {
output: tmp,
user: false,
exec: '/bin/true',
calendar: 'never',
};
const name = 'fail-timer';
const serviceContent = '[Service]\nExecStart=/bin/true';
const timerContent = '[Timer]\nOnCalendar=never';
const servicePath = join(tmp, `${name}.service`);
const timerPath = join(tmp, `${name}.timer`);
// Simulate: writing the .timer file fails
const originalWrite = Deno.writeTextFile;
const writeStub = stub(
Deno,
'writeTextFile',
async (path: string | URL, data: string | ReadableStream<string>) => {
if (typeof path === 'string' && path.endsWith('.timer')) {
throw new Error('Simulated write error');
} else {
return await originalWrite(path, data);
}
},
);
const result = await writeUnitFiles(
name,
serviceContent,
timerContent,
options,
);
// Expect: function returns undefined
assertEquals(result, undefined);
// Expect: both files have been deleted (rollback)
assertEquals(await exists(servicePath), false);
assertEquals(await exists(timerPath), false);
writeStub.restore();
});
Deno.test('writeUnitFiles: error writing .service file prevents further actions', async () => {
const tmp = await Deno.makeTempDir();
const options: TimerOptions = {
output: tmp,
user: false,
exec: '/bin/true',
calendar: 'weekly',
};
const name = 'fail-service';
const serviceContent = '[Service]\nExecStart=/bin/true';
const timerContent = '[Timer]\nOnCalendar=weekly';
const servicePath = join(tmp, `${name}.service`);
const timerPath = join(tmp, `${name}.timer`);
// Simulate: error writing the .service file
const writeStub = stub(
Deno,
'writeTextFile',
(path: string | URL, _data: string | ReadableStream<string>) => {
if (typeof path === 'string' && path.endsWith('.service')) {
throw new Error('Simulated service write error');
}
return Promise.resolve();
},
);
const result = await writeUnitFiles(
name,
serviceContent,
timerContent,
options,
);
// Expect: function returns undefined
assertEquals(result, undefined);
// Expect: no files were created
assertEquals(await exists(servicePath), false);
assertEquals(await exists(timerPath), false);
writeStub.restore();
});
Deno.test('writeUnitFiles: both files written, then error → full rollback', async () => {
const tmp = await Deno.makeTempDir();
const options: TimerOptions = {
output: tmp,
user: false,
exec: '/bin/true',
calendar: 'never',
};
const name = 'fail-after-write';
const serviceContent = '[Service]\nExecStart=/bin/true';
const timerContent = '[Timer]\nOnCalendar=never';
const servicePath = join(tmp, `${name}.service`);
const timerPath = join(tmp, `${name}.timer`);
let writeCount = 0;
const originalWriteTextFile = Deno.writeTextFile;
const writeStub = stub(
Deno,
'writeTextFile',
async (path: string | URL, data: string | ReadableStream<string>) => {
if (typeof path !== 'string') {
throw new Error('Unexpected path type');
}
// Simulate both writes, then throw an error after the second
writeCount++;
await originalWriteTextFile(path, data);
if (writeCount === 2) {
throw new Error('Simulated error after full write');
}
},
);
const result = await writeUnitFiles(
name,
serviceContent,
timerContent,
options,
);
// Expect: function returns undefined
assertEquals(result, undefined);
// Expect: both files were removed
assertEquals(await exists(servicePath), false);
assertEquals(await exists(timerPath), false);
writeStub.restore();
});
Deno.test('writeUnitFiles: rollback fails if files cannot be deleted', async () => {
const tmp = await Deno.makeTempDir();
const options: TimerOptions = {
output: tmp,
user: false,
exec: '/bin/true',
calendar: 'never',
};
const name = 'rollback-error';
const serviceContent = '[Service]\nExecStart=/bin/true';
const timerContent = '[Timer]\nOnCalendar=never';
const servicePath = join(tmp, `${name}.service`);
const timerPath = join(tmp, `${name}.timer`);
const originalWriteTextFile = Deno.writeTextFile;
const _originalRemove = Deno.remove;
let writeCount = 0;
const writeStub = stub(
Deno,
'writeTextFile',
async (path: string | URL, data: string | ReadableStream<string>) => {
writeCount++;
await originalWriteTextFile(path, data);
if (writeCount === 2) {
throw new Error('Error after full write');
}
},
);
const removeStub = stub(
Deno,
'remove',
// deno-lint-ignore require-await
async (_path: string | URL, _opts?: Deno.RemoveOptions) => {
throw new Error('Deletion forbidden!');
},
);
const logs: string[] = [];
const consoleStub = stub(console, 'error', (...args) => {
logs.push(args.map((a) => String(a)).join(' '));
});
const result = await writeUnitFiles(
name,
serviceContent,
timerContent,
options,
);
assertEquals(result, undefined);
// Files still exist because deletion failed
assertEquals(await exists(servicePath), true);
assertEquals(await exists(timerPath), true);
// Error output contains "rollback_failed"
const combinedLogs = logs.join('\n');
assertStringIncludes(combinedLogs, 'rollback_failed');
writeStub.restore();
removeStub.restore();
consoleStub.restore();
});

View File

@@ -1,6 +1,7 @@
import { ensureDir, exists } from 'https://deno.land/std@0.224.0/fs/mod.ts';
import { join } from 'https://deno.land/std@0.224.0/path/mod.ts';
import { TimerOptions } from '../types/mod.ts';
import { t } from '../i18n/mod.ts';
export async function writeUnitFiles(
name: string,
@@ -28,9 +29,9 @@ export async function writeUnitFiles(
await Deno.remove(timerPath);
}
} catch (rollbackError) {
console.error('Rollback fehlgeschlagen:', rollbackError);
console.error(t('rollback_failed'), rollbackError);
}
console.error('Fehler beim Schreiben der Units:', error);
console.error(t('error_write_units'), error);
return undefined;
}