Compare commits
58 Commits
eba7bff17a
...
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
| e482e3261c | |||
| a926e90196 | |||
| 16cf2b9e30 | |||
| 0cf44e1dfa | |||
| 44bc7ee81e | |||
| 0f171edd75 | |||
| 9a45a7be6f | |||
| 9dd461e35e | |||
| 84e81371c1 | |||
| f11fee10e9 | |||
| bde9a2e33e | |||
| c5f300b670 | |||
| d0dc17a067 | |||
| cebd41a5ac | |||
| 57e6fe410e | |||
| 60aceb75af | |||
| 9d39f5c100 | |||
| 70aa4cbc4d | |||
| 721b049100 | |||
| 5a018d03cb | |||
| e5f8c7a812 | |||
| 5e09ba1d58 | |||
| fe13d1f34e | |||
| 7aa1421639 | |||
| 4d014e2f45 | |||
| 706aa8e6ba | |||
| bfb982cc27 | |||
| 29ce94c3e8 | |||
| e85cbc4eb1 | |||
| 7f4f63eb8e | |||
| c58fe0d332 | |||
| 88511843ce | |||
| e87840e95b | |||
| 33a246cd13 | |||
| 3992b40eda | |||
| 2c684532da | |||
| d3e3d30b42 | |||
| 84212764e4 | |||
| eedae3b9f0 | |||
| bfd9991a3a | |||
| 2ab5f07c7c | |||
| 48faddb3bd | |||
| f4221f6ce4 | |||
| b3eb429fa6 | |||
| 40b609a7d4 | |||
| 3a68c705c6 | |||
| 5d662c7fd5 | |||
| d4ca38b45a | |||
| 48622a99c2 | |||
| 9866673bab | |||
| 2f965166ba | |||
| e9ec48bf15 | |||
| 2c38941f6e | |||
| effd740e45 | |||
| 8bd50d0431 | |||
| 5c89d5ccf1 | |||
| 9216f01bf6 | |||
| aed83b91b9 |
@@ -0,0 +1,26 @@
|
|||||||
|
---
|
||||||
|
description: Review the project as a whole against the agenda in docs/REVIEW.md
|
||||||
|
---
|
||||||
|
|
||||||
|
Perform a whole-project review of GoSentry.
|
||||||
|
|
||||||
|
Read [docs/REVIEW.md](../../docs/REVIEW.md) first — it is the agenda, and its
|
||||||
|
nine sections are the areas to cover. Read [docs/STANDARDS.md](../../docs/STANDARDS.md)
|
||||||
|
and [docs/ARCHITECTURE.md](../../docs/ARCHITECTURE.md) for the rules and
|
||||||
|
contracts the code is checked against.
|
||||||
|
|
||||||
|
$ARGUMENTS narrows the review when given — a package path, a file, or the name
|
||||||
|
of an agenda section. With no arguments, sweep the whole `src/` tree.
|
||||||
|
|
||||||
|
Rules for the report:
|
||||||
|
|
||||||
|
- Anything listed under "Intentional behavior" in STANDARDS.md is not a finding.
|
||||||
|
If you believe such an entry is now wrong, say so explicitly as a challenge to
|
||||||
|
the decision rather than reporting it as a bug.
|
||||||
|
- Verify before reporting. Read the surrounding code and, where cheap, confirm
|
||||||
|
the behavior with a test rather than reasoning about it alone.
|
||||||
|
- Group findings by agenda section, most severe first, each with the file and
|
||||||
|
line and what would actually go wrong.
|
||||||
|
- Report honestly that a section is clean rather than inventing something for it.
|
||||||
|
- Do not fix anything during the review. Report first; apply fixes only when
|
||||||
|
asked, following "What happens to the findings" in REVIEW.md.
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
name: Release
|
||||||
|
|
||||||
|
# Forgejo Actions workflow for Codeberg. It mirrors .github/workflows/release.yml
|
||||||
|
# and reuses the same scripts/ci-build-release.sh, so the actual build/package
|
||||||
|
# commands live in exactly one place. Codeberg has no Windows runners, but the
|
||||||
|
# Windows binary is cross-compiled with MinGW-w64 from the Linux job, so a single
|
||||||
|
# golang:1.22-bookworm container produces all three artifacts.
|
||||||
|
#
|
||||||
|
# Publishing needs a token that can write releases. Add a repository secret named
|
||||||
|
# RELEASE_TOKEN (a Codeberg access token with the "write:repository" scope) under
|
||||||
|
# Settings -> Actions -> Secrets. Without it the build still runs; only the
|
||||||
|
# upload step is skipped.
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types: [published]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
# Codeberg's hosted runners are tagged codeberg-tiny/small/medium (+ -lazy);
|
||||||
|
# there is no "docker" tag. The non-lazy runners cap at 2/5/10 min, which the
|
||||||
|
# three CGO cross-compiles blow past, so use the medium *-lazy* runner, which
|
||||||
|
# relaxes the wall-clock limit (it aims to finish within 24h).
|
||||||
|
runs-on: codeberg-medium-lazy
|
||||||
|
container:
|
||||||
|
image: golang:1.22-bookworm
|
||||||
|
steps:
|
||||||
|
- name: Provide Node.js for JS actions
|
||||||
|
# golang:1.22-bookworm ships no Node, and Codeberg's runner does not
|
||||||
|
# inject one, so JS actions (checkout, forgejo-release) fail with
|
||||||
|
# "node: not found". A run step executes through the container shell and
|
||||||
|
# needs no Node itself, so it can install Node before those actions run.
|
||||||
|
# (If a "node version" error ever appears, swap Debian's nodejs 18 for a
|
||||||
|
# NodeSource node 20 install.)
|
||||||
|
run: |
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y --no-install-recommends nodejs
|
||||||
|
command -v node || ln -s "$(command -v nodejs)" /usr/local/bin/node
|
||||||
|
|
||||||
|
- name: Checkout
|
||||||
|
uses: https://code.forgejo.org/actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install cross toolchain
|
||||||
|
# Same package list as the repo Dockerfile / GitHub workflow: native gcc
|
||||||
|
# plus X11/GL headers, the aarch64 cross compiler with arm64 runtime
|
||||||
|
# libs, MinGW-w64 for the Windows GUI binary, and zip for packaging.
|
||||||
|
run: |
|
||||||
|
dpkg --add-architecture arm64
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates \
|
||||||
|
gcc \
|
||||||
|
libc6-dev \
|
||||||
|
gcc-aarch64-linux-gnu \
|
||||||
|
libc6-dev-arm64-cross \
|
||||||
|
linux-libc-dev-arm64-cross \
|
||||||
|
gcc-mingw-w64-x86-64 \
|
||||||
|
binutils-mingw-w64-x86-64 \
|
||||||
|
pkg-config \
|
||||||
|
libgl1-mesa-dev \
|
||||||
|
xorg-dev \
|
||||||
|
libgl1-mesa-dev:arm64 \
|
||||||
|
libx11-dev:arm64 \
|
||||||
|
libxcursor-dev:arm64 \
|
||||||
|
libxrandr-dev:arm64 \
|
||||||
|
libxinerama-dev:arm64 \
|
||||||
|
libxi-dev:arm64 \
|
||||||
|
libxxf86vm-dev:arm64 \
|
||||||
|
zip
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
- name: Derive version
|
||||||
|
# On a release, strip the leading "v" so artifact names and the injected
|
||||||
|
# app version match the release tag (the release event still sets
|
||||||
|
# GITHUB_REF_TYPE=tag / GITHUB_REF_NAME=<tag>).
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then
|
||||||
|
echo "value=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Build and package
|
||||||
|
env:
|
||||||
|
VERSION: ${{ steps.version.outputs.value }}
|
||||||
|
run: |
|
||||||
|
chmod +x scripts/ci-build-release.sh
|
||||||
|
scripts/ci-build-release.sh
|
||||||
|
|
||||||
|
- name: Collect release files
|
||||||
|
# forgejo-release uploads every file in a single directory, so gather the
|
||||||
|
# archives into one flat folder.
|
||||||
|
run: |
|
||||||
|
mkdir -p dist/release
|
||||||
|
cp dist/linux/*.tar.gz dist/windows/*.zip dist/release/
|
||||||
|
|
||||||
|
- name: Attach assets to release
|
||||||
|
# Only runs for the release event; the release already exists, so this
|
||||||
|
# uploads the built archives to it. Skipped on workflow_dispatch.
|
||||||
|
if: ${{ github.event_name == 'release' }}
|
||||||
|
uses: https://code.forgejo.org/actions/forgejo-release@v2
|
||||||
|
with:
|
||||||
|
direction: upload
|
||||||
|
url: https://codeberg.org
|
||||||
|
repo: ${{ github.repository }}
|
||||||
|
tag: ${{ github.event.release.tag_name }}
|
||||||
|
release-dir: dist/release
|
||||||
|
token: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
override: true
|
||||||
@@ -1,3 +1,8 @@
|
|||||||
# Keep shell scripts LF even on Windows checkouts so bash on Linux hosts
|
# Keep shell scripts LF even on Windows checkouts so bash on Linux hosts
|
||||||
# doesn't choke on trailing CRs (e.g. "set: pipefail: invalid parameter name").
|
# doesn't choke on trailing CRs (e.g. "set: pipefail: invalid parameter name").
|
||||||
*.sh text eol=lf
|
*.sh text eol=lf
|
||||||
|
|
||||||
|
# CI workflow YAML embeds shell in `run:` blocks that Linux runners execute with
|
||||||
|
# bash, so keep these LF for the same reason as the shell scripts above.
|
||||||
|
.github/workflows/*.yml text eol=lf
|
||||||
|
.forgejo/workflows/*.yml text eol=lf
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
name: Release
|
||||||
|
|
||||||
|
# Build the Linux (amd64/arm64) and Windows (amd64) binaries whenever a GitHub
|
||||||
|
# Release is published, then attach the packaged archives to that release.
|
||||||
|
#
|
||||||
|
# Everything runs inside golang:1.22-bookworm — the same base image as the
|
||||||
|
# repo Dockerfile — so the CGO/Fyne toolchain matches the local release builds.
|
||||||
|
# The Windows binary is cross-compiled with MinGW-w64 from the same Linux job,
|
||||||
|
# which is why no windows-latest runner is needed.
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types: [published]
|
||||||
|
# Allow a manual run (from the Actions tab) to smoke-test the build without
|
||||||
|
# publishing a release. Manual runs build the artifacts but upload nothing.
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write # required to create the release and upload assets
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: golang:1.22-bookworm
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install cross toolchain
|
||||||
|
# Mirrors the package list in the repo Dockerfile: native gcc + X11/GL
|
||||||
|
# headers for amd64, the aarch64 cross compiler with arm64 runtime libs,
|
||||||
|
# and the MinGW-w64 toolchain for the Windows GUI binary. zip packages
|
||||||
|
# the Windows archive.
|
||||||
|
run: |
|
||||||
|
dpkg --add-architecture arm64
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates \
|
||||||
|
gcc \
|
||||||
|
libc6-dev \
|
||||||
|
gcc-aarch64-linux-gnu \
|
||||||
|
libc6-dev-arm64-cross \
|
||||||
|
linux-libc-dev-arm64-cross \
|
||||||
|
gcc-mingw-w64-x86-64 \
|
||||||
|
binutils-mingw-w64-x86-64 \
|
||||||
|
pkg-config \
|
||||||
|
libgl1-mesa-dev \
|
||||||
|
xorg-dev \
|
||||||
|
libgl1-mesa-dev:arm64 \
|
||||||
|
libx11-dev:arm64 \
|
||||||
|
libxcursor-dev:arm64 \
|
||||||
|
libxrandr-dev:arm64 \
|
||||||
|
libxinerama-dev:arm64 \
|
||||||
|
libxi-dev:arm64 \
|
||||||
|
libxxf86vm-dev:arm64 \
|
||||||
|
zip
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
- name: Derive version
|
||||||
|
# For a release, use the tag without its leading "v" so the artifact
|
||||||
|
# names and the injected app version match the release (the release
|
||||||
|
# event still sets GITHUB_REF_TYPE=tag / GITHUB_REF_NAME=<tag>).
|
||||||
|
# Otherwise fall back to the version in source (handled by the build
|
||||||
|
# script).
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
ref="${GITHUB_REF_NAME:-}"
|
||||||
|
if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then
|
||||||
|
echo "value=${ref#v}" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Build and package
|
||||||
|
env:
|
||||||
|
VERSION: ${{ steps.version.outputs.value }}
|
||||||
|
run: |
|
||||||
|
chmod +x scripts/ci-build-release.sh
|
||||||
|
scripts/ci-build-release.sh
|
||||||
|
|
||||||
|
- name: Upload build artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: gosentry-release
|
||||||
|
path: |
|
||||||
|
dist/linux/*.tar.gz
|
||||||
|
dist/windows/*.zip
|
||||||
|
|
||||||
|
- name: Attach assets to release
|
||||||
|
# Only runs for the release event; the release already exists, so this
|
||||||
|
# just uploads the built archives to it. Skipped on workflow_dispatch.
|
||||||
|
if: github.event_name == 'release'
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ github.event.release.tag_name }}
|
||||||
|
files: |
|
||||||
|
dist/linux/*.tar.gz
|
||||||
|
dist/windows/*.zip
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
# Build outputs
|
# Build outputs
|
||||||
dist/
|
dist/
|
||||||
|
|
||||||
|
# Persistent Go build cache for Docker-based release builds.
|
||||||
|
.gocache/
|
||||||
|
|
||||||
# Generated Windows resource compiled from packaging/windows/gosentry.rc.
|
# Generated Windows resource compiled from packaging/windows/gosentry.rc.
|
||||||
cmd/gosentry/*.syso
|
cmd/gosentry/*.syso
|
||||||
|
|
||||||
@@ -17,6 +20,10 @@ logs/
|
|||||||
go.work
|
go.work
|
||||||
go.work.sum
|
go.work.sum
|
||||||
|
|
||||||
|
# Claude Code per-developer settings. The shared command in .claude/commands is
|
||||||
|
# tracked; locally granted tool permissions are not.
|
||||||
|
.claude/settings.local.json
|
||||||
|
|
||||||
# GoodSync metadata. This is intentionally kept because the directory is local
|
# GoodSync metadata. This is intentionally kept because the directory is local
|
||||||
# to the user's file synchronization setup.
|
# to the user's file synchronization setup.
|
||||||
_gsdata_/
|
_gsdata_/
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# GoSentry — instructions for Claude Code
|
||||||
|
|
||||||
|
Cross-platform desktop scheduler (Go + Fyne GUI). Single process: GUI,
|
||||||
|
application service, scheduler, storage, and command runner in one binary.
|
||||||
|
|
||||||
|
## Read before changing code
|
||||||
|
|
||||||
|
- [docs/STANDARDS.md](docs/STANDARDS.md) — **required.** Code-quality rules and
|
||||||
|
the list of intentional behavior. Do not "fix" anything listed there as
|
||||||
|
intentional; if a change contradicts it, update the document in the same commit.
|
||||||
|
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — package contracts and event flow.
|
||||||
|
- [docs/TESTS.md](docs/TESTS.md) — test layout and conventions.
|
||||||
|
- [docs/ROADMAP.md](docs/ROADMAP.md) — deliberately out of scope.
|
||||||
|
|
||||||
|
## Reviewing the project
|
||||||
|
|
||||||
|
When the user asks for a review of the project (rather than of a specific
|
||||||
|
diff), follow [docs/REVIEW.md](docs/REVIEW.md) — it is the agenda, and the
|
||||||
|
`/review-project` command runs the same thing. Do not improvise a checklist.
|
||||||
|
|
||||||
|
## Key rules (full list in STANDARDS.md)
|
||||||
|
|
||||||
|
- `src/app.Service` is the sole owner of job and runtime state; the UI reads it
|
||||||
|
through typed events, never through shared mutable state.
|
||||||
|
- User-facing errors go to `dialog.ShowError` or a History event — never a silent
|
||||||
|
`return`.
|
||||||
|
- Pure helpers get a unit test in the same package; fixes of severity ≥ medium get
|
||||||
|
a regression test.
|
||||||
|
- UI view constructors accept an injected `*app.Service`; `app.Open()` is called
|
||||||
|
only from `run.go`.
|
||||||
|
- Off-main-thread widget updates must go through `fyne.Do` (Fyne v2.7.4).
|
||||||
|
|
||||||
|
## Build and test
|
||||||
|
|
||||||
|
CGO is required — the Fyne GUI links native libraries. On Windows the toolchain
|
||||||
|
is MSYS2 UCRT64; the default shell environment here has CGO off, so set it
|
||||||
|
explicitly:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:Path = 'C:\msys64\ucrt64\bin;' + $env:Path; $env:CGO_ENABLED = '1'
|
||||||
|
```
|
||||||
|
|
||||||
|
Then:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
scripts\test.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
which runs `go vet ./...` and `go test -race ./...`. Release binaries come from
|
||||||
|
`scripts\build-windows.bat` / `scripts/build-linux.sh` — see
|
||||||
|
[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md).
|
||||||
|
|
||||||
|
## Repository conventions
|
||||||
|
|
||||||
|
- Commit directly to `main`; do not create feature branches.
|
||||||
|
- Notable changes get a [docs/CHANGELOG.md](docs/CHANGELOG.md) entry under the
|
||||||
|
current version.
|
||||||
|
- The window/taskbar icon comes from the `gosentry.ico` PE resource — regenerate
|
||||||
|
it from the PNGs whenever an icon changes, not just the embedded asset.
|
||||||
@@ -1,3 +1,10 @@
|
|||||||
|
<p align="center">
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="assets/logo/gosentry-logo-dark.svg">
|
||||||
|
<img src="assets/logo/gosentry-logo.svg" alt="GoSentry" width="420">
|
||||||
|
</picture>
|
||||||
|
</p>
|
||||||
|
|
||||||
# GoSentry
|
# GoSentry
|
||||||
|
|
||||||
GoSentry is a cross-platform desktop scheduler. It provides a native GUI for
|
GoSentry is a cross-platform desktop scheduler. It provides a native GUI for
|
||||||
@@ -18,20 +25,36 @@ creating, grouping, pausing, running, and monitoring scheduled shell commands.
|
|||||||
- Job definitions stored in a clean, hand-editable `jobs.json`.
|
- Job definitions stored in a clean, hand-editable `jobs.json`.
|
||||||
- `@every` intervals and standard 5-field cron expressions.
|
- `@every` intervals and standard 5-field cron expressions.
|
||||||
- Manual and scheduled command runs.
|
- Manual and scheduled command runs.
|
||||||
- Parallel or sequential execution mode; configurable overlap policy (skip or queue).
|
- Parallel or sequential execution mode; overlap policy (skip or queue) set globally or per job.
|
||||||
|
- Run timeout, off by default, set globally or per job.
|
||||||
- Per-run `.log` files with stdout/stderr capture.
|
- Per-run `.log` files with stdout/stderr capture.
|
||||||
- Log cleanup by maximum file count and maximum age.
|
- Log cleanup by maximum file count and maximum age.
|
||||||
- Global pause/resume for scheduled job execution (manual runs remain available).
|
- Global pause/resume for scheduled job execution (manual runs remain available).
|
||||||
- Desktop notifications on job failure.
|
- Desktop notifications on job failure.
|
||||||
- Windows tray icon: left-click to show the window, right-click for the menu.
|
- Windows tray icon: left-click to show the window, right-click for the menu.
|
||||||
- Autostart on login (Windows shortcut; Linux XDG desktop entry).
|
- Autostart on login (Windows shortcut; Linux XDG desktop entry).
|
||||||
|
- Detailed or compact job list, and a default or branded theme; both are remembered.
|
||||||
|
|
||||||
|
## Platforms
|
||||||
|
|
||||||
|
GoSentry is built and tested on **Windows** and **Linux**:
|
||||||
|
|
||||||
|
| Platform | Status | Notes |
|
||||||
|
|----------|--------|-------|
|
||||||
|
| Windows | Supported | Tray icon, autostart shortcut (`.lnk`), desktop integration. |
|
||||||
|
| Linux | Supported | Autostart via XDG desktop entry; desktop integration on X11/Wayland. |
|
||||||
|
| macOS | Not supported | The Fyne GUI may build, but autostart and desktop integration are not implemented. |
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
- [Changelog](docs/CHANGELOG.md)
|
- [Changelog](docs/CHANGELOG.md) — record of notable changes by version
|
||||||
- [Roadmap](docs/ROADMAP.md)
|
- [Roadmap](docs/ROADMAP.md) — planned work larger than a single bug fix
|
||||||
- [Architecture](docs/ARCHITECTURE.md)
|
- [Architecture](docs/ARCHITECTURE.md) — component interaction model
|
||||||
|
- [Standards](docs/STANDARDS.md) — quality rules and intentional behavior
|
||||||
|
- [Review](docs/REVIEW.md) — what a whole-project review looks at
|
||||||
- [Development](docs/DEVELOPMENT.md) — build instructions, project layout, dependencies
|
- [Development](docs/DEVELOPMENT.md) — build instructions, project layout, dependencies
|
||||||
|
- [Tests](docs/TESTS.md) — test suite layout and how to run it
|
||||||
|
- [Performance](docs/PERFORMANCE.md) — measured performance findings
|
||||||
|
|
||||||
## Storage
|
## Storage
|
||||||
|
|
||||||
@@ -42,17 +65,29 @@ portable application: moving the program folder also moves its configuration.
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"jobs_dir": ".",
|
"jobs_file": "jobs.json",
|
||||||
"logs_dir": "logs",
|
"logs_dir": "logs",
|
||||||
"max_log_files": 100,
|
"max_log_files": 100,
|
||||||
"max_log_age_days": 30,
|
"max_log_age_days": 30,
|
||||||
"keep_running_in_tray": true,
|
"keep_running_in_tray": true,
|
||||||
"notify_on_failure": true,
|
"notify_on_failure": true,
|
||||||
"execution_mode": "parallel",
|
"execution_mode": "parallel",
|
||||||
"overlap_policy": "skip"
|
"overlap_policy": "skip",
|
||||||
|
"default_timeout_seconds": 0,
|
||||||
|
"theme": "default",
|
||||||
|
"job_list_view": "detailed"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
That is the file GoSentry writes on first run. `default_timeout_seconds` is the
|
||||||
|
run timeout applied to jobs that do not set their own; `0` means no timeout, and
|
||||||
|
it is written out even though it is zero, because a missing value and a
|
||||||
|
deliberate "no timeout" have to stay distinguishable in a hand-edited file.
|
||||||
|
`theme` is `default` or `gosentry` (the branded teal/amber look), and
|
||||||
|
`job_list_view` is `detailed` or `compact` — both are remembered from the
|
||||||
|
choices made in the app. Keys left at their off value (`start_on_login`,
|
||||||
|
`paused`) are omitted until they are turned on.
|
||||||
|
|
||||||
`jobs.json` stores job definitions:
|
`jobs.json` stores job definitions:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
@@ -70,10 +105,15 @@ portable application: moving the program folder also moves its configuration.
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`jobs_dir` is the directory GoSentry reads `jobs.json` from. The default `"."`
|
`jobs_file` is the file GoSentry reads job definitions from, file name included,
|
||||||
means the same folder as the executable. An absolute path can be used when jobs
|
so the file can be named anything. The default `"jobs.json"` is relative and
|
||||||
|
resolves to the executable's folder. An absolute path can be used when jobs
|
||||||
should live elsewhere, such as a shared network drive.
|
should live elsewhere, such as a shared network drive.
|
||||||
|
|
||||||
|
A `gosentry.json` from an earlier version that carries `jobs_dir` instead keeps
|
||||||
|
working: the directory is combined with `jobs.json` on load, and the file is
|
||||||
|
rewritten with `jobs_file`.
|
||||||
|
|
||||||
`logs_dir` is relative to the program folder when it does not start with a
|
`logs_dir` is relative to the program folder when it does not start with a
|
||||||
drive letter or `/`.
|
drive letter or `/`.
|
||||||
|
|
||||||
@@ -111,9 +151,20 @@ Standard 5-field cron expressions:
|
|||||||
5. Use **Pause** on a single job to suspend it without deleting it.
|
5. Use **Pause** on a single job to suspend it without deleting it.
|
||||||
6. Use **Pause all** as a global stop switch for all scheduled runs.
|
6. Use **Pause all** as a global stop switch for all scheduled runs.
|
||||||
7. Open **History** to see past runs, their trigger (`Manual`, `Schedule`, or `UI`), state, and log file.
|
7. Open **History** to see past runs, their trigger (`Manual`, `Schedule`, or `UI`), state, and log file.
|
||||||
8. Open **Settings** to change storage directories, log cleanup limits, queue behavior, and notifications.
|
8. Open **Settings** to change the storage paths, log cleanup limits, queue behavior, and notifications.
|
||||||
|
|
||||||
Changing `jobs_dir` in Settings saves the current job list to the new directory.
|
The **Jobs file** row picks the file itself: **Browse** lists `.json` files, and
|
||||||
|
a path can also be typed to name a file that does not exist yet. What Save does
|
||||||
|
depends on whether that file is already there:
|
||||||
|
|
||||||
|
- **The file exists** — its jobs are loaded and replace the current list, so
|
||||||
|
selecting a jobs file switches to it (another machine's file, a shared one on
|
||||||
|
a network drive). History records how many jobs were loaded and from where.
|
||||||
|
- **The file does not exist** — the current jobs are written to it, which is how
|
||||||
|
the jobs file is renamed or moved somewhere else.
|
||||||
|
|
||||||
|
Switching to a different jobs file is refused while a job is running, because
|
||||||
|
loading a new list discards the run state of the old one.
|
||||||
|
|
||||||
The **Start on login** checkbox shows an `OK` or `Problem` status. Saving with
|
The **Start on login** checkbox shows an `OK` or `Problem` status. Saving with
|
||||||
it enabled writes an autostart entry using the current executable path.
|
it enabled writes an autostart entry using the current executable path.
|
||||||
@@ -122,8 +173,8 @@ without opening the main window.
|
|||||||
|
|
||||||
## Queue Settings
|
## Queue Settings
|
||||||
|
|
||||||
Two settings in the **Queue** group of the Settings tab control how simultaneous
|
Three settings in the **Queue** group of the Settings tab control how
|
||||||
and overlapping runs are handled.
|
simultaneous, overlapping, and over-long runs are handled.
|
||||||
|
|
||||||
**Execution mode** — applies when multiple jobs become due at the same tick:
|
**Execution mode** — applies when multiple jobs become due at the same tick:
|
||||||
|
|
||||||
@@ -132,14 +183,25 @@ and overlapping runs are handled.
|
|||||||
| `parallel` (default) | All due jobs start at the same time. |
|
| `parallel` (default) | All due jobs start at the same time. |
|
||||||
| `sequential` | Due jobs are started one after another, in the order they appear in the list. |
|
| `sequential` | Due jobs are started one after another, in the order they appear in the list. |
|
||||||
|
|
||||||
**Overlap policy** — applies when a job's next scheduled run fires while its
|
**Default overlap policy** — applies when a job's next scheduled run fires while
|
||||||
previous run is still active:
|
its previous run is still active:
|
||||||
|
|
||||||
| Value | Behaviour |
|
| Value | Behaviour |
|
||||||
|-------|-----------|
|
|-------|-----------|
|
||||||
| `skip` (default) | The new run is discarded; the running instance continues. |
|
| `skip` (default) | The new run is discarded; the running instance continues. |
|
||||||
| `queue` | The new run is held and starts immediately after the current run finishes. |
|
| `queue` | The new run is held and starts immediately after the current run finishes. |
|
||||||
|
|
||||||
|
**Default timeout (s)** — how long a run may take before it is killed. `0` (the
|
||||||
|
default) means no limit.
|
||||||
|
|
||||||
|
The last two are defaults: a job's own dialog has an **Overlap policy** and a
|
||||||
|
**Timeout (s)** field that override them. A job that overrides nothing follows
|
||||||
|
whatever the Settings tab says, so changing a default moves every such job with
|
||||||
|
it. In `jobs.json` an override is an `overlap_policy` or `timeout_seconds` key
|
||||||
|
on the job; absent means inherit. A `"timeout_seconds": 0` on a job is an
|
||||||
|
override too — it means that job has no timeout even when the global default
|
||||||
|
sets one.
|
||||||
|
|
||||||
## Notifications
|
## Notifications
|
||||||
|
|
||||||
When **Notify on failure** is enabled in Settings, GoSentry sends a desktop
|
When **Notify on failure** is enabled in Settings, GoSentry sends a desktop
|
||||||
@@ -160,7 +222,7 @@ Linux:
|
|||||||
[Desktop Entry]
|
[Desktop Entry]
|
||||||
Type=Application
|
Type=Application
|
||||||
Name=GoSentry
|
Name=GoSentry
|
||||||
Exec=/opt/gosentry/gosentry-0.9.0-linux-amd64 --start-in-tray
|
Exec=/opt/gosentry/gosentry-<version>-linux-amd64 --start-in-tray
|
||||||
Terminal=false
|
Terminal=false
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -201,10 +263,15 @@ Known workaround:
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
dist\windows\
|
dist\windows\
|
||||||
gosentry-0.9.0-windows-amd64.exe
|
gosentry-<version>-windows-amd64.exe
|
||||||
opengl32.dll
|
opengl32.dll
|
||||||
...
|
...
|
||||||
```
|
```
|
||||||
|
|
||||||
Mesa's software OpenGL implementation lets the Fyne window start even when the
|
Mesa's software OpenGL implementation lets the Fyne window start even when the
|
||||||
VirtualBox/RDP driver does not provide usable OpenGL.
|
VirtualBox/RDP driver does not provide usable OpenGL.
|
||||||
|
|
||||||
|
## Development assistance
|
||||||
|
|
||||||
|
Parts of this project were developed with assistance from [Cursor](https://cursor.com/) AI (Composer agent)
|
||||||
|
and [Claude Code](https://claude.com/claude-code).
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>GoSentry — логотип v3</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@500;600;700&family=Space+Grotesk:wght@500;600;700&family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700&family=Inter:wght@400;500&display=swap" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
:root{
|
||||||
|
--petrol:#0A4A58; --petrol-900:#04262E; --amber:#F7A80C;
|
||||||
|
--ink:#04252C; --paper:#F1F5F5; --line-l:rgba(4,37,44,.12);
|
||||||
|
}
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
body{margin:0;background:var(--paper);color:var(--ink);
|
||||||
|
font-family:"Inter",system-ui,sans-serif;-webkit-font-smoothing:antialiased}
|
||||||
|
.wrap{max-width:1080px;margin:0 auto;padding:0 26px}
|
||||||
|
header{background:radial-gradient(120% 140% at 80% 0%,var(--petrol),var(--petrol-900));color:#fff;padding:50px 0 40px}
|
||||||
|
header .eyebrow{font-family:"Space Grotesk";font-weight:600;font-size:12px;letter-spacing:.2em;text-transform:uppercase;color:var(--amber);margin:0 0 12px}
|
||||||
|
header h1{font-family:"Space Grotesk";font-weight:700;font-size:clamp(24px,4vw,34px);margin:0 0 8px;letter-spacing:-.02em}
|
||||||
|
header p{margin:0;color:rgba(255,255,255,.72);max-width:62ch;font-size:15px}
|
||||||
|
|
||||||
|
section{border-bottom:1px solid var(--line-l);padding:40px 0}
|
||||||
|
.chead{display:flex;align-items:baseline;gap:14px;margin-bottom:6px;flex-wrap:wrap}
|
||||||
|
.num{font-family:"Space Grotesk";font-weight:700;color:var(--amber);font-size:14px}
|
||||||
|
.ctitle{font-family:"Space Grotesk";font-weight:700;font-size:19px;margin:0;letter-spacing:-.01em}
|
||||||
|
.cnote{font-size:14px;color:#4b666e;margin:0 0 22px;max-width:66ch}
|
||||||
|
|
||||||
|
/* wordmark engine */
|
||||||
|
.wm{font-weight:600;letter-spacing:-.03em;line-height:1;white-space:nowrap;display:inline-flex;align-items:baseline}
|
||||||
|
.wm .am{color:var(--amber)} .wm .pe{color:var(--petrol)}
|
||||||
|
.deep .wm .pe{color:#fff}
|
||||||
|
.dial{width:.68em;height:.68em;display:inline-block;transform:translateY(.02em);margin:0 .015em}
|
||||||
|
.f-space{font-family:"Space Grotesk"} .f-sora{font-family:"Sora"} .f-bric{font-family:"Bricolage Grotesque"}
|
||||||
|
|
||||||
|
.hero-stage{display:grid;grid-template-columns:1fr 1fr;gap:16px}
|
||||||
|
.panel{border-radius:16px;min-height:170px;display:flex;align-items:center;justify-content:center;padding:30px;border:1px solid var(--line-l);position:relative}
|
||||||
|
.panel.light{background:#fff}
|
||||||
|
.panel.deep{background:var(--petrol-900);border-color:transparent}
|
||||||
|
.tag{position:absolute;top:12px;left:14px;font-family:"Space Grotesk";font-weight:600;font-size:10px;letter-spacing:.14em;color:rgba(4,37,44,.22);text-transform:uppercase}
|
||||||
|
.deep .tag{color:rgba(255,255,255,.3)}
|
||||||
|
.hero .wm{font-size:clamp(46px,11vw,82px)}
|
||||||
|
|
||||||
|
.row{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}
|
||||||
|
.cell{background:#fff;border:1px solid var(--line-l);border-radius:14px;padding:26px 18px;text-align:center}
|
||||||
|
.cell .lbl{font-family:"Space Grotesk";font-weight:600;font-size:10.5px;letter-spacing:.12em;text-transform:uppercase;color:#5E7580;margin:0 0 16px}
|
||||||
|
.cell .wm{font-size:38px}
|
||||||
|
.rec{display:inline-block;font-family:"Space Grotesk";font-weight:700;font-size:9.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--amber);border:1px solid var(--amber);border-radius:5px;padding:2px 6px;margin-left:8px;vertical-align:1px}
|
||||||
|
|
||||||
|
.faces{display:grid;grid-template-columns:1fr;gap:12px}
|
||||||
|
.frow{background:#fff;border:1px solid var(--line-l);border-radius:14px;padding:20px 26px;display:flex;align-items:center;justify-content:space-between;gap:20px;flex-wrap:wrap}
|
||||||
|
.frow .fn{font-family:"Space Grotesk";font-weight:600;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#5E7580;min-width:150px}
|
||||||
|
.frow .wm{font-size:clamp(34px,7vw,50px)}
|
||||||
|
|
||||||
|
.foot{padding:30px 0 60px;color:#5E7580;font-family:"Space Grotesk";font-weight:500;font-size:12.5px}
|
||||||
|
:focus-visible{outline:3px solid var(--amber);outline-offset:3px}
|
||||||
|
@media (max-width:760px){.hero-stage{grid-template-columns:1fr}.row{grid-template-columns:1fr}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<div class="wrap">
|
||||||
|
<p class="eyebrow">GoSentry / logotype · v3</p>
|
||||||
|
<h1>Two-tone + деталь: «o» как циферблат</h1>
|
||||||
|
<p>В слове уже есть готовый кружок — буква «o» в «Go». Делаем из неё маленький циферблат: тема расписания и «дозора» встроена прямо в надпись, а не приклеена сбоку иконкой.</p>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- HERO: recommended -->
|
||||||
|
<section class="hero"><div class="wrap">
|
||||||
|
<div class="chead"><span class="num">★</span><h3 class="ctitle">Рекомендую: Space Grotesk + стрелки</h3></div>
|
||||||
|
<p class="cnote">Янтарные «G» и циферблат-«o», петрол «Sentry». Циферблат со стрелками сразу читается как часы и держит характер даже мелко.</p>
|
||||||
|
<div class="hero-stage">
|
||||||
|
<div class="panel light"><span class="tag">light</span>
|
||||||
|
<span class="wm f-space"><span class="am">G</span><svg class="dial" viewBox="0 0 100 100"><circle cx="50" cy="50" r="36" fill="none" stroke="#F7A80C" stroke-width="13"/><path d="M50 50 L50 28" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><path d="M50 50 L67 58" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><circle cx="50" cy="50" r="6" fill="#F7A80C"/></svg><span class="pe">Sentry</span></span>
|
||||||
|
</div>
|
||||||
|
<div class="panel deep"><span class="tag">dark</span>
|
||||||
|
<span class="wm f-space"><span class="am">G</span><svg class="dial" viewBox="0 0 100 100"><circle cx="50" cy="50" r="36" fill="none" stroke="#F7A80C" stroke-width="13"/><path d="M50 50 L50 28" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><path d="M50 50 L67 58" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><circle cx="50" cy="50" r="6" fill="#F7A80C"/></svg><span class="pe">Sentry</span></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div></section>
|
||||||
|
|
||||||
|
<!-- dial intensity -->
|
||||||
|
<section><div class="wrap">
|
||||||
|
<div class="chead"><span class="num">01</span><h3 class="ctitle">Насколько «часы» показывать</h3></div>
|
||||||
|
<p class="cnote">Три уровня детали в «o». Слева — обычная буква (деталь почти незаметна), в центре — одна засечка на 12 (тонкий намёк на дозор/время), справа — полноценные стрелки.</p>
|
||||||
|
<div class="row">
|
||||||
|
<div class="cell"><p class="lbl">plain — просто «o»</p>
|
||||||
|
<span class="wm f-space"><span class="am">G</span><svg class="dial" viewBox="0 0 100 100"><circle cx="50" cy="50" r="36" fill="none" stroke="#F7A80C" stroke-width="13"/></svg><span class="pe">Sentry</span></span>
|
||||||
|
</div>
|
||||||
|
<div class="cell"><p class="lbl">tick — засечка на 12</p>
|
||||||
|
<span class="wm f-space"><span class="am">G</span><svg class="dial" viewBox="0 0 100 100"><circle cx="50" cy="50" r="36" fill="none" stroke="#F7A80C" stroke-width="13"/><path d="M50 19 L50 32" stroke="#F7A80C" stroke-width="11" stroke-linecap="round"/><circle cx="50" cy="50" r="5" fill="#F7A80C"/></svg><span class="pe">Sentry</span></span>
|
||||||
|
</div>
|
||||||
|
<div class="cell"><p class="lbl">hands — стрелки <span class="rec">рек.</span></p>
|
||||||
|
<span class="wm f-space"><span class="am">G</span><svg class="dial" viewBox="0 0 100 100"><circle cx="50" cy="50" r="36" fill="none" stroke="#F7A80C" stroke-width="13"/><path d="M50 50 L50 28" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><path d="M50 50 L67 58" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><circle cx="50" cy="50" r="6" fill="#F7A80C"/></svg><span class="pe">Sentry</span></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div></section>
|
||||||
|
|
||||||
|
<!-- face choice in context -->
|
||||||
|
<section><div class="wrap">
|
||||||
|
<div class="chead"><span class="num">02</span><h3 class="ctitle">Шрифт — теперь разница видна</h3></div>
|
||||||
|
<p class="cnote">Одна и та же деталь, три гарнитуры крупно. Смотри на «G», «S», «t», «y» — там весь характер. Space Grotesk — техничный и приметный; Sora — гладкий, нейтральный; Bricolage — самый выразительный, «человечный».</p>
|
||||||
|
<div class="faces">
|
||||||
|
<div class="frow"><span class="fn">Space Grotesk ★</span>
|
||||||
|
<span class="wm f-space"><span class="am">G</span><svg class="dial" viewBox="0 0 100 100"><circle cx="50" cy="50" r="36" fill="none" stroke="#F7A80C" stroke-width="13"/><path d="M50 50 L50 28" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><path d="M50 50 L67 58" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><circle cx="50" cy="50" r="6" fill="#F7A80C"/></svg><span class="pe">Sentry</span></span>
|
||||||
|
</div>
|
||||||
|
<div class="frow"><span class="fn">Sora</span>
|
||||||
|
<span class="wm f-sora"><span class="am">G</span><svg class="dial" viewBox="0 0 100 100"><circle cx="50" cy="50" r="36" fill="none" stroke="#F7A80C" stroke-width="13"/><path d="M50 50 L50 28" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><path d="M50 50 L67 58" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><circle cx="50" cy="50" r="6" fill="#F7A80C"/></svg><span class="pe">Sentry</span></span>
|
||||||
|
</div>
|
||||||
|
<div class="frow"><span class="fn">Bricolage</span>
|
||||||
|
<span class="wm f-bric"><span class="am">G</span><svg class="dial" viewBox="0 0 100 100"><circle cx="50" cy="50" r="36" fill="none" stroke="#F7A80C" stroke-width="13"/><path d="M50 50 L50 28" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><path d="M50 50 L67 58" stroke="#F7A80C" stroke-width="9" stroke-linecap="round"/><circle cx="50" cy="50" r="6" fill="#F7A80C"/></svg><span class="pe">Sentry</span></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div></section>
|
||||||
|
|
||||||
|
<div class="foot"><div class="wrap">Выбери уровень детали (plain / tick / hands) + шрифт — переведу «o»-циферблат и весь логотип в кривые и отдам чистый SVG (light/dark) + PNG.</div></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# GoSentry logo
|
||||||
|
|
||||||
|
Recommended wordmark variant from [`../gosentry-logo.html`](../gosentry-logo.html):
|
||||||
|
**Space Grotesk SemiBold** with an amber **G**, a **clock-dial "o"** (ring + hands),
|
||||||
|
and a petrol **"Sentry"**. The dial sits exactly in the `o` slot, so the schedule /
|
||||||
|
"watch" theme lives inside the letters instead of a bolt-on icon.
|
||||||
|
|
||||||
|
## Colors
|
||||||
|
|
||||||
|
| token | hex | use |
|
||||||
|
|--------|-----------|-----------------------------|
|
||||||
|
| amber | `#F7A80C` | `G`, dial ring + hands |
|
||||||
|
| petrol | `#0A4A58` | `Sentry` (light background) |
|
||||||
|
| white | `#FFFFFF` | `Sentry` (dark background) |
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
Vector (self-contained — glyphs are outlined to paths, no font required):
|
||||||
|
|
||||||
|
- `gosentry-logo.svg` — transparent, petrol `Sentry` (for light backgrounds)
|
||||||
|
- `gosentry-logo-dark.svg` — transparent, white `Sentry` (for dark backgrounds)
|
||||||
|
- `gosentry-logo-mono.svg` — single-color petrol
|
||||||
|
|
||||||
|
Raster (transparent PNG, aspect ≈ 4326×1034 ≈ 4.18:1):
|
||||||
|
|
||||||
|
- `gosentry-logo-{256,512,1024,2048}.png` — petrol `Sentry`
|
||||||
|
- `gosentry-logo-dark-{256,512,1024,2048}.png` — white `Sentry`
|
||||||
|
|
||||||
|
## Regenerating
|
||||||
|
|
||||||
|
Requires `fonttools` and `matplotlib`, plus the Space Grotesk variable font
|
||||||
|
(SIL OFL) instanced to weight 600 as `SpaceGrotesk-600.ttf`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python gen_logo.py # writes SVGs into ./out
|
||||||
|
python raster.py # writes PNGs into ./out
|
||||||
|
```
|
||||||
|
|
||||||
|
`gen_logo.py` (SVG) and `raster.py` (PNG) share the same layout + dial geometry,
|
||||||
|
so both outputs stay identical. Space Grotesk is licensed under the SIL Open Font
|
||||||
|
License; outlining its glyphs into a logo is permitted.
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Generate GoSentry wordmark logo assets (recommended variant:
|
||||||
|
Space Grotesk SemiBold + amber 'G' + clock-dial 'o' with hands + 'Sentry')."""
|
||||||
|
import os
|
||||||
|
from fontTools.ttLib import TTFont
|
||||||
|
from fontTools.pens.svgPathPen import SVGPathPen
|
||||||
|
from fontTools.pens.transformPen import TransformPen
|
||||||
|
from fontTools.pens.boundsPen import BoundsPen
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
OUT = os.path.join(HERE, "out")
|
||||||
|
os.makedirs(OUT, exist_ok=True)
|
||||||
|
|
||||||
|
AMBER = "#F7A80C"
|
||||||
|
PETROL = "#0A4A58"
|
||||||
|
WHITE = "#FFFFFF"
|
||||||
|
|
||||||
|
LS = -30 # letter-spacing -0.03em at 1000 upm
|
||||||
|
|
||||||
|
f = TTFont(os.path.join(HERE, "SpaceGrotesk-600.ttf"))
|
||||||
|
cmap = f.getBestCmap()
|
||||||
|
hmtx = f["hmtx"]
|
||||||
|
gs = f.getGlyphSet()
|
||||||
|
|
||||||
|
def glyph_path(ch, dx):
|
||||||
|
"""Return SVG path 'd' for ch, shifted by dx in font units (y still up)."""
|
||||||
|
g = cmap[ord(ch)]
|
||||||
|
pen = SVGPathPen(gs)
|
||||||
|
tpen = TransformPen(pen, (1, 0, 0, 1, dx, 0))
|
||||||
|
gs[g].draw(tpen)
|
||||||
|
return pen.getCommands(), hmtx[g][0]
|
||||||
|
|
||||||
|
def o_metrics():
|
||||||
|
g = cmap[ord("o")]
|
||||||
|
bp = BoundsPen(gs); gs[g].draw(bp)
|
||||||
|
xmin,ymin,xmax,ymax = bp.bounds
|
||||||
|
return hmtx[g][0], xmin, ymin, xmax, ymax
|
||||||
|
|
||||||
|
# ---- layout the wordmark ---------------------------------------------------
|
||||||
|
x = 0.0
|
||||||
|
G_d, adv = glyph_path("G", x); x += adv + LS
|
||||||
|
|
||||||
|
# dial occupies the 'o' advance slot
|
||||||
|
o_adv, oxmin, oymin, oxmax, oymax = o_metrics()
|
||||||
|
o_left = x
|
||||||
|
cx = o_left + (oxmin + oxmax) / 2.0
|
||||||
|
cy = (oymin + oymax) / 2.0
|
||||||
|
R = ((oxmax - oxmin) + (oymax - oymin)) / 4.0 # avg radius, matches the 'o'
|
||||||
|
x += o_adv + LS
|
||||||
|
|
||||||
|
sentry_d = []
|
||||||
|
for ch in "Sentry":
|
||||||
|
d, adv = glyph_path(ch, x)
|
||||||
|
sentry_d.append(d)
|
||||||
|
x += adv + LS
|
||||||
|
x -= LS # no trailing letter-spacing
|
||||||
|
SENTRY_D = " ".join(sentry_d)
|
||||||
|
|
||||||
|
# ---- dial geometry (matched to the 'o', proportions from the HTML mock) ----
|
||||||
|
SW = R * 0.30 # ring stroke width
|
||||||
|
Rmid = R - SW / 2.0 # centreline radius of ring
|
||||||
|
HW = R * 0.21 # hand width
|
||||||
|
hour_len = R * 0.54 # 12 o'clock hand
|
||||||
|
min_len = R * 0.46 # ~4 o'clock hand
|
||||||
|
min_ang = 62 # degrees clockwise from 12
|
||||||
|
import math
|
||||||
|
mx = cx + min_len * math.sin(math.radians(min_ang))
|
||||||
|
my = cy + min_len * math.cos(math.radians(min_ang)) # font-up: +y is up
|
||||||
|
cap = R * 0.14
|
||||||
|
|
||||||
|
dial = f'''<circle cx="{cx:.1f}" cy="{cy:.1f}" r="{Rmid:.1f}" fill="none" stroke="{AMBER}" stroke-width="{SW:.1f}"/>
|
||||||
|
<path d="M{cx:.1f} {cy:.1f} L{cx:.1f} {cy+hour_len:.1f}" stroke="{AMBER}" stroke-width="{HW:.1f}" stroke-linecap="round"/>
|
||||||
|
<path d="M{cx:.1f} {cy:.1f} L{mx:.1f} {my:.1f}" stroke="{AMBER}" stroke-width="{HW:.1f}" stroke-linecap="round"/>
|
||||||
|
<circle cx="{cx:.1f}" cy="{cy:.1f}" r="{cap:.1f}" fill="{AMBER}"/>'''
|
||||||
|
|
||||||
|
# ---- overall bounds (font units, y up) -------------------------------------
|
||||||
|
bp = BoundsPen(gs)
|
||||||
|
xall = 0.0
|
||||||
|
gG = cmap[ord("G")]; gs[gG].draw(TransformPen(bp,(1,0,0,1,0,0)))
|
||||||
|
xall += hmtx[gG][0] + LS + o_adv + LS
|
||||||
|
for ch in "Sentry":
|
||||||
|
g = cmap[ord(ch)]
|
||||||
|
gs[g].draw(TransformPen(bp,(1,0,0,1,xall,0)))
|
||||||
|
xall += hmtx[g][0] + LS
|
||||||
|
bx0,by0,bx1,by1 = bp.bounds
|
||||||
|
# include the dial extents
|
||||||
|
bx0 = min(bx0, cx-R-SW/2); bx1 = max(bx1, cx+R+SW/2)
|
||||||
|
by0 = min(by0, cy-R-SW/2); by1 = max(by1, cy+R+SW/2)
|
||||||
|
|
||||||
|
PAD = 60
|
||||||
|
W = (bx1 - bx0) + 2*PAD
|
||||||
|
H = (by1 - by0) + 2*PAD
|
||||||
|
# transform: font(x,y up) -> screen: translate then flip y
|
||||||
|
tx = PAD - bx0
|
||||||
|
ty = PAD + by1
|
||||||
|
transform = f"matrix(1 0 0 -1 {tx:.2f} {ty:.2f})"
|
||||||
|
|
||||||
|
def svg(sentry_color, bg=None, name=""):
|
||||||
|
bgrect = f'<rect width="{W:.1f}" height="{H:.1f}" fill="{bg}"/>\n' if bg else ""
|
||||||
|
return f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W:.1f} {H:.1f}" role="img" aria-label="GoSentry">
|
||||||
|
{bgrect}<g transform="{transform}">
|
||||||
|
<path d="{G_d}" fill="{AMBER}"/>
|
||||||
|
<path d="{SENTRY_D}" fill="{sentry_color}"/>
|
||||||
|
{dial}
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
'''
|
||||||
|
|
||||||
|
variants = {
|
||||||
|
"gosentry-logo.svg": svg(PETROL), # light bg, transparent
|
||||||
|
"gosentry-logo-dark.svg": svg(WHITE), # dark bg, transparent
|
||||||
|
"gosentry-logo-onlight.svg": svg(PETROL, bg="#FFFFFF"),
|
||||||
|
"gosentry-logo-ondark.svg": svg(WHITE, bg="#04262E"),
|
||||||
|
"gosentry-logo-mono.svg": svg(PETROL).replace(AMBER, PETROL), # single-colour petrol
|
||||||
|
}
|
||||||
|
for fn, data in variants.items():
|
||||||
|
with open(os.path.join(OUT, fn), "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(data)
|
||||||
|
print("wrote", fn)
|
||||||
|
print("viewBox %.1f x %.1f" % (W, H))
|
||||||
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,10 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4326.0 1034.0" role="img" aria-label="GoSentry">
|
||||||
|
<g transform="matrix(1 0 0 -1 8.00 774.00)">
|
||||||
|
<path d="M312.0 -14Q238.0 -14 179.5 18.5Q121.0 51 86.5 113.5Q52.0 176 52.0 267V433Q52.0 569 128.0 641.5Q204.0 714 332.0 714Q460.0 714 529.0 645.5Q598.0 577 598.0 461V457H480.0V465Q480.0 505 464.0 537.0Q448.0 569 415.0 587.5Q382.0 606 332.0 606Q258.0 606 215.5 560.5Q173.0 515 173.0 435V265Q173.0 186 215.5 139.0Q258.0 92 334.0 92Q410.0 92 445.0 133.0Q480.0 174 480.0 238V250H303.0V352H598.0V0H488.0V69H471.0Q463.0 51 446.0 31.5Q429.0 12 397.5 -1.0Q366.0 -14 312.0 -14Z" fill="#F7A80C"/>
|
||||||
|
<path d="M1524.0 -14Q1444.0 -14 1382.5 14.5Q1321.0 43 1286.0 97.0Q1251.0 151 1251.0 229V255H1370.0V229Q1370.0 160 1412.0 126.0Q1454.0 92 1524.0 92Q1595.0 92 1631.0 121.0Q1667.0 150 1667.0 196Q1667.0 227 1650.0 246.5Q1633.0 266 1600.5 278.0Q1568.0 290 1522.0 301L1492.0 307Q1423.0 323 1372.5 347.5Q1322.0 372 1295.0 411.0Q1268.0 450 1268.0 513Q1268.0 576 1298.0 621.0Q1328.0 666 1383.0 690.0Q1438.0 714 1512.0 714Q1586.0 714 1644.0 689.0Q1702.0 664 1735.5 614.0Q1769.0 564 1769.0 489V456H1650.0V489Q1650.0 532 1633.0 558.0Q1616.0 584 1585.0 596.0Q1554.0 608 1512.0 608Q1450.0 608 1418.0 584.0Q1386.0 560 1386.0 516Q1386.0 488 1400.5 468.5Q1415.0 449 1443.5 436.5Q1472.0 424 1515.0 415L1545.0 408Q1617.0 392 1671.0 367.5Q1725.0 343 1755.5 303.0Q1786.0 263 1786.0 199Q1786.0 136 1753.5 88.0Q1721.0 40 1662.5 13.0Q1604.0 -14 1524.0 -14Z M2091.0 -14Q2017.0 -14 1960.5 17.5Q1904.0 49 1872.5 106.5Q1841.0 164 1841.0 241V253Q1841.0 331 1872.0 388.0Q1903.0 445 1959.0 476.5Q2015.0 508 2088.0 508Q2160.0 508 2214.0 476.5Q2268.0 445 2298.0 388.0Q2328.0 331 2328.0 255V214H1957.0Q1959.0 156 1998.0 121.0Q2037.0 86 2094.0 86Q2150.0 86 2177.0 110.5Q2204.0 135 2218.0 166L2313.0 117Q2299.0 90 2272.5 59.5Q2246.0 29 2202.0 7.5Q2158.0 -14 2091.0 -14ZM1958.0 301H2211.0Q2207.0 350 2173.5 379.0Q2140.0 408 2087.0 408Q2032.0 408 1999.0 379.0Q1966.0 350 1958.0 301Z M2416.0 0V494H2529.0V425H2546.0Q2559.0 453 2593.0 478.0Q2627.0 503 2696.0 503Q2753.0 503 2797.0 477.0Q2841.0 451 2865.5 405.0Q2890.0 359 2890.0 296V0H2775.0V287Q2775.0 347 2745.5 376.5Q2716.0 406 2662.0 406Q2601.0 406 2566.0 365.5Q2531.0 325 2531.0 250V0Z M3189.0 0Q3141.0 0 3112.5 28.5Q3084.0 57 3084.0 106V399H2955.0V494H3084.0V653H3199.0V494H3341.0V399H3199.0V125Q3199.0 95 3227.0 95H3326.0V0Z M3428.0 0V494H3541.0V437H3558.0Q3569.0 468 3595.0 482.0Q3621.0 496 3657.0 496H3717.0V394H3655.0Q3605.0 394 3574.0 367.5Q3543.0 341 3543.0 286V0Z M3844.0 -200V-100H4117.0Q4145.0 -100 4145.0 -70V68H4128.0Q4120.0 50 4102.0 32.5Q4084.0 15 4054.0 3.5Q4024.0 -8 3978.0 -8Q3921.0 -8 3877.0 17.5Q3833.0 43 3809.0 89.5Q3785.0 136 3785.0 198V494H3899.0V207Q3899.0 147 3928.5 118.0Q3958.0 89 4012.0 89Q4073.0 89 4108.5 129.0Q4144.0 169 4144.0 244V494H4258.0V-94Q4258.0 -143 4230.0 -171.5Q4202.0 -200 4154.0 -200Z" fill="#FFFFFF"/>
|
||||||
|
<circle cx="937.5" cy="247.0" r="220.4" fill="none" stroke="#F7A80C" stroke-width="77.8"/>
|
||||||
|
<path d="M937.5 247.0 L937.5 387.0" stroke="#F7A80C" stroke-width="54.4" stroke-linecap="round"/>
|
||||||
|
<path d="M937.5 247.0 L1042.8 303.0" stroke="#F7A80C" stroke-width="54.4" stroke-linecap="round"/>
|
||||||
|
<circle cx="937.5" cy="247.0" r="36.3" fill="#F7A80C"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 3.2 KiB |
@@ -0,0 +1,10 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4326.0 1034.0" role="img" aria-label="GoSentry">
|
||||||
|
<g transform="matrix(1 0 0 -1 8.00 774.00)">
|
||||||
|
<path d="M312.0 -14Q238.0 -14 179.5 18.5Q121.0 51 86.5 113.5Q52.0 176 52.0 267V433Q52.0 569 128.0 641.5Q204.0 714 332.0 714Q460.0 714 529.0 645.5Q598.0 577 598.0 461V457H480.0V465Q480.0 505 464.0 537.0Q448.0 569 415.0 587.5Q382.0 606 332.0 606Q258.0 606 215.5 560.5Q173.0 515 173.0 435V265Q173.0 186 215.5 139.0Q258.0 92 334.0 92Q410.0 92 445.0 133.0Q480.0 174 480.0 238V250H303.0V352H598.0V0H488.0V69H471.0Q463.0 51 446.0 31.5Q429.0 12 397.5 -1.0Q366.0 -14 312.0 -14Z" fill="#0A4A58"/>
|
||||||
|
<path d="M1524.0 -14Q1444.0 -14 1382.5 14.5Q1321.0 43 1286.0 97.0Q1251.0 151 1251.0 229V255H1370.0V229Q1370.0 160 1412.0 126.0Q1454.0 92 1524.0 92Q1595.0 92 1631.0 121.0Q1667.0 150 1667.0 196Q1667.0 227 1650.0 246.5Q1633.0 266 1600.5 278.0Q1568.0 290 1522.0 301L1492.0 307Q1423.0 323 1372.5 347.5Q1322.0 372 1295.0 411.0Q1268.0 450 1268.0 513Q1268.0 576 1298.0 621.0Q1328.0 666 1383.0 690.0Q1438.0 714 1512.0 714Q1586.0 714 1644.0 689.0Q1702.0 664 1735.5 614.0Q1769.0 564 1769.0 489V456H1650.0V489Q1650.0 532 1633.0 558.0Q1616.0 584 1585.0 596.0Q1554.0 608 1512.0 608Q1450.0 608 1418.0 584.0Q1386.0 560 1386.0 516Q1386.0 488 1400.5 468.5Q1415.0 449 1443.5 436.5Q1472.0 424 1515.0 415L1545.0 408Q1617.0 392 1671.0 367.5Q1725.0 343 1755.5 303.0Q1786.0 263 1786.0 199Q1786.0 136 1753.5 88.0Q1721.0 40 1662.5 13.0Q1604.0 -14 1524.0 -14Z M2091.0 -14Q2017.0 -14 1960.5 17.5Q1904.0 49 1872.5 106.5Q1841.0 164 1841.0 241V253Q1841.0 331 1872.0 388.0Q1903.0 445 1959.0 476.5Q2015.0 508 2088.0 508Q2160.0 508 2214.0 476.5Q2268.0 445 2298.0 388.0Q2328.0 331 2328.0 255V214H1957.0Q1959.0 156 1998.0 121.0Q2037.0 86 2094.0 86Q2150.0 86 2177.0 110.5Q2204.0 135 2218.0 166L2313.0 117Q2299.0 90 2272.5 59.5Q2246.0 29 2202.0 7.5Q2158.0 -14 2091.0 -14ZM1958.0 301H2211.0Q2207.0 350 2173.5 379.0Q2140.0 408 2087.0 408Q2032.0 408 1999.0 379.0Q1966.0 350 1958.0 301Z M2416.0 0V494H2529.0V425H2546.0Q2559.0 453 2593.0 478.0Q2627.0 503 2696.0 503Q2753.0 503 2797.0 477.0Q2841.0 451 2865.5 405.0Q2890.0 359 2890.0 296V0H2775.0V287Q2775.0 347 2745.5 376.5Q2716.0 406 2662.0 406Q2601.0 406 2566.0 365.5Q2531.0 325 2531.0 250V0Z M3189.0 0Q3141.0 0 3112.5 28.5Q3084.0 57 3084.0 106V399H2955.0V494H3084.0V653H3199.0V494H3341.0V399H3199.0V125Q3199.0 95 3227.0 95H3326.0V0Z M3428.0 0V494H3541.0V437H3558.0Q3569.0 468 3595.0 482.0Q3621.0 496 3657.0 496H3717.0V394H3655.0Q3605.0 394 3574.0 367.5Q3543.0 341 3543.0 286V0Z M3844.0 -200V-100H4117.0Q4145.0 -100 4145.0 -70V68H4128.0Q4120.0 50 4102.0 32.5Q4084.0 15 4054.0 3.5Q4024.0 -8 3978.0 -8Q3921.0 -8 3877.0 17.5Q3833.0 43 3809.0 89.5Q3785.0 136 3785.0 198V494H3899.0V207Q3899.0 147 3928.5 118.0Q3958.0 89 4012.0 89Q4073.0 89 4108.5 129.0Q4144.0 169 4144.0 244V494H4258.0V-94Q4258.0 -143 4230.0 -171.5Q4202.0 -200 4154.0 -200Z" fill="#0A4A58"/>
|
||||||
|
<circle cx="937.5" cy="247.0" r="220.4" fill="none" stroke="#0A4A58" stroke-width="77.8"/>
|
||||||
|
<path d="M937.5 247.0 L937.5 387.0" stroke="#0A4A58" stroke-width="54.4" stroke-linecap="round"/>
|
||||||
|
<path d="M937.5 247.0 L1042.8 303.0" stroke="#0A4A58" stroke-width="54.4" stroke-linecap="round"/>
|
||||||
|
<circle cx="937.5" cy="247.0" r="36.3" fill="#0A4A58"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 3.2 KiB |
@@ -0,0 +1,10 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4326.0 1034.0" role="img" aria-label="GoSentry">
|
||||||
|
<g transform="matrix(1 0 0 -1 8.00 774.00)">
|
||||||
|
<path d="M312.0 -14Q238.0 -14 179.5 18.5Q121.0 51 86.5 113.5Q52.0 176 52.0 267V433Q52.0 569 128.0 641.5Q204.0 714 332.0 714Q460.0 714 529.0 645.5Q598.0 577 598.0 461V457H480.0V465Q480.0 505 464.0 537.0Q448.0 569 415.0 587.5Q382.0 606 332.0 606Q258.0 606 215.5 560.5Q173.0 515 173.0 435V265Q173.0 186 215.5 139.0Q258.0 92 334.0 92Q410.0 92 445.0 133.0Q480.0 174 480.0 238V250H303.0V352H598.0V0H488.0V69H471.0Q463.0 51 446.0 31.5Q429.0 12 397.5 -1.0Q366.0 -14 312.0 -14Z" fill="#F7A80C"/>
|
||||||
|
<path d="M1524.0 -14Q1444.0 -14 1382.5 14.5Q1321.0 43 1286.0 97.0Q1251.0 151 1251.0 229V255H1370.0V229Q1370.0 160 1412.0 126.0Q1454.0 92 1524.0 92Q1595.0 92 1631.0 121.0Q1667.0 150 1667.0 196Q1667.0 227 1650.0 246.5Q1633.0 266 1600.5 278.0Q1568.0 290 1522.0 301L1492.0 307Q1423.0 323 1372.5 347.5Q1322.0 372 1295.0 411.0Q1268.0 450 1268.0 513Q1268.0 576 1298.0 621.0Q1328.0 666 1383.0 690.0Q1438.0 714 1512.0 714Q1586.0 714 1644.0 689.0Q1702.0 664 1735.5 614.0Q1769.0 564 1769.0 489V456H1650.0V489Q1650.0 532 1633.0 558.0Q1616.0 584 1585.0 596.0Q1554.0 608 1512.0 608Q1450.0 608 1418.0 584.0Q1386.0 560 1386.0 516Q1386.0 488 1400.5 468.5Q1415.0 449 1443.5 436.5Q1472.0 424 1515.0 415L1545.0 408Q1617.0 392 1671.0 367.5Q1725.0 343 1755.5 303.0Q1786.0 263 1786.0 199Q1786.0 136 1753.5 88.0Q1721.0 40 1662.5 13.0Q1604.0 -14 1524.0 -14Z M2091.0 -14Q2017.0 -14 1960.5 17.5Q1904.0 49 1872.5 106.5Q1841.0 164 1841.0 241V253Q1841.0 331 1872.0 388.0Q1903.0 445 1959.0 476.5Q2015.0 508 2088.0 508Q2160.0 508 2214.0 476.5Q2268.0 445 2298.0 388.0Q2328.0 331 2328.0 255V214H1957.0Q1959.0 156 1998.0 121.0Q2037.0 86 2094.0 86Q2150.0 86 2177.0 110.5Q2204.0 135 2218.0 166L2313.0 117Q2299.0 90 2272.5 59.5Q2246.0 29 2202.0 7.5Q2158.0 -14 2091.0 -14ZM1958.0 301H2211.0Q2207.0 350 2173.5 379.0Q2140.0 408 2087.0 408Q2032.0 408 1999.0 379.0Q1966.0 350 1958.0 301Z M2416.0 0V494H2529.0V425H2546.0Q2559.0 453 2593.0 478.0Q2627.0 503 2696.0 503Q2753.0 503 2797.0 477.0Q2841.0 451 2865.5 405.0Q2890.0 359 2890.0 296V0H2775.0V287Q2775.0 347 2745.5 376.5Q2716.0 406 2662.0 406Q2601.0 406 2566.0 365.5Q2531.0 325 2531.0 250V0Z M3189.0 0Q3141.0 0 3112.5 28.5Q3084.0 57 3084.0 106V399H2955.0V494H3084.0V653H3199.0V494H3341.0V399H3199.0V125Q3199.0 95 3227.0 95H3326.0V0Z M3428.0 0V494H3541.0V437H3558.0Q3569.0 468 3595.0 482.0Q3621.0 496 3657.0 496H3717.0V394H3655.0Q3605.0 394 3574.0 367.5Q3543.0 341 3543.0 286V0Z M3844.0 -200V-100H4117.0Q4145.0 -100 4145.0 -70V68H4128.0Q4120.0 50 4102.0 32.5Q4084.0 15 4054.0 3.5Q4024.0 -8 3978.0 -8Q3921.0 -8 3877.0 17.5Q3833.0 43 3809.0 89.5Q3785.0 136 3785.0 198V494H3899.0V207Q3899.0 147 3928.5 118.0Q3958.0 89 4012.0 89Q4073.0 89 4108.5 129.0Q4144.0 169 4144.0 244V494H4258.0V-94Q4258.0 -143 4230.0 -171.5Q4202.0 -200 4154.0 -200Z" fill="#0A4A58"/>
|
||||||
|
<circle cx="937.5" cy="247.0" r="220.4" fill="none" stroke="#F7A80C" stroke-width="77.8"/>
|
||||||
|
<path d="M937.5 247.0 L937.5 387.0" stroke="#F7A80C" stroke-width="54.4" stroke-linecap="round"/>
|
||||||
|
<path d="M937.5 247.0 L1042.8 303.0" stroke="#F7A80C" stroke-width="54.4" stroke-linecap="round"/>
|
||||||
|
<circle cx="937.5" cy="247.0" r="36.3" fill="#F7A80C"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 3.2 KiB |
@@ -0,0 +1,97 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Rasterize the GoSentry wordmark to PNG at several widths, reusing the
|
||||||
|
same font outlines + dial geometry as gen_logo.py (no SVG rasterizer needed)."""
|
||||||
|
import os, math
|
||||||
|
import matplotlib
|
||||||
|
matplotlib.use("Agg")
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
from matplotlib.path import Path
|
||||||
|
from matplotlib.patches import PathPatch, Circle
|
||||||
|
from matplotlib.lines import Line2D
|
||||||
|
from fontTools.ttLib import TTFont
|
||||||
|
from fontTools.pens.basePen import BasePen
|
||||||
|
from fontTools.pens.boundsPen import BoundsPen
|
||||||
|
from fontTools.pens.transformPen import TransformPen
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
OUT = os.path.join(HERE, "out"); os.makedirs(OUT, exist_ok=True)
|
||||||
|
AMBER, PETROL, WHITE = "#F7A80C", "#0A4A58", "#FFFFFF"
|
||||||
|
LS = -30
|
||||||
|
|
||||||
|
f = TTFont(os.path.join(HERE, "SpaceGrotesk-600.ttf"))
|
||||||
|
cmap, hmtx, gs = f.getBestCmap(), f["hmtx"], f.getGlyphSet()
|
||||||
|
|
||||||
|
class MplPen(BasePen):
|
||||||
|
def __init__(self, glyphSet):
|
||||||
|
super().__init__(glyphSet); self.v=[]; self.c=[]
|
||||||
|
def _moveTo(self,p): self.v.append(p); self.c.append(Path.MOVETO)
|
||||||
|
def _lineTo(self,p): self.v.append(p); self.c.append(Path.LINETO)
|
||||||
|
def _curveToOne(self,p1,p2,p3):
|
||||||
|
self.v += [p1,p2,p3]; self.c += [Path.CURVE4]*3
|
||||||
|
def _qCurveToOne(self,p1,p2):
|
||||||
|
self.v += [p1,p2]; self.c += [Path.CURVE3]*2
|
||||||
|
def _closePath(self):
|
||||||
|
self.v.append((0,0)); self.c.append(Path.CLOSEPOLY)
|
||||||
|
|
||||||
|
def glyph_mplpath(ch, dx):
|
||||||
|
pen = MplPen(gs)
|
||||||
|
gs[cmap[ord(ch)]].draw(TransformPen(pen,(1,0,0,1,dx,0)))
|
||||||
|
return Path(pen.v, pen.c), hmtx[cmap[ord(ch)]][0]
|
||||||
|
|
||||||
|
# layout
|
||||||
|
x=0.0
|
||||||
|
paths_amber=[]; paths_petrol=[]
|
||||||
|
p,adv = glyph_mplpath("G",x); paths_amber.append(p); x+=adv+LS
|
||||||
|
og=cmap[ord("o")]; bp=BoundsPen(gs); gs[og].draw(bp)
|
||||||
|
oxmin,oymin,oxmax,oymax=bp.bounds; o_adv=hmtx[og][0]
|
||||||
|
cx=x+(oxmin+oxmax)/2; cy=(oymin+oymax)/2
|
||||||
|
R=((oxmax-oxmin)+(oymax-oymin))/4
|
||||||
|
x+=o_adv+LS
|
||||||
|
for ch in "Sentry":
|
||||||
|
p,adv=glyph_mplpath(ch,x); paths_petrol.append(p); x+=adv+LS
|
||||||
|
x-=LS
|
||||||
|
|
||||||
|
SW=R*0.30; Rmid=R-SW/2; HW=R*0.21
|
||||||
|
hour_len=R*0.54; min_len=R*0.46; ang=math.radians(62)
|
||||||
|
mx=cx+min_len*math.sin(ang); my=cy+min_len*math.cos(ang); cap=R*0.14
|
||||||
|
|
||||||
|
# bounds
|
||||||
|
allb=BoundsPen(gs); gs[cmap[ord('G')]].draw(allb)
|
||||||
|
xx=hmtx[cmap[ord('G')]][0]+LS+o_adv+LS
|
||||||
|
for ch in "Sentry":
|
||||||
|
gs[cmap[ord(ch)]].draw(TransformPen(allb,(1,0,0,1,xx,0))); xx+=hmtx[cmap[ord(ch)]][0]+LS
|
||||||
|
bx0,by0,bx1,by1=allb.bounds
|
||||||
|
bx0=min(bx0,cx-R-SW/2); bx1=max(bx1,cx+R+SW/2)
|
||||||
|
by0=min(by0,cy-R-SW/2); by1=max(by1,cy+R+SW/2)
|
||||||
|
PAD=60
|
||||||
|
X0,X1=bx0-PAD,bx1+PAD; Y0,Y1=by0-PAD,by1+PAD
|
||||||
|
W=X1-X0; H=Y1-Y0
|
||||||
|
|
||||||
|
def render(path_png, width_px, sentry_color, bg=None, mono=False):
|
||||||
|
dpi=100
|
||||||
|
fw=width_px/dpi; fh=fw*H/W
|
||||||
|
fig=plt.figure(figsize=(fw,fh),dpi=dpi)
|
||||||
|
ax=fig.add_axes([0,0,1,1]); ax.set_xlim(X0,X1); ax.set_ylim(Y0,Y1)
|
||||||
|
ax.set_aspect('equal'); ax.axis('off')
|
||||||
|
if bg: fig.patch.set_facecolor(bg); ax.set_facecolor(bg)
|
||||||
|
else: fig.patch.set_alpha(0)
|
||||||
|
amberc = sentry_color if mono else AMBER
|
||||||
|
for p in paths_amber: ax.add_patch(PathPatch(p,facecolor=amberc,edgecolor='none',antialiased=True))
|
||||||
|
for p in paths_petrol: ax.add_patch(PathPatch(p,facecolor=sentry_color,edgecolor='none',antialiased=True))
|
||||||
|
pt_per_unit = fw/W*72
|
||||||
|
ax.add_patch(Circle((cx,cy),Rmid,fill=False,edgecolor=amberc,linewidth=SW*pt_per_unit))
|
||||||
|
for (ex,ey) in [(cx,cy+hour_len),(mx,my)]:
|
||||||
|
ax.add_line(Line2D([cx,ex],[cy,ey],color=amberc,linewidth=HW*pt_per_unit,
|
||||||
|
solid_capstyle='round'))
|
||||||
|
ax.add_patch(Circle((cx,cy),cap,facecolor=amberc,edgecolor='none'))
|
||||||
|
fig.savefig(path_png,dpi=dpi,transparent=(bg is None))
|
||||||
|
plt.close(fig)
|
||||||
|
print("wrote",os.path.basename(path_png))
|
||||||
|
|
||||||
|
for w in (256,512,1024,2048):
|
||||||
|
render(os.path.join(OUT,f"gosentry-logo-{w}.png"),w,PETROL)
|
||||||
|
render(os.path.join(OUT,f"gosentry-logo-dark-{w}.png"),w,WHITE)
|
||||||
|
render(os.path.join(OUT,"gosentry-logo-onlight-1024.png"),1024,PETROL,bg="#FFFFFF")
|
||||||
|
render(os.path.join(OUT,"gosentry-logo-ondark-1024.png"),1024,WHITE,bg="#04262E")
|
||||||
|
render(os.path.join(OUT,"gosentry-logo-mono-1024.png"),1024,PETROL,mono=True)
|
||||||
|
print(f"aspect {W:.0f}x{H:.0f}")
|
||||||
@@ -17,7 +17,8 @@ src/
|
|||||||
storage/ JSON persistence (gosentry.json, jobs.json)
|
storage/ JSON persistence (gosentry.json, jobs.json)
|
||||||
platform/
|
platform/
|
||||||
autostart/ Manager interface + Windows (shortcut) and Linux (XDG) impls
|
autostart/ Manager interface + Windows (shortcut) and Linux (XDG) impls
|
||||||
desktop/ display-scale helper (Linux only)
|
desktop/ desktop entry + icon under XDG data home (Linux only)
|
||||||
|
filemanager/ open a folder in the desktop file manager
|
||||||
winproc/ hidden-window startup flags (Windows only)
|
winproc/ hidden-window startup flags (Windows only)
|
||||||
ui/ Fyne windows, tabs, and dialogs; reads service via Events
|
ui/ Fyne windows, tabs, and dialogs; reads service via Events
|
||||||
```
|
```
|
||||||
@@ -27,19 +28,19 @@ src/
|
|||||||
```mermaid
|
```mermaid
|
||||||
flowchart LR
|
flowchart LR
|
||||||
user["Desktop user"]
|
user["Desktop user"]
|
||||||
ui["src/ui\nFyne windows, tabs, dialogs"]
|
ui["src/ui - Fyne windows, tabs, dialogs"]
|
||||||
svc["src/app Service\nsole owner of job + runtime state"]
|
svc["src/app Service - sole owner of job + runtime state"]
|
||||||
store["src/storage Store\nJSON config and jobs"]
|
store["src/storage Store - JSON config and jobs"]
|
||||||
sched["src/scheduler Scheduler\npure timing loop"]
|
sched["src/scheduler Scheduler - pure timing loop"]
|
||||||
runner["src/runner\nshell command execution"]
|
runner["src/runner - shell command execution"]
|
||||||
autostart["src/platform/autostart Manager\nWindows shortcut / Linux XDG"]
|
autostart["src/platform/autostart Manager - Windows shortcut / Linux XDG"]
|
||||||
config["gosentry.json\napplication settings"]
|
config["gosentry.json - application settings"]
|
||||||
jobs["jobs.json\njob definitions"]
|
jobs["jobs.json - job definitions"]
|
||||||
logs["logs_dir\nper-run command output logs"]
|
logs["logs_dir - per-run command output logs"]
|
||||||
shell["Platform shell\ncmd.exe /C or sh -c"]
|
shell["Platform shell - cmd.exe /C or sh -c"]
|
||||||
|
|
||||||
user -->|"edits jobs, settings, runs commands"| ui
|
user -->|"edits jobs, settings, runs commands"| ui
|
||||||
ui -->|"CreateJob, UpdateJob, DeleteJob, RunNow, UpdateSettings, …"| svc
|
ui -->|"CreateJob, UpdateJob, DeleteJob, RunNow, UpdateSettings, AutostartStatus, …"| svc
|
||||||
svc -->|"SaveJobs, SaveConfig, LoadJobs, LoadConfig"| store
|
svc -->|"SaveJobs, SaveConfig, LoadJobs, LoadConfig"| store
|
||||||
store -->|"read/write"| config
|
store -->|"read/write"| config
|
||||||
store -->|"read/write"| jobs
|
store -->|"read/write"| jobs
|
||||||
@@ -50,10 +51,9 @@ flowchart LR
|
|||||||
runner -->|"execute command"| shell
|
runner -->|"execute command"| shell
|
||||||
runner -->|"write stdout/stderr log"| logs
|
runner -->|"write stdout/stderr log"| logs
|
||||||
runner -->|"RunRecord"| svc
|
runner -->|"RunRecord"| svc
|
||||||
svc -->|"emit JobChanged / RunRecorded / ErrorOccurred"| ui
|
svc -->|"emit JobChanged / RunRecorded / JobsLoaded / ErrorOccurred"| ui
|
||||||
ui -->|"display jobs, history, status"| user
|
ui -->|"display jobs, history, status"| user
|
||||||
|
|
||||||
ui -->|"SetAutostart, AutostartStatus"| autostart
|
|
||||||
svc -->|"Set / Status via Manager"| autostart
|
svc -->|"Set / Status via Manager"| autostart
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -63,7 +63,7 @@ flowchart LR
|
|||||||
`cmd/gosentry` calls `ui.Run`, which creates an `app.Service`, opens the
|
`cmd/gosentry` calls `ui.Run`, which creates an `app.Service`, opens the
|
||||||
store, loads `gosentry.json` and `jobs.json`, subscribes the UI to service
|
store, loads `gosentry.json` and `jobs.json`, subscribes the UI to service
|
||||||
events, builds the main window, and calls `Service.Start` to begin the
|
events, builds the main window, and calls `Service.Start` to begin the
|
||||||
scheduler loop. On first launch the service seeds per-job run-time statistics
|
scheduler loop. On every launch the service seeds per-job run-time statistics
|
||||||
from existing log files so the details panel reflects accumulated history
|
from existing log files so the details panel reflects accumulated history
|
||||||
immediately (see §Statistics below).
|
immediately (see §Statistics below).
|
||||||
|
|
||||||
@@ -74,6 +74,14 @@ flowchart LR
|
|||||||
`Event`. The UI's observer receives the event and refreshes the relevant
|
`Event`. The UI's observer receives the event and refreshes the relevant
|
||||||
widget on the main thread via `fyne.Do`.
|
widget on the main thread via `fyne.Do`.
|
||||||
|
|
||||||
|
`UpdateSettings` has one extra step: when the configured jobs file changes
|
||||||
|
and a file already exists at the new path, that file is authoritative. The
|
||||||
|
Service loads it, calls `adoptJobsLocked` to rebuild the jobs slice, runtime
|
||||||
|
map, schedule cache, next-run times, and log-seeded statistics around it, and
|
||||||
|
emits `JobsLoaded` plus a broad `JobChanged`. A path with no file behind it
|
||||||
|
receives the current jobs instead. Adoption drops all runtime state, so it is
|
||||||
|
refused while a job is running.
|
||||||
|
|
||||||
3. Scheduled run:
|
3. Scheduled run:
|
||||||
`scheduler.Scheduler` fires a tick every second. On each tick it calls
|
`scheduler.Scheduler` fires a tick every second. On each tick it calls
|
||||||
`Service.RunDue(now)`. The Service checks which enabled, non-paused jobs are
|
`Service.RunDue(now)`. The Service checks which enabled, non-paused jobs are
|
||||||
@@ -87,8 +95,9 @@ flowchart LR
|
|||||||
|
|
||||||
5. Command execution:
|
5. Command execution:
|
||||||
`runner.RunJob` builds the platform-specific invocation, executes the
|
`runner.RunJob` builds the platform-specific invocation, executes the
|
||||||
command through the platform shell, captures stdout and stderr, writes one
|
command through the platform shell under the caller-supplied timeout, captures
|
||||||
timestamped `.log` file, and returns a `domain.RunRecord` containing
|
stdout and stderr, writes one timestamped `.log` file, and returns a
|
||||||
|
`domain.RunRecord` containing
|
||||||
`DurationMS` (wall-clock milliseconds from start to finish; for `StartOnly`
|
`DurationMS` (wall-clock milliseconds from start to finish; for `StartOnly`
|
||||||
fire-and-forget jobs it measures launch latency — the time to spawn the
|
fire-and-forget jobs it measures launch latency — the time to spawn the
|
||||||
process — since there is no exit to wait for).
|
process — since there is no exit to wait for).
|
||||||
@@ -97,6 +106,9 @@ flowchart LR
|
|||||||
When a run goroutine completes, `Service` updates the job's runtime
|
When a run goroutine completes, `Service` updates the job's runtime
|
||||||
(including the statistics aggregate), saves JSON, triggers log cleanup, and
|
(including the statistics aggregate), saves JSON, triggers log cleanup, and
|
||||||
emits `RunRecorded`. The UI observer appends the record to the History tab.
|
emits `RunRecorded`. The UI observer appends the record to the History tab.
|
||||||
|
History rows exist only for the current process session; restarting the app
|
||||||
|
clears the table (aggregate stats in the details panel are still seeded from
|
||||||
|
log files).
|
||||||
|
|
||||||
7. Autostart:
|
7. Autostart:
|
||||||
`UpdateSettings` in the Service calls `autostart.Manager.Set`. The Manager
|
`UpdateSettings` in the Service calls `autostart.Manager.Set`. The Manager
|
||||||
@@ -125,6 +137,32 @@ in flight increments `JobRuntime.PendingRuns`. When the current run finishes,
|
|||||||
`executeRun` drains the counter by starting one deferred run per completion until
|
`executeRun` drains the counter by starting one deferred run per completion until
|
||||||
`PendingRuns` reaches zero.
|
`PendingRuns` reaches zero.
|
||||||
|
|
||||||
|
### Per-job command timeout
|
||||||
|
|
||||||
|
`domain.Job` carries a `TimeoutSeconds *int` field
|
||||||
|
(`json:"timeout_seconds,omitempty"`), following the same inherit pattern as the
|
||||||
|
overlap policy. It is a **pointer** because the setting has three states that
|
||||||
|
must stay distinguishable on disk:
|
||||||
|
|
||||||
|
| `Job.TimeoutSeconds` | jobs.json | Meaning |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `nil` | field absent | inherit `Config.DefaultTimeoutSeconds` |
|
||||||
|
| `0` | `"timeout_seconds": 0` | no timeout, does **not** inherit |
|
||||||
|
| `> 0` | `"timeout_seconds": 45` | per-job limit in seconds |
|
||||||
|
|
||||||
|
The global `Config.DefaultTimeoutSeconds` (default **0**, i.e. no timeout) is
|
||||||
|
written unconditionally — no `omitempty` — for the same reason: `0` there is a
|
||||||
|
deliberate choice, not a missing value, and `storage.loadOrCreateConfig` must not
|
||||||
|
normalize it away. `app.Service.effectiveTimeout`
|
||||||
|
resolves the effective duration under `mu` and `startRunLocked` snapshots it into
|
||||||
|
`runEnv.timeout`. `runner.RunJob(ctx, job, trigger, logsDir, timeout)` takes the
|
||||||
|
resolved duration as an argument, so the runner stays ignorant of the global
|
||||||
|
config: a positive duration applies the timeout via `context.WithTimeout` and
|
||||||
|
reports `Timed out after <timeout>` on expiry; a non-positive duration runs
|
||||||
|
without a deadline, bounded only by `ctx` (app shutdown). `StartOnly` jobs run on
|
||||||
|
the untimed context and so measure launch latency only, unaffected by the run
|
||||||
|
timeout.
|
||||||
|
|
||||||
### Run-time statistics
|
### Run-time statistics
|
||||||
|
|
||||||
`domain.JobRuntime` holds a rolling aggregate updated after each run:
|
`domain.JobRuntime` holds a rolling aggregate updated after each run:
|
||||||
@@ -150,6 +188,11 @@ accumulated run history immediately after a restart.
|
|||||||
Older log files that pre-date the `duration` header are tolerated: the run is
|
Older log files that pre-date the `duration` header are tolerated: the run is
|
||||||
counted but the timing is skipped.
|
counted but the timing is skipped.
|
||||||
|
|
||||||
|
`JobRuntime.Logs` (per-run `RunRecord` entries shown in the History tab) is
|
||||||
|
**session-only**: it is not written to `jobs.json` and is not rebuilt from
|
||||||
|
`.log` files on startup. Log files on disk feed aggregate counters via
|
||||||
|
`SeedStats` only. See [STANDARDS.md](STANDARDS.md).
|
||||||
|
|
||||||
### Persisted global pause
|
### Persisted global pause
|
||||||
|
|
||||||
`domain.Config` carries a `Paused bool` field (`json:"paused,omitempty"`).
|
`domain.Config` carries a `Paused bool` field (`json:"paused,omitempty"`).
|
||||||
@@ -161,11 +204,24 @@ the moment the window opens.
|
|||||||
|
|
||||||
### `jobs_view.go` file structure
|
### `jobs_view.go` file structure
|
||||||
|
|
||||||
`src/ui/jobs_view.go` is split across three files to stay within the ~250-line
|
The size guideline for a file in this project is ~250 lines.
|
||||||
size guideline:
|
`src/ui/jobs_view.go` is split across three files along these seams; the view
|
||||||
|
file itself has grown back over the guideline since — see the split item in
|
||||||
|
[ROADMAP.md](ROADMAP.md), which tracks every file currently over it:
|
||||||
|
|
||||||
| File | Contents |
|
| File | Contents |
|
||||||
|------|----------|
|
|------|----------|
|
||||||
| `jobs_view.go` | `newJobsView` — list, toolbar, button wiring, and layout |
|
| `jobs_view.go` | `newJobsView` — list, toolbar, button wiring, and layout |
|
||||||
| `jobs_view_details.go` | `detailsPanel` struct — widget creation, `update`, `clear`, `container` |
|
| `jobs_view_details.go` | `detailsPanel` struct — widget creation, `update`, `clear`, `container` |
|
||||||
| `jobs_view_helpers.go` | Pure helpers — `filteredJobIndexes`, `folderOptions`, `filterValue`, `indexOfID`, `lastJobLogs` |
|
| `jobs_view_helpers.go` | Pure helpers — `filteredJobIndexes`, `folderOptions`, `filterValue`, `indexOfID`, `lastJobLogs`, `nextJobListView`, `viewToggleText` |
|
||||||
|
|
||||||
|
### `settings_view.go` file structure
|
||||||
|
|
||||||
|
`src/ui/settings_view.go` is split across three files the same way, once its
|
||||||
|
own size passed the guideline:
|
||||||
|
|
||||||
|
| File | Contents |
|
||||||
|
|------|----------|
|
||||||
|
| `settings_view.go` | `settingsView` — field construction, save, load, validate; the Theme label translation helpers |
|
||||||
|
| `settings_view_layout.go` | `newSettingsLayout`, `settingsSection`, `settingsRow` — the two-column arrangement and the button row |
|
||||||
|
| `settings_view_helpers.go` | Pure helpers — `fyneVersion`, `mustParseURL`, `settingsFolderPath`, `openFolder`, `chooseFile`/`chooseJSONFile`, `chooseFolder` (`chooseFile` also backs `job_dialog.go`'s command browser) |
|
||||||
|
|||||||
@@ -2,6 +2,256 @@
|
|||||||
|
|
||||||
All notable GoSentry changes are recorded in this file.
|
All notable GoSentry changes are recorded in this file.
|
||||||
|
|
||||||
|
## 1.0.0 - 2026-07-27
|
||||||
|
|
||||||
|
**The window opens at the size it asks for, and the Jobs divider can be
|
||||||
|
dragged.**
|
||||||
|
|
||||||
|
**Window:**
|
||||||
|
|
||||||
|
- **The window opens at 1024×660 and can now be dragged narrower than it opens.**
|
||||||
|
Fyne treats the assembled content's minimum size as a hard floor over the
|
||||||
|
requested size, and two widgets in Settings pushed that minimum past 1024 px:
|
||||||
|
a fixed width applied to seven controls that the layout already stretched, and
|
||||||
|
the read-only config path, which grew the whole tab with the length of the
|
||||||
|
path it was showing — a 75-character path alone demanded 1501 px. The path now
|
||||||
|
clips when the window is genuinely narrow instead of widening the window, and
|
||||||
|
the content minimum is 972 px.
|
||||||
|
|
||||||
|
**Jobs:**
|
||||||
|
|
||||||
|
- **The divider between the job list and the details pane is draggable.**
|
||||||
|
Previously the list was pinned at its natural width and the details pane took
|
||||||
|
whatever was left, so a long command or a deep folder path could not be given
|
||||||
|
more room. Either pane can now be widened at the other's expense, and neither
|
||||||
|
can be dragged below its own content, so the details pane condenses rather
|
||||||
|
than clipping. The divider opens at the list's natural width; its position is
|
||||||
|
not saved, so a restart reopens at that default.
|
||||||
|
|
||||||
|
**History:**
|
||||||
|
|
||||||
|
- **Columns measure their own content.** Time, Trigger and State were fixed
|
||||||
|
pixel widths with as little as 1.6 px of headroom and truncated their own
|
||||||
|
values on a scaled UI or at a larger text size; all five now size themselves
|
||||||
|
from the text they have to show, under the current theme. Job and Detail stay
|
||||||
|
bounded so one long row cannot take over the table.
|
||||||
|
|
||||||
|
**Settings:**
|
||||||
|
|
||||||
|
- The **Save / Cancel / Restore defaults** row sits 4 px from the left edge, as
|
||||||
|
its layout always intended, rather than 8.
|
||||||
|
- The caption column is as wide as the widest caption instead of a fixed width,
|
||||||
|
which gives each value column about 22 px more and keeps the captions readable
|
||||||
|
at a larger text size.
|
||||||
|
- The **Application** and **About** blocks are about 2 px tighter: every stacked
|
||||||
|
row group in the app now shares one spacing derived from the theme rather than
|
||||||
|
three separately tuned numbers.
|
||||||
|
- The **Theme** dropdown is no longer flush against the **Notifications**
|
||||||
|
checkbox. That shared row spacing pulls rows together by one text inset, which
|
||||||
|
the rows above have to give but a dropdown — which paints its box out to the
|
||||||
|
row's edge — does not, so the gap collapsed to about a pixel. The Theme row
|
||||||
|
now keeps the same gap the checkbox rows have.
|
||||||
|
|
||||||
|
**Documentation:**
|
||||||
|
|
||||||
|
- The **README** describes the application that exists. Its `gosentry.json`
|
||||||
|
sample was three keys short of what the app writes on first run, which made
|
||||||
|
the one file the user is invited to hand-edit the least accurate thing in the
|
||||||
|
document; it is now the real default, with each key explained — including why
|
||||||
|
a zero timeout is written out and an unset one is not. The feature list has
|
||||||
|
caught up with the run timeout, the theme, the compact job list, and the
|
||||||
|
per-job overlap and timeout overrides the job dialog has always offered.
|
||||||
|
- **`docs/DEVELOPMENT.md`** is ordered as stack, external libraries, run from
|
||||||
|
source, build, release, CI, behind a two-level table of contents, instead of
|
||||||
|
opening with MSYS2 setup and burying "Run From Source" mid-document. The
|
||||||
|
library table gains versions and licenses, the `package-*` scripts are
|
||||||
|
documented for the first time and labelled by OS, and the Codeberg
|
||||||
|
`RELEASE_TOKEN` note now states the failure mode rather than leaving it to be
|
||||||
|
inferred from a red job: build and packaging succeed, the upload step fails on
|
||||||
|
authentication and takes the job with it, leaving a published release with no
|
||||||
|
assets. The Project Layout section is gone — it duplicated ARCHITECTURE's
|
||||||
|
package map and had drifted out of date.
|
||||||
|
- **Cutting a GitHub release now documents the push mirror it has to survive.**
|
||||||
|
GitHub is a pruning push mirror of Gitea, so `gh release create` creating the
|
||||||
|
tag itself produces a tag Gitea does not know about, which the next
|
||||||
|
synchronisation deletes — orphaning the release and taking its uploaded
|
||||||
|
archives with it, without a single failed step to point at. The procedure is
|
||||||
|
push the tag to Gitea, wait for the mirror, verify the tag on GitHub, then
|
||||||
|
publish with `--verify-tag`.
|
||||||
|
- **`docs/TESTS.md`** matches the suite it indexes again. It listed 130 tests
|
||||||
|
against 170 in the tree, omitted four test files entirely, and named two tests
|
||||||
|
that no longer exist. Every test function now appears exactly once, under the
|
||||||
|
file it actually lives in.
|
||||||
|
- **`docs/ARCHITECTURE.md`** no longer draws the UI calling the autostart
|
||||||
|
manager directly — it does not, and `src/ui` holds no reference to that
|
||||||
|
package — and `platform/desktop` is described by what it does (the XDG desktop
|
||||||
|
entry and icon) rather than as a display-scale helper.
|
||||||
|
- The **~250-line file guideline** is stated as the target it is, with the six
|
||||||
|
files currently over it recorded as a `docs/ROADMAP.md` item. They are to be
|
||||||
|
split in one pass during the next whole-project review, since six separate
|
||||||
|
passes would settle the same seam question six ways.
|
||||||
|
|
||||||
|
## 0.15.0 - 2026-07-26
|
||||||
|
|
||||||
|
**Settings points at the jobs file itself, not the folder holding it.**
|
||||||
|
|
||||||
|
**Settings:**
|
||||||
|
|
||||||
|
- The **Jobs directory** row is now a **Jobs file** row. Browse opens a file
|
||||||
|
picker filtered to `.json` instead of a folder picker, so the job list can
|
||||||
|
live under any file name — `team-jobs.json`, one file per machine, a file
|
||||||
|
shared over a network drive — rather than a fixed `jobs.json` per folder. The
|
||||||
|
field stays editable, which is how a file that does not exist yet is named.
|
||||||
|
- **Selecting an existing jobs file now loads it.** Previously the current job
|
||||||
|
list was written over whatever was at the new path, which made it impossible
|
||||||
|
to switch to an existing jobs file — its contents were destroyed on Save. Now
|
||||||
|
an existing file wins: its jobs are loaded, normalized, and replace the loaded
|
||||||
|
list, with runtimes, parsed schedules, next-run times, and log-seeded
|
||||||
|
statistics rebuilt around them. A path with no file behind it still receives
|
||||||
|
the current jobs (and its folder is created), which is how the jobs file is
|
||||||
|
renamed or relocated. History records `Jobs loaded — N jobs from <path>`,
|
||||||
|
since the switch happens without a prompt.
|
||||||
|
- Switching to a different jobs file is refused while a job is running: adoption
|
||||||
|
discards every runtime, and a run finishing afterwards would write its result
|
||||||
|
onto whichever job inherited its ID. Settings unrelated to the jobs file still
|
||||||
|
save normally during a run.
|
||||||
|
- Saving a path with no file name (a trailing separator, `.`, `..`) is rejected
|
||||||
|
with "jobs file must include a file name" instead of failing later with an
|
||||||
|
opaque OS error.
|
||||||
|
|
||||||
|
**Configuration:**
|
||||||
|
|
||||||
|
- `Config.JobsDir` / `jobs_dir` is replaced by `Config.JobsFile` / `jobs_file`,
|
||||||
|
which holds the full path including the file name; the default is
|
||||||
|
`"jobs.json"`, resolved against the program folder as before. `Paths.JobsDir`
|
||||||
|
is now derived from the configured file so job saves still create the folder.
|
||||||
|
- A `gosentry.json` written by an earlier version is migrated on load: its
|
||||||
|
`jobs_dir` is joined with `jobs.json`, which is the exact file that version
|
||||||
|
used, and the retired key is dropped when the config is rewritten.
|
||||||
|
- New `app.JobsLoaded{Path, Count}` event, emitted when a selected jobs file
|
||||||
|
replaces the job list; the UI turns it into the History entry. New
|
||||||
|
`storage.LoadJobsFile`, which reads and normalizes a jobs file and reports a
|
||||||
|
missing one as "not found" instead of seeding it the way startup does.
|
||||||
|
|
||||||
|
## 0.14.0 - 2026-07-26
|
||||||
|
|
||||||
|
**Compact job list view, "no timeout" at both timeout levels, and an Open
|
||||||
|
button for the logs folder.**
|
||||||
|
|
||||||
|
**Compact job list view.**
|
||||||
|
|
||||||
|
- The Jobs sidebar can now render each job as a single line — name on the left,
|
||||||
|
status on the right — instead of the three-line block. A toggle button beside
|
||||||
|
the Folder filter switches between **Compact** and **Detailed**; it is
|
||||||
|
labelled with the action it performs, like the "Disable auto" button. Compact
|
||||||
|
fits many more jobs on screen without scrolling; selection, the details panel,
|
||||||
|
the folder filter, and live status updates all work unchanged in both modes.
|
||||||
|
- The choice is persisted as a new `Config.JobListView` field
|
||||||
|
(`"detailed"` / `"compact"`, written to `gosentry.json` as `job_list_view`),
|
||||||
|
so it survives a restart. Empty/legacy configs and any unrecognised value
|
||||||
|
normalize to detailed, so existing installs keep the current look.
|
||||||
|
|
||||||
|
**Jobs sidebar:**
|
||||||
|
|
||||||
|
- The **Folder** caption moved onto the filter row itself, beside the select and
|
||||||
|
the view toggle, instead of occupying its own line above it — the job list now
|
||||||
|
starts a full label higher.
|
||||||
|
|
||||||
|
**Settings:**
|
||||||
|
|
||||||
|
- The **Logs directory** row gained an **Open** button that shows the folder in
|
||||||
|
the desktop file manager (Explorer on Windows, the XDG handler on Linux), so
|
||||||
|
reading a log file no longer means copying the path by hand. It opens the
|
||||||
|
path currently in the field — including an edit that has not been saved yet —
|
||||||
|
resolving a relative directory against the application folder exactly as the
|
||||||
|
store does. A folder that is missing (the logs directory is created on the
|
||||||
|
first run) or cannot be opened is reported in a dialog.
|
||||||
|
- The Save/Cancel/Defaults row sat flush against the separator above it and the
|
||||||
|
tab's left edge; it now uses the same padding as the other vertical gaps in
|
||||||
|
the tab.
|
||||||
|
|
||||||
|
**Job dialog:**
|
||||||
|
|
||||||
|
- The **Arguments** placeholder now states the field's rule — one argument per
|
||||||
|
line, no quoting — instead of showing a lone example path that left the
|
||||||
|
line-per-argument convention to guesswork.
|
||||||
|
|
||||||
|
**Timeouts: 0 now means "no timeout" at both levels.**
|
||||||
|
|
||||||
|
- The global **Default timeout** in Settings now defaults to `0`, meaning jobs
|
||||||
|
run to completion with no deadline instead of being killed after 30s.
|
||||||
|
- A per-job timeout of `0` now also means "no timeout" and no longer inherits
|
||||||
|
the global default. Leaving the job's timeout **empty** is what inherits.
|
||||||
|
`Job.TimeoutSeconds` became `*int` so the three states — unset, explicit 0,
|
||||||
|
and a positive limit — stay distinguishable in `jobs.json`.
|
||||||
|
- Fixed: a global default of `0` did not survive a restart. `gosentry.json` was
|
||||||
|
loaded with `0` treated as a missing value and silently reset to 30s, so the
|
||||||
|
setting only held for the current session. `default_timeout_seconds` is now
|
||||||
|
written unconditionally and read back as-is.
|
||||||
|
|
||||||
|
Existing jobs and configs are unaffected: a job with no `timeout_seconds` still
|
||||||
|
inherits, and a saved global default of 30 stays 30.
|
||||||
|
|
||||||
|
**Internal:**
|
||||||
|
|
||||||
|
- Job names in the list are truncated through the widget's `Truncation` field;
|
||||||
|
`fyne.TextTruncate` is deprecated in Fyne 2.7.4. Behavior is unchanged.
|
||||||
|
- Docker release builds mount `.gocache/` from the host, so `--rm` container
|
||||||
|
removal no longer wipes `GOCACHE` between runs.
|
||||||
|
- Added `docs/REVIEW.md` (the project-review agenda) and a "Config file
|
||||||
|
compatibility" section in `docs/STANDARDS.md` recording the rule the `Theme`,
|
||||||
|
`JobListView`, and `TimeoutSeconds` fields already follow. Added `CLAUDE.md`.
|
||||||
|
|
||||||
|
## 0.13.0 - 2026-07-26
|
||||||
|
|
||||||
|
**Branded GoSentry color theme; Cancel/Defaults buttons in Settings.**
|
||||||
|
|
||||||
|
**Theme:**
|
||||||
|
- Added a custom Fyne theme derived from the logo and app icon (deep teal
|
||||||
|
primary, amber accent, branded job-status colors) with light and dark
|
||||||
|
variants; users can switch between it and Fyne's default theme from
|
||||||
|
Settings. The choice is persisted as a new `Config.Theme` field
|
||||||
|
(`"default"` / `"gosentry"`), applied at startup before the first frame
|
||||||
|
and live-previewed when picked in Settings. Empty/legacy configs
|
||||||
|
normalize to the default theme so existing installs keep the original
|
||||||
|
look.
|
||||||
|
- The light variant is boldly branded: a soft teal window canvas with
|
||||||
|
white inputs, menus, dialogs, and buttons on top, plus teal-tinted
|
||||||
|
separators, input borders, and table headers, so cards and fields lift
|
||||||
|
off the background instead of reading as a plain accent swap on gray.
|
||||||
|
The dark variant uses deep-teal surfaces to echo the app icon. Text
|
||||||
|
stays dark/light per the base foreground for contrast in both variants.
|
||||||
|
|
||||||
|
**Settings tab:**
|
||||||
|
- Added Cancel and Defaults buttons. Cancel discards unsaved edits by
|
||||||
|
reloading the saved config; Defaults loads built-in default values into
|
||||||
|
the form for review before saving. `domain.DefaultConfig()` is now the
|
||||||
|
single source of truth for default values, shared by storage and the
|
||||||
|
Settings UI.
|
||||||
|
|
||||||
|
## 0.12.0 - 2026-07-25
|
||||||
|
|
||||||
|
**Per-job command timeout:**
|
||||||
|
- Each job may now set its own run timeout (seconds) in the job dialog; leaving
|
||||||
|
it empty inherits a new **Default timeout** in Settings (default 30s), the same
|
||||||
|
inherit pattern as the overlap policy. The details panel shows the effective
|
||||||
|
value, marking inherited jobs as `(global default)`.
|
||||||
|
- The formerly hard-coded 30s guard in `runner.RunJob` is now the configurable
|
||||||
|
default. `StartOnly` fire-and-forget jobs remain unaffected by the run timeout,
|
||||||
|
continuing to measure launch latency only.
|
||||||
|
|
||||||
|
## 0.11.5 - 2026-07-01
|
||||||
|
|
||||||
|
**Quality and documentation polish:**
|
||||||
|
|
||||||
|
- Replaced the interim `docs/FUTURE_WORK.md` with `docs/STANDARDS.md` — a slim,
|
||||||
|
permanent reference for code-quality rules and intentional behavior.
|
||||||
|
- `newMainView` now accepts an injected `*app.Service` for testability;
|
||||||
|
`RunNow` errors are shown in a dialog instead of failing silently.
|
||||||
|
- Empty job lists no longer panic when building the Jobs tab.
|
||||||
|
- Added regression and helper tests for overlap/pause scheduling, UI history
|
||||||
|
helpers, main-view smoke build, and Linux desktop integration.
|
||||||
|
|
||||||
## 0.11.4 - 2026-06-30
|
## 0.11.4 - 2026-06-30
|
||||||
|
|
||||||
**Statistics:**
|
**Statistics:**
|
||||||
|
|||||||
@@ -1,53 +0,0 @@
|
|||||||
# GoSentry — Code Review (2026-06-29)
|
|
||||||
|
|
||||||
Версия на момент ревью: **0.11.2** (исправления вошли в **0.11.3**)
|
|
||||||
|
|
||||||
## Итог
|
|
||||||
|
|
||||||
| Критерий | Оценка |
|
|
||||||
|----------|--------|
|
|
||||||
| Архитектура | 9/10 |
|
|
||||||
| Сложность vs масштаб | 8/10 |
|
|
||||||
| Качество кода | 8/10 |
|
|
||||||
| Поддерживаемость | 8/10 |
|
|
||||||
| Логические ошибки | 9/10 (после исправлений) |
|
|
||||||
|
|
||||||
Проект зрелый и поддерживаемый для десктопного планировщика (~59 `.go`-файлов). Архитектура слоистая, core-логика хорошо протестирована.
|
|
||||||
|
|
||||||
## Сильные стороны
|
|
||||||
|
|
||||||
- Single-writer `app.Service` с явным locking contract
|
|
||||||
- Разделение `domain.Job` (durable) и `domain.JobRuntime` (transient)
|
|
||||||
- Event-driven UI без обратных вызовов в Fyne под lock
|
|
||||||
- Portable storage от `os.Executable()`
|
|
||||||
- Инъекция `runJob` и `scheduler.Clock` в тестах
|
|
||||||
- Подробная документация (`ARCHITECTURE.md`, inline comments)
|
|
||||||
|
|
||||||
## Найденные проблемы и статус исправлений
|
|
||||||
|
|
||||||
| # | Проблема | Серьёзность | Статус |
|
|
||||||
|---|----------|-------------|--------|
|
|
||||||
| 1 | Data race: `store.Paths` в `executeRun` без lock | Высокая | Исправлено |
|
|
||||||
| 2 | Run стартует при ошибке `SaveJobs` | Средняя | Исправлено |
|
|
||||||
| 3 | CRUD эмитит events при failed save | Средняя | Исправлено |
|
|
||||||
| 4 | Overlap queue — только один `Pending` | Средняя | Исправлено (`PendingRuns`) |
|
|
||||||
| 5 | `time.Now()` vs scheduler clock в `startRunLocked` | Низкая | Исправлено |
|
|
||||||
| 6 | Silent log write failures | Низкая | Исправлено |
|
|
||||||
| 7 | Невалидный per-job `overlap_policy` | Низкая | Исправлено |
|
|
||||||
| 8 | Docs drift (YAML, RunNow/pause) | Низкая | Исправлено |
|
|
||||||
| 9 | `StartOnly` игнорировал cancel context | Низкая | Исправлено |
|
|
||||||
| 10 | `SeedStats` коллизия sanitized имён | Низкая | Исправлено (match по `job_id`) |
|
|
||||||
| 11 | `AvgDurationMS` seed vs live расходились | Низкая | Исправлено (`TimedRunCount`) |
|
|
||||||
| 12 | Legacy ticket-ссылки в комментариях | Низкая | Исправлено |
|
|
||||||
|
|
||||||
## Намеренное поведение (не баги)
|
|
||||||
|
|
||||||
- `RunNow` разрешён при global pause и для disabled jobs
|
|
||||||
- Sequential mode — FIFO по порядку в `jobs.json`
|
|
||||||
- Scheduler tick 1s — sub-second `@every` не поддерживается
|
|
||||||
- Command timeout 30s — глобальный лимит
|
|
||||||
|
|
||||||
## Рекомендации на будущее
|
|
||||||
|
|
||||||
- UI widget tests или smoke E2E
|
|
||||||
- Per-job command timeout в конфиге
|
|
||||||
@@ -1,18 +1,51 @@
|
|||||||
# GoSentry — Development
|
# GoSentry — Development
|
||||||
|
|
||||||
Build instructions, project layout, and dependency information for contributors.
|
Toolchain, dependency, build, and release information for contributors.
|
||||||
|
|
||||||
## Requirements
|
## Contents
|
||||||
|
|
||||||
Common:
|
1. [Technology Stack and Tools](#1-technology-stack-and-tools)
|
||||||
|
- [Toolchain — Windows](#toolchain--windows)
|
||||||
|
- [Toolchain — Linux](#toolchain--linux)
|
||||||
|
- [Repository scripts](#repository-scripts)
|
||||||
|
2. [External Libraries](#2-external-libraries)
|
||||||
|
3. [Run From Source](#3-run-from-source)
|
||||||
|
4. [Building the Executable](#4-building-the-executable)
|
||||||
|
- [Windows](#windows)
|
||||||
|
- [Linux](#linux)
|
||||||
|
- [Linux using Docker](#linux-using-docker)
|
||||||
|
5. [Building a Release](#5-building-a-release)
|
||||||
|
- [All targets from Linux](#all-targets-from-linux)
|
||||||
|
- [Packaging](#packaging)
|
||||||
|
6. [CI](#6-ci)
|
||||||
|
- [Cutting a release](#cutting-a-release)
|
||||||
|
- [Releasing through the GitHub push mirror](#releasing-through-the-github-push-mirror)
|
||||||
|
|
||||||
|
## 1. Technology Stack and Tools
|
||||||
|
|
||||||
|
GoSentry is a single desktop process written in Go with a Fyne GUI. There is no
|
||||||
|
server component and no external runtime: the release artifact is one native
|
||||||
|
executable per platform.
|
||||||
|
|
||||||
|
| Layer | Choice |
|
||||||
|
| --- | --- |
|
||||||
|
| Language | Go 1.22 or newer |
|
||||||
|
| GUI toolkit | Fyne v2 (OpenGL desktop backend) |
|
||||||
|
| Scheduling | `robfig/cron/v3` expression parser |
|
||||||
|
| Persistence | Plain JSON files (`gosentry.json`, `jobs.json`) |
|
||||||
|
| Build | `go build` driven by the scripts in `scripts/` |
|
||||||
|
| Reproducible builds | Docker (`golang:1.22-bookworm` based [Dockerfile](../Dockerfile)) |
|
||||||
|
| CI | GitHub Actions and Forgejo Actions (Codeberg) |
|
||||||
|
|
||||||
|
CGO is mandatory. The Fyne desktop backend links against native OpenGL and
|
||||||
|
window-system libraries, so a C compiler must be present for every build,
|
||||||
|
including `go run` and `go test`.
|
||||||
|
|
||||||
|
### Toolchain — Windows
|
||||||
|
|
||||||
- [Go](https://go.dev/) 1.22 or newer.
|
- [Go](https://go.dev/) 1.22 or newer.
|
||||||
|
- MSYS2 with UCRT64 GCC in `C:\msys64\ucrt64\bin` (plus `windres` for the icon
|
||||||
Windows:
|
resource).
|
||||||
|
|
||||||
- MSYS2 with UCRT64 GCC in `C:\msys64\ucrt64\bin`.
|
|
||||||
|
|
||||||
Install these dependencies on Windows:
|
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# 1. Install Go 1.22 or newer from https://go.dev/dl/.
|
# 1. Install Go 1.22 or newer from https://go.dev/dl/.
|
||||||
@@ -33,12 +66,12 @@ Test-Path C:\msys64\ucrt64\bin\gcc.exe
|
|||||||
Test-Path C:\msys64\ucrt64\bin\windres.exe
|
Test-Path C:\msys64\ucrt64\bin\windres.exe
|
||||||
```
|
```
|
||||||
|
|
||||||
Linux:
|
### Toolchain — Linux
|
||||||
|
|
||||||
|
- [Go](https://go.dev/) 1.22 or newer.
|
||||||
- A C compiler.
|
- A C compiler.
|
||||||
- [Fyne](https://fyne.io/) native build dependencies, including OpenGL/X11 development packages.
|
- [Fyne](https://fyne.io/) native build dependencies, including OpenGL/X11
|
||||||
|
development packages.
|
||||||
On Debian/Ubuntu, the Linux dependencies are typically:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Go builds the application, gcc is required by CGO/Fyne, and the OpenGL/X11
|
# Go builds the application, gcc is required by CGO/Fyne, and the OpenGL/X11
|
||||||
@@ -46,84 +79,41 @@ On Debian/Ubuntu, the Linux dependencies are typically:
|
|||||||
sudo apt install golang gcc libgl1-mesa-dev xorg-dev
|
sudo apt install golang gcc libgl1-mesa-dev xorg-dev
|
||||||
```
|
```
|
||||||
|
|
||||||
## Build
|
### Repository scripts
|
||||||
|
|
||||||
### Windows
|
| Script | Purpose |
|
||||||
|
| --- | --- |
|
||||||
|
| `scripts/test.bat`, `scripts/test.sh` | `go vet ./...` then `go test -race ./...` |
|
||||||
|
| `scripts/build-windows.bat` | Windows amd64 executable |
|
||||||
|
| `scripts/build-linux.sh` | Linux amd64 executable |
|
||||||
|
| `scripts/build-linux-docker.sh` | Linux amd64 executable, built in Docker |
|
||||||
|
| `scripts/build-release-linux.sh` | Multi-target release artifacts from one Linux/Docker workflow |
|
||||||
|
| `scripts/package-windows.bat`, `scripts/package-linux.sh` | Wrap a built binary into a distributable archive |
|
||||||
|
| `scripts/ci-build-release.sh` | Entry point used by both CI workflows |
|
||||||
|
|
||||||
```powershell
|
Build outputs are written to `dist/`. The package layout is documented in
|
||||||
# Builds dist\windows\gosentry-<version>-windows-amd64.exe. The script changes
|
[ARCHITECTURE.md](ARCHITECTURE.md).
|
||||||
# to the repository root first, so double-clicking it from Explorer works. It
|
|
||||||
# also adds MSYS2 UCRT64 to PATH for this process only, embeds the Windows icon
|
|
||||||
# when windres is available, and uses the Windows GUI subsystem so no console
|
|
||||||
# window opens at startup.
|
|
||||||
.\scripts\build-windows.bat
|
|
||||||
```
|
|
||||||
|
|
||||||
The Windows build is created as a GUI application, so it does not open a terminal window.
|
## 2. External Libraries
|
||||||
|
|
||||||
The binary is written to:
|
GoSentry keeps the direct dependency list intentionally small. GoSentry itself
|
||||||
|
is distributed under the [MIT License](../LICENSE).
|
||||||
|
|
||||||
```text
|
| Dependency | Version | Repository | License |
|
||||||
dist\windows\gosentry-0.9.0-windows-amd64.exe
|
| --- | --- | --- | --- |
|
||||||
```
|
| Go toolchain | 1.22+ | https://go.googlesource.com/go | BSD 3-Clause |
|
||||||
|
| `fyne.io/fyne/v2` | v2.7.4 | https://github.com/fyne-io/fyne | BSD 3-Clause |
|
||||||
|
| `github.com/robfig/cron/v3` | v3.0.1 | https://github.com/robfig/cron | MIT |
|
||||||
|
|
||||||
### Linux
|
The remaining entries in `go.mod` are indirect dependencies pulled in by Fyne
|
||||||
|
and the Go module resolver. To list every direct and indirect module used by the
|
||||||
|
current checkout:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Make the helper executable once, then build a linux/amd64 Fyne binary.
|
go list -m all
|
||||||
chmod +x ./scripts/build-linux.sh
|
|
||||||
./scripts/build-linux.sh
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The binary is written to:
|
## 3. Run From Source
|
||||||
|
|
||||||
```text
|
|
||||||
dist/linux/gosentry-0.9.0-linux-amd64
|
|
||||||
```
|
|
||||||
|
|
||||||
### Linux using Docker
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Builds the Linux binary inside Docker using the versioned image tag
|
|
||||||
# gitea.mixdep.ru/mix/gosentry-builder:<version>. Useful from hosts or CI jobs
|
|
||||||
# where the native Linux/Fyne packages are not installed locally.
|
|
||||||
chmod +x ./scripts/build-linux-docker.sh
|
|
||||||
./scripts/build-linux-docker.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
The binary is copied to:
|
|
||||||
|
|
||||||
```text
|
|
||||||
dist/linux/gosentry-0.9.0-linux-amd64
|
|
||||||
```
|
|
||||||
|
|
||||||
### Release build from Linux
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Interactively choose Linux amd64, Linux arm64, Windows amd64, or all artifacts
|
|
||||||
# from one Linux/Docker workflow. The Dockerfile contains the builder
|
|
||||||
# environment; the build commands live in this script. Docker runs the build
|
|
||||||
# with the current user's UID/GID so dist/ files are not owned by root.
|
|
||||||
chmod +x ./scripts/build-release-linux.sh
|
|
||||||
./scripts/build-release-linux.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
Non-interactive release builds can pass target names:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Build only Linux arm64 and Windows amd64 artifacts.
|
|
||||||
./scripts/build-release-linux.sh linux-arm64 windows-amd64
|
|
||||||
```
|
|
||||||
|
|
||||||
The binaries are copied to:
|
|
||||||
|
|
||||||
```text
|
|
||||||
dist/linux/gosentry-0.9.0-linux-amd64
|
|
||||||
dist/linux/gosentry-0.9.0-linux-arm64
|
|
||||||
dist/windows/gosentry-0.9.0-windows-amd64.exe
|
|
||||||
```
|
|
||||||
|
|
||||||
## Run From Source
|
|
||||||
|
|
||||||
Windows:
|
Windows:
|
||||||
|
|
||||||
@@ -146,41 +136,216 @@ Linux:
|
|||||||
CGO_ENABLED=1 go run ./cmd/gosentry
|
CGO_ENABLED=1 go run ./cmd/gosentry
|
||||||
```
|
```
|
||||||
|
|
||||||
## Project Layout
|
The same environment is required for the test suite — see
|
||||||
|
[TESTS.md](TESTS.md):
|
||||||
|
|
||||||
- `cmd/gosentry` — entry point; starts the desktop app.
|
```powershell
|
||||||
- `src/domain` — pure value types: `Job`, `Config`, `RunRecord`, `Schedule`, `JobRuntime`.
|
scripts\test.bat
|
||||||
- `src/app` — `Service`: sole owner of job and runtime state; emits typed events to the UI.
|
```
|
||||||
- `src/scheduler` — pure timing loop; calls `Service.RunDue` on every tick.
|
|
||||||
- `src/runner` — shell command execution, log file writing, and log cleanup.
|
|
||||||
- `src/storage` — JSON persistence (`gosentry.json`, `jobs.json`).
|
|
||||||
- `src/platform/autostart` — `Manager` interface with Windows (shortcut) and Linux (XDG) implementations.
|
|
||||||
- `src/platform/desktop` — display-scale helper (Linux only).
|
|
||||||
- `src/platform/winproc` — hidden-window startup flags (Windows only).
|
|
||||||
- `src/ui` — Fyne windows, tabs, and dialogs; reads service state through events.
|
|
||||||
- `assets` — app icons embedded into the application binary.
|
|
||||||
- `scripts` — build helpers.
|
|
||||||
- `docs` — architecture notes, changelog, and roadmap.
|
|
||||||
|
|
||||||
Build outputs are written to `dist/`.
|
## 4. Building the Executable
|
||||||
|
|
||||||
## Dependencies
|
### Windows
|
||||||
|
|
||||||
GoSentry keeps the direct dependency list intentionally small:
|
```powershell
|
||||||
|
# Builds dist\windows\gosentry-<version>-windows-amd64.exe. The script changes
|
||||||
|
# to the repository root first, so double-clicking it from Explorer works. It
|
||||||
|
# also adds MSYS2 UCRT64 to PATH for this process only, embeds the Windows icon
|
||||||
|
# when windres is available, and uses the Windows GUI subsystem so no console
|
||||||
|
# window opens at startup.
|
||||||
|
.\scripts\build-windows.bat
|
||||||
|
```
|
||||||
|
|
||||||
- [`fyne.io/fyne/v2`](https://fyne.io/) for the native GUI.
|
The Windows build is created as a GUI application, so it does not open a
|
||||||
- `github.com/robfig/cron/v3` for cron schedule parsing.
|
terminal window. The binary is written to:
|
||||||
|
|
||||||
The remaining entries in `go.mod` are indirect dependencies pulled by Fyne and the Go module resolver.
|
```text
|
||||||
|
dist\windows\gosentry-<version>-windows-amd64.exe
|
||||||
|
```
|
||||||
|
|
||||||
Source repositories for mirroring:
|
### Linux
|
||||||
|
|
||||||
- Go toolchain: https://go.googlesource.com/go
|
|
||||||
- Fyne: https://github.com/fyne-io/fyne
|
|
||||||
- robfig/cron: https://github.com/robfig/cron
|
|
||||||
|
|
||||||
To list every direct and indirect Go module used by the current checkout:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go list -m all
|
# Make the helper executable once, then build a linux/amd64 Fyne binary.
|
||||||
|
chmod +x ./scripts/build-linux.sh
|
||||||
|
./scripts/build-linux.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The binary is written to:
|
||||||
|
|
||||||
|
```text
|
||||||
|
dist/linux/gosentry-<version>-linux-amd64
|
||||||
|
```
|
||||||
|
|
||||||
|
### Linux using Docker
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Builds the Linux binary inside Docker using the versioned image tag
|
||||||
|
# gitea.mixdep.ru/mix/gosentry-builder:<version>. Useful from hosts or CI jobs
|
||||||
|
# where the native Linux/Fyne packages are not installed locally.
|
||||||
|
chmod +x ./scripts/build-linux-docker.sh
|
||||||
|
./scripts/build-linux-docker.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
The binary is copied to:
|
||||||
|
|
||||||
|
```text
|
||||||
|
dist/linux/gosentry-<version>-linux-amd64
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. Building a Release
|
||||||
|
|
||||||
|
### All targets from Linux
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Interactively choose Linux amd64, Linux arm64, Windows amd64, or all artifacts
|
||||||
|
# from one Linux/Docker workflow. The Dockerfile contains the builder
|
||||||
|
# environment; the build commands live in this script. Docker runs the build
|
||||||
|
# with the current user's UID/GID so dist/ files are not owned by root.
|
||||||
|
chmod +x ./scripts/build-release-linux.sh
|
||||||
|
./scripts/build-release-linux.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Non-interactive release builds can pass target names:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Build only Linux arm64 and Windows amd64 artifacts.
|
||||||
|
./scripts/build-release-linux.sh linux-arm64 windows-amd64
|
||||||
|
```
|
||||||
|
|
||||||
|
The binaries are copied to:
|
||||||
|
|
||||||
|
```text
|
||||||
|
dist/linux/gosentry-<version>-linux-amd64
|
||||||
|
dist/linux/gosentry-<version>-linux-arm64
|
||||||
|
dist/windows/gosentry-<version>-windows-amd64.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
### Packaging
|
||||||
|
|
||||||
|
The `package-*` scripts build the binary for their platform and wrap it in a
|
||||||
|
distributable archive together with `README.md` and `CHANGELOG.md`:
|
||||||
|
|
||||||
|
Windows:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
scripts\package-windows.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
dist\windows\gosentry-<version>-windows-amd64.zip
|
||||||
|
```
|
||||||
|
|
||||||
|
Linux:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./scripts/package-linux.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
dist/linux/gosentry-<version>-linux-amd64.tar.gz
|
||||||
|
dist/linux/gosentry-<version>-linux-arm64.tar.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
The arm64 archive is produced only when the `aarch64-linux-gnu-gcc` cross
|
||||||
|
compiler is available; otherwise that target is skipped with a message.
|
||||||
|
|
||||||
|
The version stamped into the file names and into the binary comes from
|
||||||
|
`src/app/version.go`.
|
||||||
|
|
||||||
|
## 6. CI
|
||||||
|
|
||||||
|
Tagged releases are built automatically on both GitHub and Codeberg:
|
||||||
|
|
||||||
|
- `.github/workflows/release.yml` — GitHub Actions.
|
||||||
|
- `.forgejo/workflows/release.yml` — Forgejo Actions (Codeberg).
|
||||||
|
|
||||||
|
Both run inside `golang:1.22-bookworm` (the same base image as the
|
||||||
|
[Dockerfile](../Dockerfile)), install the cross toolchain, and call
|
||||||
|
`scripts/ci-build-release.sh`, which builds and packages all three artifacts:
|
||||||
|
|
||||||
|
```text
|
||||||
|
dist/linux/gosentry-<version>-linux-amd64.tar.gz
|
||||||
|
dist/linux/gosentry-<version>-linux-arm64.tar.gz
|
||||||
|
dist/windows/gosentry-<version>-windows-amd64.zip
|
||||||
|
```
|
||||||
|
|
||||||
|
The Windows binary is cross-compiled with MinGW-w64 from the Linux job, so no
|
||||||
|
Windows runner is required. Each archive contains the executable plus `README.md`
|
||||||
|
and `CHANGELOG.md`, matching the local `package-*` scripts.
|
||||||
|
|
||||||
|
### Cutting a release
|
||||||
|
|
||||||
|
Before tagging:
|
||||||
|
|
||||||
|
1. Bump `src/app/version.go`. The tag must match it exactly.
|
||||||
|
2. Add the version's [CHANGELOG.md](CHANGELOG.md) section.
|
||||||
|
3. Retake the README screenshots (`images/screenshot_jobs.PNG`,
|
||||||
|
`images/screenshot_settings.PNG`) if the GUI changed its appearance. This is
|
||||||
|
easy to forget because nothing fails without it: `README.md` is packaged
|
||||||
|
inside every release archive and is what the forge shows on the project page,
|
||||||
|
so a stale shot advertises an application that no longer exists. Take them
|
||||||
|
from a real build, not from a development run with test data.
|
||||||
|
4. Run `scripts/test.bat` (or `go vet ./... && go test -race ./...`) and push
|
||||||
|
`main`, so the tag lands on a commit the forge actually has.
|
||||||
|
|
||||||
|
Then create and publish a release with a matching `v` tag on the forge (GitHub
|
||||||
|
Releases / Codeberg releases). `origin` is the Gitea repository, and GitHub is a
|
||||||
|
push mirror of it, so the tag is pushed to Gitea and reaches GitHub through the
|
||||||
|
mirror — never created on GitHub directly (see
|
||||||
|
[Releasing through the GitHub push mirror](#releasing-through-the-github-push-mirror)):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git tag v0.11.5
|
||||||
|
git push origin v0.11.5 # Gitea; and to the Codeberg remote
|
||||||
|
|
||||||
|
# wait for the mirror, then confirm GitHub actually has the tag
|
||||||
|
git ls-remote --tags https://github.com/mixeme/gosentry.git v0.11.5
|
||||||
|
|
||||||
|
gh release create v0.11.5 --verify-tag --generate-notes # GitHub; publishes the release
|
||||||
|
```
|
||||||
|
|
||||||
|
Publishing the release triggers the workflow: it strips the leading `v` from
|
||||||
|
the tag and injects it as the version (so the tag must match `version.go`),
|
||||||
|
builds the archives, and attaches them to that release. `workflow_dispatch`
|
||||||
|
also allows a manual, upload-free build to smoke-test the pipeline.
|
||||||
|
|
||||||
|
Codeberg publishing needs a repository secret named `RELEASE_TOKEN` (a Codeberg
|
||||||
|
access token with the `write:repository` scope) under
|
||||||
|
**Settings → Actions → Secrets**. Without it the build and packaging steps still
|
||||||
|
succeed, but the upload step fails on authentication and takes the job down with
|
||||||
|
it, leaving a published release with no attached assets. GitHub needs no such
|
||||||
|
setup: `softprops/action-gh-release` falls back to the built-in `GITHUB_TOKEN`,
|
||||||
|
and the workflow already grants it `contents: write`.
|
||||||
|
|
||||||
|
### Releasing through the GitHub push mirror
|
||||||
|
|
||||||
|
The GitHub repository `mixeme/gosentry` is not a separate remote you push to; it
|
||||||
|
is a push mirror driven by Gitea. Gitea mirrors with pruning, so every ref that
|
||||||
|
exists on GitHub but not in Gitea is deleted on the next synchronisation.
|
||||||
|
|
||||||
|
This is what breaks the obvious way of cutting a GitHub release. `gh release
|
||||||
|
create v1.0.0` creates the tag on GitHub when it is missing — a tag Gitea has
|
||||||
|
never heard of. The next mirror run prunes it, GitHub orphans the release whose
|
||||||
|
tag disappeared and turns it into a draft, and the release looks deleted on the
|
||||||
|
Releases page. The archives go with it. Nothing reports an error: the workflow
|
||||||
|
ran, the assets uploaded, and the release evaporated afterwards.
|
||||||
|
|
||||||
|
The order that works is therefore:
|
||||||
|
|
||||||
|
1. `git push origin <tag>` — the tag enters Gitea, which owns it.
|
||||||
|
2. Wait for the mirror, or force it with **Settings → Repository → Mirror
|
||||||
|
Settings → Synchronize Now** in Gitea.
|
||||||
|
3. `git ls-remote --tags https://github.com/mixeme/gosentry.git <tag>` — confirm
|
||||||
|
GitHub has it.
|
||||||
|
4. `gh release create <tag> --verify-tag …` — `--verify-tag` is the guard, not a
|
||||||
|
nicety: without it `gh` silently creates the doomed tag when the mirror has
|
||||||
|
not caught up yet.
|
||||||
|
|
||||||
|
Release notes and assets are GitHub-side metadata; a mirror push cannot touch
|
||||||
|
them, so once the release sits on a mirrored tag, later synchronisations leave
|
||||||
|
it alone. Two consequences follow. Moving a published tag in Gitea force-pushes
|
||||||
|
it on GitHub and leaves the release pointing at a different commit, and deleting
|
||||||
|
a published tag in Gitea destroys the GitHub release along with its uploaded
|
||||||
|
archives — neither is recoverable from the mirror side. Codeberg is unaffected:
|
||||||
|
its releases live in the same forge as its tags.
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# GoSentry — Review Agenda
|
||||||
|
|
||||||
|
What to look at when reviewing the project as a whole, as opposed to a single
|
||||||
|
diff. This is the agenda; the rules a review checks against live in
|
||||||
|
[STANDARDS.md](STANDARDS.md) and [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||||
|
|
||||||
|
Scope note: a normal pull-request review checks the change. This agenda is for
|
||||||
|
a periodic sweep of the whole codebase, so a pass may legitimately end with
|
||||||
|
"nothing to report" on most items.
|
||||||
|
|
||||||
|
## 1. Architecture and project structure
|
||||||
|
|
||||||
|
Does the code still match the package map and the event flow in
|
||||||
|
[ARCHITECTURE.md](ARCHITECTURE.md)? Watch for the boundaries that matter here:
|
||||||
|
`app.Service` as the sole owner of job and runtime state, the UI reading it
|
||||||
|
through typed events, `domain` staying free of I/O, and platform-specific code
|
||||||
|
staying behind the `platform/*` interfaces.
|
||||||
|
|
||||||
|
## 2. Complexity against the size of the project
|
||||||
|
|
||||||
|
GoSentry is a single-process desktop app with two direct dependencies. Flag
|
||||||
|
abstraction that is not paying for itself: interfaces with one implementation
|
||||||
|
and no test seam, indirection added for a use case nobody has asked for, a new
|
||||||
|
dependency where thirty lines of standard library would do. Also check the
|
||||||
|
opposite direction — files that have grown past the size guideline in
|
||||||
|
ARCHITECTURE and should be split the way `jobs_view.go` was.
|
||||||
|
|
||||||
|
## 3. Code quality
|
||||||
|
|
||||||
|
The checkable rules are in [STANDARDS.md](STANDARDS.md) — error handling, unit
|
||||||
|
tests for pure helpers, regression tests for fixes, `fyne.Do` for updates off
|
||||||
|
the main thread. Beyond them: concurrency around `Service.mu`, goroutines whose
|
||||||
|
lifetime is not obvious, and error paths that report something less useful than
|
||||||
|
what they caught.
|
||||||
|
|
||||||
|
## 4. Documentation and comments
|
||||||
|
|
||||||
|
Does every documented behavior still exist, and does every non-obvious behavior
|
||||||
|
get documented? Check the doc set against the code: README (user-facing
|
||||||
|
behavior and config keys), ARCHITECTURE (packages and flows), STANDARDS
|
||||||
|
(rules and intentional behavior), DEVELOPMENT (build), TESTS, PERFORMANCE,
|
||||||
|
CHANGELOG (an entry per notable change). For comments, the bar is *why*, not
|
||||||
|
*what* — a comment restating the line below it is noise; an unexplained
|
||||||
|
workaround is a finding.
|
||||||
|
|
||||||
|
## 5. Readability and maintainability
|
||||||
|
|
||||||
|
Read a package as someone who has not seen it before. Can the next change be
|
||||||
|
made without reverse-engineering? Naming that matches the domain vocabulary,
|
||||||
|
functions that do one thing, and control flow that does not need a diagram.
|
||||||
|
|
||||||
|
## 6. Logical errors
|
||||||
|
|
||||||
|
Correctness independent of style: scheduling and timing edge cases (overlap
|
||||||
|
policy, sequential mode, pause interactions), off-by-one and boundary handling,
|
||||||
|
zero values that mean something (see the timeout rules in STANDARDS), state
|
||||||
|
that can be observed mid-update, and error paths that leave state inconsistent.
|
||||||
|
|
||||||
|
## 7. Legacy code and migrations
|
||||||
|
|
||||||
|
The app has no database, so migration means file compatibility: `gosentry.json`
|
||||||
|
and `jobs.json` written by an older version must keep working. Check that new
|
||||||
|
`Config` fields are backward compatible, that normalization happens in one
|
||||||
|
place, and that values which are meaningful zeros are not normalized away. Also
|
||||||
|
look for code kept alive only for a case that no longer exists.
|
||||||
|
|
||||||
|
## 8. Undocumented or under-documented contentious decisions
|
||||||
|
|
||||||
|
Any decision a future reader would question needs its reasoning recorded where
|
||||||
|
it lives: a comment at the code, an entry in the "Intentional behavior" section
|
||||||
|
of [STANDARDS.md](STANDARDS.md), or — when the work is deferred rather than
|
||||||
|
decided — a note in [ROADMAP.md](ROADMAP.md), which is where the frozen
|
||||||
|
window-size work keeps its rationale.
|
||||||
|
|
||||||
|
## 9. Other improvement proposals
|
||||||
|
|
||||||
|
Anything that does not fit above: build and release ergonomics, test coverage
|
||||||
|
gaps, dependency health, UX rough edges.
|
||||||
|
|
||||||
|
## What happens to the findings
|
||||||
|
|
||||||
|
- A defect → fix it, with a regression test when severity is medium or higher.
|
||||||
|
- Behavior that turns out to be deliberate → record it under "Intentional
|
||||||
|
behavior" in [STANDARDS.md](STANDARDS.md) so it is not re-reported.
|
||||||
|
- Work larger than a single fix → [ROADMAP.md](ROADMAP.md), with the reasoning.
|
||||||
|
- A new rule the review establishes → [STANDARDS.md](STANDARDS.md).
|
||||||
@@ -5,6 +5,126 @@ Completed work is recorded in [CHANGELOG.md](CHANGELOG.md), not here.
|
|||||||
|
|
||||||
## Open Items
|
## Open Items
|
||||||
|
|
||||||
|
### Update check from GitHub releases
|
||||||
|
|
||||||
|
Releases are published as GitHub Releases (tags like `v0.12.0`, built by
|
||||||
|
`.github/workflows/release.yml`), but the app never tells the user a newer
|
||||||
|
version exists — they have to check the releases page by hand.
|
||||||
|
|
||||||
|
Add an update check that queries the GitHub Releases API
|
||||||
|
(`GET /repos/mixeme/gosentry/releases/latest`) for the latest published tag,
|
||||||
|
strips the leading `v`, and compares it against `app.Version`. When a newer
|
||||||
|
version is available, surface it non-intrusively — an "Update available"
|
||||||
|
line in Settings (next to the existing version/build info) with a hyperlink
|
||||||
|
to the release page, not a modal on launch.
|
||||||
|
|
||||||
|
Design notes / open questions:
|
||||||
|
|
||||||
|
- *Opt-in and offline-safe.* The check makes a network request, so it must be
|
||||||
|
off by default (or clearly consented) and never block startup. Failures
|
||||||
|
(offline, rate-limited, API change) should be silent — no error dialogs for a
|
||||||
|
best-effort convenience feature.
|
||||||
|
- *Version comparison.* Compare semantic versions, not strings, so `0.12.0`
|
||||||
|
reads as newer than `0.9.0`. A tiny semver comparator in `app` (or a small
|
||||||
|
dependency) avoids lexical bugs.
|
||||||
|
- *Where the check lives.* Keep it in the `app` layer behind the Service so the
|
||||||
|
UI only renders the result, and cache the last check so opening Settings
|
||||||
|
repeatedly does not spam the API (unauthenticated GitHub allows 60 req/h).
|
||||||
|
- *Repo coordinates.* The primary remote is Gitea; the GitHub repo used for
|
||||||
|
releases is [`mixeme/gosentry`](https://github.com/mixeme/gosentry) and must
|
||||||
|
be wired in explicitly (constant or build-time value) rather than derived from
|
||||||
|
`origin`.
|
||||||
|
- *No auto-download.* Scope is detection and notification only; installing the
|
||||||
|
update stays a manual click-through to the release page.
|
||||||
|
|
||||||
|
### Import/export jobs as a cron table
|
||||||
|
|
||||||
|
Jobs can only be moved between machines by copying `jobs.json` by hand. Add
|
||||||
|
"Import" / "Export" actions (Settings tab, file dialogs) that read and write a
|
||||||
|
crontab-style text file, so a job list can be shared, version-controlled, or
|
||||||
|
seeded from an existing Unix crontab.
|
||||||
|
|
||||||
|
Export writes one line per job — schedule fields, then command and arguments —
|
||||||
|
and import parses the same format back into `domain.Job` values.
|
||||||
|
|
||||||
|
Design notes / open questions:
|
||||||
|
|
||||||
|
- *The job model is wider than a crontab line.* `Name`, `Folder`, `StartOnly`,
|
||||||
|
`OverlapPolicy`, `TimeoutSeconds`, and `Enabled` have no cron equivalent.
|
||||||
|
Either accept a lossy export (schedule + command only) or carry the extra
|
||||||
|
fields in a structured comment above each line (`# gosentry: name=… folder=…
|
||||||
|
timeout=…`), which keeps the file readable by real cron while making the
|
||||||
|
round-trip lossless. The comment form is preferred; decide the exact key set
|
||||||
|
before implementing.
|
||||||
|
- *Disabled jobs.* `Enabled: false` maps naturally to a commented-out line, but
|
||||||
|
then a disabled job is indistinguishable from a user's own comment unless the
|
||||||
|
`# gosentry:` marker is present. Pick one representation and document it.
|
||||||
|
- *`@every` is not crontab.* GoSentry accepts `@every 10s` (see
|
||||||
|
[`domain.Parse`](../src/domain/schedule.go)), which no cron implementation
|
||||||
|
understands. Exporting it produces a file that is not a valid crontab;
|
||||||
|
exporting it as an approximation would silently change the schedule. Keep the
|
||||||
|
raw string and flag the file as GoSentry-flavoured, rather than converting.
|
||||||
|
- *Command vs arguments.* Crontab has a single command string; GoSentry splits
|
||||||
|
`Command` and `Arguments`. Import must split the line the same way the runner
|
||||||
|
would (see `runner/invocation*.go`, which differs per OS), and export must
|
||||||
|
join them back without changing quoting.
|
||||||
|
- *What to skip on import.* Environment assignments (`SHELL=`, `PATH=`,
|
||||||
|
`MAILTO=`), six-field (seconds) crontabs, and `@reboot` are outside what
|
||||||
|
`domain.Parse` accepts. Skip them, and report which lines were skipped and
|
||||||
|
why — a partial import that silently drops rows is worse than a failed one.
|
||||||
|
- *Merge semantics.* Import must decide between replacing the job list and
|
||||||
|
appending to it, and must assign fresh IDs rather than trusting the file.
|
||||||
|
Appending with a confirmation dialog is the safer default; replacing needs an
|
||||||
|
explicit "this deletes N jobs" confirmation.
|
||||||
|
- *Where it lives.* Encoding/decoding is pure text handling and belongs in
|
||||||
|
`domain` (or a small `storage` codec) with unit tests over round-trips; the
|
||||||
|
Service exposes import/export operations; the UI only picks the file and
|
||||||
|
shows the outcome.
|
||||||
|
|
||||||
|
### Split the files that are over the size guideline
|
||||||
|
|
||||||
|
[ARCHITECTURE.md](ARCHITECTURE.md) sets a ~250-line guideline per source file
|
||||||
|
and records the `jobs_view.go` and `settings_view.go` splits as the worked
|
||||||
|
examples. Six non-test files are over it at 1.0.0, including both files that
|
||||||
|
were already split once:
|
||||||
|
|
||||||
|
| File | Lines |
|
||||||
|
|------|-------|
|
||||||
|
| `src/app/operations.go` | 490 |
|
||||||
|
| `src/ui/jobs_view.go` | 355 |
|
||||||
|
| `src/app/run.go` | 287 |
|
||||||
|
| `src/ui/history_view.go` | 282 |
|
||||||
|
| `src/ui/settings_view.go` | 277 |
|
||||||
|
| `src/storage/store.go` | 265 |
|
||||||
|
|
||||||
|
This is deliberately deferred to the next whole-project review rather than done
|
||||||
|
piecemeal: [REVIEW.md](REVIEW.md) already asks item 2 to look for exactly this,
|
||||||
|
a split touches every reader of the file, and doing all six in one pass keeps
|
||||||
|
the seams consistent instead of settling them six different ways. Splitting is
|
||||||
|
also the kind of change that reads as pure movement while quietly dropping a
|
||||||
|
function, so it wants one careful pass, not six hurried ones.
|
||||||
|
|
||||||
|
Seams visible today, as a starting point rather than a decision:
|
||||||
|
|
||||||
|
- **`operations.go`** — the worst overage and the clearest split: the public
|
||||||
|
mutating operations (`CreateJob` … `UpdateSettings`), the `…Locked` state
|
||||||
|
helpers that only they call, and the pure validators and normalizers
|
||||||
|
(`normalizeJob`, `validateJob`, `hasFileName`, `validateConfig`) are three
|
||||||
|
distinct jobs already sitting in three consecutive blocks.
|
||||||
|
- **`history_view.go`** — the column-measuring helpers (`textWidth` through
|
||||||
|
`historyColumnWidths`) are pure, already unit-tested, and independent of the
|
||||||
|
table they size.
|
||||||
|
- **`jobs_view.go`** — nearly all of it is one `newJobsView` constructor, so the
|
||||||
|
split has to break that function up (list template, toolbar handlers,
|
||||||
|
assembly) rather than move whole functions. Larger judgement call than the
|
||||||
|
others.
|
||||||
|
- **`run.go`**, **`settings_view.go`**, **`store.go`** — barely over. Worth
|
||||||
|
re-measuring at the time; if a pass elsewhere has shrunk them, leave them
|
||||||
|
alone rather than splitting for the sake of the number.
|
||||||
|
|
||||||
|
Scope note: the guideline is about source files. Test files are much larger and
|
||||||
|
that is fine — a table-driven test file grows with the cases it covers.
|
||||||
|
|
||||||
### Window size persistence *(frozen)*
|
### Window size persistence *(frozen)*
|
||||||
|
|
||||||
Window size is currently **not** saved on quit or close. Saving was disabled
|
Window size is currently **not** saved on quit or close. Saving was disabled
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# GoSentry — Standards
|
||||||
|
|
||||||
|
Quality rules and intentional behavior for contributors. Package contracts live
|
||||||
|
in [ARCHITECTURE.md](ARCHITECTURE.md); test conventions in [TESTS.md](TESTS.md);
|
||||||
|
what a whole-project review looks at, in [REVIEW.md](REVIEW.md).
|
||||||
|
|
||||||
|
## Code quality
|
||||||
|
|
||||||
|
- Follow package contracts in [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||||
|
- User-facing errors → `dialog.ShowError` or a History event, never a silent `return`.
|
||||||
|
- Pure helpers → unit test in the same package.
|
||||||
|
- Fixes with severity ≥ medium → regression test.
|
||||||
|
- Documented intentional behavior → section below, not a backlog bug.
|
||||||
|
- UI view constructors accept `*app.Service`; call `app.Open()` only from `run.go`.
|
||||||
|
- A size that must follow the theme is **measured at build time, not written as
|
||||||
|
a pixel constant.** `theme.Padding()` and text metrics depend on the running
|
||||||
|
app's theme, text size, and DPI, so a hand-tuned number is only correct for
|
||||||
|
the one theme it was tuned against and clips under any other. Measure the real
|
||||||
|
widget, or derive the value from the theme, in a named helper: `rowOverlap`
|
||||||
|
(theme padding), `captionColumnWidth` and `textColumnWidth` (the widest of the
|
||||||
|
actual strings), `activityRowsHeight` (the list's own row template). The same
|
||||||
|
applies to a ratio computed from an absolute width — see `initialSplitOffset`.
|
||||||
|
A raw pixel literal is left only where nothing about it tracks the theme, and
|
||||||
|
says so in a comment.
|
||||||
|
|
||||||
|
## Config file compatibility
|
||||||
|
|
||||||
|
There is no migration step: `gosentry.json` and `jobs.json` are read as-is, are
|
||||||
|
meant to be hand-editable, and may have been written by an older version. A
|
||||||
|
change to their shape has to stay compatible on its own.
|
||||||
|
|
||||||
|
- A new `Config` field is tagged `omitempty`, and its zero value must mean the
|
||||||
|
behavior that existed before the field was added — a file written without it
|
||||||
|
keeps working unchanged. `DefaultConfig()` still sets the value explicitly.
|
||||||
|
- A zero that carries meaning is not a missing field and must not be backfilled
|
||||||
|
on load. See `DefaultTimeoutSeconds` in `storage.loadOrCreateConfig` and
|
||||||
|
`Job.TimeoutSeconds *int`, where unset and `0` are different answers.
|
||||||
|
- An unrecognised enum value reads as the default rather than an error, through
|
||||||
|
one helper that every consumer shares (`JobListView.IsCompact`, `ui.themeFor`),
|
||||||
|
and is normalized before being written back, so the file never gains a value
|
||||||
|
no reader understands.
|
||||||
|
- A renamed key keeps the old field on `Config` (tagged `omitempty`) purely so
|
||||||
|
it can still be read. `storage.loadOrCreateConfig` converts it to the new
|
||||||
|
field and clears it, so the retired key disappears on the next save. See
|
||||||
|
`Config.JobsDir` → `Config.JobsFile`. Where the new field has a non-empty
|
||||||
|
default, clear that default before unmarshalling, or "the file omits it" and
|
||||||
|
"the file sets it" become indistinguishable and the conversion never runs.
|
||||||
|
- Each of the three gets a test: the default in `storage`, the normalization in
|
||||||
|
`domain`, and a round-trip through the real config file in `app`.
|
||||||
|
|
||||||
|
## Intentional behavior (not bugs)
|
||||||
|
|
||||||
|
- `RunNow` is allowed during global pause and for disabled jobs.
|
||||||
|
- Selecting a jobs file that already exists **loads** it: its jobs replace the
|
||||||
|
in-memory list, which is the only way the user can switch between job lists. A
|
||||||
|
path with no file behind it receives the current jobs (rename/relocate). The
|
||||||
|
switch is refused while a job is running, because adoption drops every runtime
|
||||||
|
and a finishing run would then write its result onto whichever job inherited
|
||||||
|
its ID.
|
||||||
|
- Sequential mode runs jobs FIFO by order in `jobs.json`.
|
||||||
|
- Scheduler tick is 1s — sub-second `@every` intervals are not supported.
|
||||||
|
- Command timeout defaults to no timeout globally (`Config.DefaultTimeoutSeconds`
|
||||||
|
= 0) and is overridable per job (`Job.TimeoutSeconds *int`: unset = inherit the
|
||||||
|
global default, 0 = no timeout, positive = seconds). Neither zero may be
|
||||||
|
normalized away on load — 0 is a value, not a missing field.
|
||||||
|
- **History tab is session-only.** `JobRuntime.Logs` exists only in memory for the
|
||||||
|
current process. Log files on disk feed aggregate statistics via `SeedStats`
|
||||||
|
only. See [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
Larger or blocked work is tracked in [ROADMAP.md](ROADMAP.md) (update check from
|
||||||
|
GitHub releases, cron-table import/export, window size persistence, History
|
||||||
|
column filters).
|
||||||
@@ -22,6 +22,10 @@ Both scripts run:
|
|||||||
1. `go vet ./...` — static analysis for common errors and suspicious code patterns
|
1. `go vet ./...` — static analysis for common errors and suspicious code patterns
|
||||||
2. `go test -race ./...` — tests with race condition detection enabled
|
2. `go test -race ./...` — tests with race condition detection enabled
|
||||||
|
|
||||||
|
The GUI tests build the Fyne desktop backend, so CGO must be enabled; on Windows
|
||||||
|
that means the MSYS2 UCRT64 toolchain described in
|
||||||
|
[DEVELOPMENT.md](DEVELOPMENT.md).
|
||||||
|
|
||||||
### Manual test commands
|
### Manual test commands
|
||||||
|
|
||||||
Run all tests:
|
Run all tests:
|
||||||
@@ -74,6 +78,20 @@ Tests schedule parsing and validation.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### src/domain/config_test.go
|
||||||
|
|
||||||
|
**Package:** `domain`
|
||||||
|
|
||||||
|
Tests the normalization rule shared by every consumer of the jobs-list density
|
||||||
|
setting.
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestJobListViewIsCompact` | Verifies only the exact `"compact"` value selects one-line rows: empty, differently-cased, and unrecognised values all read as detailed. |
|
||||||
|
| `TestDefaultConfigUsesDetailedJobList` | Verifies `DefaultConfig` selects the detailed job list. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### src/app/service_test.go
|
### src/app/service_test.go
|
||||||
|
|
||||||
**Package:** `app`
|
**Package:** `app`
|
||||||
@@ -114,13 +132,15 @@ Tests all mutating operations on the Service, scheduler integration, and setting
|
|||||||
| Test | Purpose |
|
| Test | Purpose |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
| `TestSetGlobalPauseUpdatesRuntimesAndEmits` | Verifies that `SetGlobalPause` updates all job runtimes, emits `SchedulerStateChanged`, and persists state. |
|
| `TestSetGlobalPauseUpdatesRuntimesAndEmits` | Verifies that `SetGlobalPause` updates all job runtimes, emits `SchedulerStateChanged`, and persists state. |
|
||||||
|
| `TestSetGlobalPausePersistsToConfigFile` | Verifies the paused flag reaches `gosentry.json`, which is what makes the pause survive a restart. |
|
||||||
|
| `TestServiceRebuiltFromPausedStoreStartsPaused` | Verifies a Service built from a paused config starts paused, with the paused next-run text applied before the first tick. |
|
||||||
| `TestRunNowUsesRunnerAndRecords` | Verifies that `RunNow` invokes the runner, records a `RunRecord`, and emits `RunRecorded`. |
|
| `TestRunNowUsesRunnerAndRecords` | Verifies that `RunNow` invokes the runner, records a `RunRecord`, and emits `RunRecorded`. |
|
||||||
| `TestRunNowNotFound` | Verifies that `RunNow` returns an error for an unknown job ID. |
|
| `TestRunNowNotFound` | Verifies that `RunNow` returns an error for an unknown job ID. |
|
||||||
| `TestRunNowRefusedWhileAlreadyRunning` | Verifies that a second concurrent `RunNow` on the same job is rejected while the first is in progress. |
|
| `TestRunNowRefusedWhileAlreadyRunning` | Verifies that a second concurrent `RunNow` on the same job is rejected while the first is in progress. |
|
||||||
| `TestRunNowRefusedWhilePaused` | Verifies that `RunNow` is rejected when the global pause flag is set. |
|
| `TestRunNowAllowedWhilePaused` | Verifies that `RunNow` is allowed when the global pause flag is set (pause stops scheduled runs only). |
|
||||||
| `TestRunDueStartsDueJob` | Verifies that `RunDue` launches a job whose next-run time has passed. |
|
| `TestRunDueStartsDueJob` | Verifies that `RunDue` launches a job whose next-run time has passed. |
|
||||||
| `TestRunDueSkipsJobNotYetDue` | Verifies that `RunDue` does not launch a job that is not yet due. |
|
| `TestRunDueSkipsJobNotYetDue` | Verifies that `RunDue` does not launch a job that is not yet due. |
|
||||||
| `TestRunDueSkipsJobInRunningState` | Verifies that `RunDue` does not start a second concurrent run for an already-running job. |
|
| `TestRunDueSkipsJobInRunningState` | Verifies that `RunDue` does not start a second concurrent run for an already-running job, even with a stale `NextDue` in the past. |
|
||||||
| `TestRunDueDoesNothingWhilePaused` | Verifies that `RunDue` launches nothing when the global pause flag is set. |
|
| `TestRunDueDoesNothingWhilePaused` | Verifies that `RunDue` launches nothing when the global pause flag is set. |
|
||||||
| `TestStartDrivesRunDueOnTick` | Verifies that `Service.Start` wires `RunDue` to the scheduler tick and that each tick advances state. |
|
| `TestStartDrivesRunDueOnTick` | Verifies that `Service.Start` wires `RunDue` to the scheduler tick and that each tick advances state. |
|
||||||
|
|
||||||
@@ -130,10 +150,43 @@ Tests all mutating operations on the Service, scheduler integration, and setting
|
|||||||
|------|---------|
|
|------|---------|
|
||||||
| `TestUpdateSettingsPersistsAndValidates` | Verifies that `UpdateSettings` persists a valid config and rewrites autostart if needed. |
|
| `TestUpdateSettingsPersistsAndValidates` | Verifies that `UpdateSettings` persists a valid config and rewrites autostart if needed. |
|
||||||
| `TestUpdateSettingsRejectsInvalidConfigs` | Verifies that `UpdateSettings` returns validation errors without persisting. |
|
| `TestUpdateSettingsRejectsInvalidConfigs` | Verifies that `UpdateSettings` returns validation errors without persisting. |
|
||||||
|
| `TestHasFileName` | Verifies the jobs-file path check: a file name passes; a trailing separator, `.`, and `..` do not. |
|
||||||
|
| `TestUpdateSettingsWritesJobsToTheNewFile` | Verifies that changing `JobsFile` re-resolves `Paths.JobsPath` and writes the loaded jobs to the new file, creating its folder. |
|
||||||
|
| `TestUpdateSettingsAdoptsExistingJobsFile` | Verifies that selecting a jobs file that already exists replaces the job list with its contents, rebuilds runtimes, and emits `JobsLoaded`. |
|
||||||
|
| `TestUpdateSettingsKeepsJobsWhenTheNewFileIsMissing` | Verifies that a path with no file behind it receives the current jobs instead (the rename/relocate case). |
|
||||||
|
| `TestUpdateSettingsRefusesJobsFileSwitchWhileRunning` | Verifies that switching the jobs file is refused (and not persisted) while a job runs, while unrelated settings still save. |
|
||||||
|
| `TestSetJobListViewPersistsToConfigFile` | Verifies the Jobs-list density preference reaches `gosentry.json`, so the chosen view reopens after a restart. |
|
||||||
|
| `TestSetJobListViewNormalizesUnknownValue` | Verifies anything but `"compact"` is stored as `"detailed"`, so the config never gains a value no reader understands. |
|
||||||
| `TestPrependLogCapsActivityList` | Verifies that the activity log never grows beyond its maximum cap. |
|
| `TestPrependLogCapsActivityList` | Verifies that the activity log never grows beyond its maximum cap. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### src/app/run_test.go
|
||||||
|
|
||||||
|
**Package:** `app`
|
||||||
|
|
||||||
|
Tests overlap policy, sequential execution, run statistics, timeout resolution,
|
||||||
|
and scheduler edge cases using injected `runJob` and `primeDue`.
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestUpdateStats` | Verifies aggregate duration math on `JobRuntime`. |
|
||||||
|
| `TestUpdateStatsSkipsZeroDuration` | Verifies zero-duration runs are excluded from averages. |
|
||||||
|
| `TestRunDueParallelStartsAllDueJobs` | Parallel mode: both due jobs enter the runner before either completes. |
|
||||||
|
| `TestRunDueSequentialSerializes` | Sequential mode: job 2 waits until job 1 finishes. |
|
||||||
|
| `TestRunDueSkipDropsOverlap` | Global skip: no second concurrent run, `PendingRuns` stays 0. |
|
||||||
|
| `TestRunDueQueueRerunsAfterFinish` | Queue: one deferred run after an in-flight finish. |
|
||||||
|
| `TestRunDueQueueDrainsMultipleOverlaps` | Queue: multiple missed ticks drain as separate runs. |
|
||||||
|
| `TestRunDuePerJobQueueOverridesGlobalSkip` | Per-job `queue` beats global `skip`. |
|
||||||
|
| `TestRunDuePerJobSkipOverridesGlobalQueue` | Per-job `skip` beats global `queue`. |
|
||||||
|
| `TestRunDueEmptyOverlapInheritsGlobal` | Empty per-job policy inherits the global default. |
|
||||||
|
| `TestRunNowSequentialGuard` | Manual run refused while another job runs in sequential mode. |
|
||||||
|
| `TestStartRunLockedRollbackOnSaveFailure` | Regression: run does not start when `SaveJobs` fails. |
|
||||||
|
| `TestRunDueQueueDrainSkippedWhenPaused` | Queued overlaps are not drained while the scheduler is paused. |
|
||||||
|
| `TestEffectiveTimeout` | Verifies the three-state resolution: `nil` inherits the global default, a positive value overrides it, and an explicit `0` means no timeout without inheriting. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### src/app/events_test.go
|
### src/app/events_test.go
|
||||||
|
|
||||||
**Package:** `app`
|
**Package:** `app`
|
||||||
@@ -158,11 +211,15 @@ Tests display-formatting helpers used by the UI.
|
|||||||
|------|---------|
|
|------|---------|
|
||||||
| `TestStatusText` | Verifies that job status codes map to the correct display strings. |
|
| `TestStatusText` | Verifies that job status codes map to the correct display strings. |
|
||||||
| `TestEventText` | Verifies trigger-type labels for scheduled, manual, and UI triggers. |
|
| `TestEventText` | Verifies trigger-type labels for scheduled, manual, and UI triggers. |
|
||||||
|
| `TestEventLine` | Verifies the one-line activity rendering of a `RunRecord`, including the log basename and the `Unknown` fallback for a blank trigger. |
|
||||||
| `TestDisplayFolder` | Verifies that an empty folder string shows "No folder". |
|
| `TestDisplayFolder` | Verifies that an empty folder string shows "No folder". |
|
||||||
| `TestDisplayArguments` | Verifies that an empty arguments string shows "None". |
|
| `TestDisplayArguments` | Verifies that an empty arguments string shows "None". |
|
||||||
| `TestDisplayRunMode` | Verifies run-mode labels for normal and start-only modes. |
|
| `TestDisplayRunMode` | Verifies run-mode labels for normal and start-only modes. |
|
||||||
| `TestDisplayInvocation` | Verifies that the full invocation display string combines command and arguments with spacing. |
|
| `TestDisplayInvocation` | Verifies that the full invocation display string combines command and arguments with spacing. |
|
||||||
| `TestDisplayIndex` | Verifies that the display index is one-based (job slice index + 1). |
|
| `TestDisplayIndex` | Verifies the list position of a job index in a filtered index slice. |
|
||||||
|
| `TestDisplayStats` | Verifies statistics line formatting for the details panel. |
|
||||||
|
| `TestDisplayOverlapPolicy` | Verifies per-job vs inherited global overlap policy labels. |
|
||||||
|
| `TestDisplayTimeout` | Verifies the three timeout states read differently in the details panel: `45 s`, `no timeout`, and `… (global default)`. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -170,7 +227,7 @@ Tests display-formatting helpers used by the UI.
|
|||||||
|
|
||||||
**Package:** `storage`
|
**Package:** `storage`
|
||||||
|
|
||||||
Tests JSON round-tripping and default generation.
|
Tests JSON round-tripping, default generation, and backward compatibility.
|
||||||
|
|
||||||
| Test | Purpose |
|
| Test | Purpose |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
@@ -178,6 +235,11 @@ Tests JSON round-tripping and default generation.
|
|||||||
| `TestConfigRoundTrip` | Verifies that settings saved to JSON are reloaded with identical field values. |
|
| `TestConfigRoundTrip` | Verifies that settings saved to JSON are reloaded with identical field values. |
|
||||||
| `TestNormalizeJobsFillsDefaults` | Verifies that `normalizeJobs` assigns sequential IDs and sets default name, schedule, and command for jobs missing those fields. |
|
| `TestNormalizeJobsFillsDefaults` | Verifies that `normalizeJobs` assigns sequential IDs and sets default name, schedule, and command for jobs missing those fields. |
|
||||||
| `TestLoadOrCreateConfigCreatesDefaultsOnFirstRun` | Verifies that a missing config file is created with sane defaults and a sample job. |
|
| `TestLoadOrCreateConfigCreatesDefaultsOnFirstRun` | Verifies that a missing config file is created with sane defaults and a sample job. |
|
||||||
|
| `TestLoadOrCreateConfigKeepsZeroTimeoutOnReload` | Verifies that `default_timeout_seconds: 0` survives a reload rather than being normalized away — 0 is a value, not a missing field. |
|
||||||
|
| `TestLoadOrCreateConfigMigratesJobsDir` | Verifies that a pre-0.15 `jobs_dir` becomes `jobs_file` pointing at the same `jobs.json`, and that the retired key is not written back. |
|
||||||
|
| `TestLoadJobsFileReportsMissingWithoutCreating` | Verifies that `LoadJobsFile` reports a missing file as not-found without creating or seeding it, and normalizes the jobs it does load. |
|
||||||
|
| `TestApplyConfigPathsDerivesJobsDir` | Verifies that the configured jobs file resolves against the program folder and that `Paths.JobsDir` is derived from it. |
|
||||||
|
| `TestJobTimeoutRoundTripsThreeStates` | Verifies the on-disk encoding that keeps "inherit" and "no timeout" distinguishable: `nil` is omitted entirely, an explicit `0` is written and read back as set. |
|
||||||
| `TestJobsJSONDoesNotPersistRuntimeNoise` | Verifies that `jobs.json` does not persist runtime state (LastRun, NextRun, etc.). Only durable job fields are stored. |
|
| `TestJobsJSONDoesNotPersistRuntimeNoise` | Verifies that `jobs.json` does not persist runtime state (LastRun, NextRun, etc.). Only durable job fields are stored. |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -199,7 +261,7 @@ Tests the timing-loop contract using a fake clock.
|
|||||||
|
|
||||||
**Package:** `runner`
|
**Package:** `runner`
|
||||||
|
|
||||||
Tests command execution, exit code handling, output capture, and Windows-specific process behavior.
|
Tests command execution, exit code handling, output capture, and the run timeout.
|
||||||
|
|
||||||
#### Log file tests
|
#### Log file tests
|
||||||
|
|
||||||
@@ -232,6 +294,14 @@ Tests command execution, exit code handling, output capture, and Windows-specifi
|
|||||||
|------|---------|
|
|------|---------|
|
||||||
| `TestRunJobFailsOnNonZeroExitCode` | Verifies that a nonzero process exit code results in "Failed" status with an "exit code N" detail. |
|
| `TestRunJobFailsOnNonZeroExitCode` | Verifies that a nonzero process exit code results in "Failed" status with an "exit code N" detail. |
|
||||||
|
|
||||||
|
#### Timeout
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestRunJobTimesOut` | Verifies that a positive timeout kills a long-running command and reports `Timed out after <timeout>`. |
|
||||||
|
| `TestRunJobZeroTimeoutMeansNoTimeout` | Verifies that a non-positive duration runs without a deadline, bounded only by the caller's context. |
|
||||||
|
| `TestRunJobStartOnlyIgnoresTimeout` | Verifies that fire-and-forget jobs run on the untimed context, so the timeout never kills a process the runner is not waiting for. |
|
||||||
|
|
||||||
#### Start-only mode
|
#### Start-only mode
|
||||||
|
|
||||||
| Test | Purpose |
|
| Test | Purpose |
|
||||||
@@ -239,14 +309,39 @@ Tests command execution, exit code handling, output capture, and Windows-specifi
|
|||||||
| `TestRunJobStartOnlyDoesNotWaitForExitCode` | Verifies that `StartOnly: true` jobs launch and return "OK" immediately without waiting for the process to exit. |
|
| `TestRunJobStartOnlyDoesNotWaitForExitCode` | Verifies that `StartOnly: true` jobs launch and return "OK" immediately without waiting for the process to exit. |
|
||||||
| `TestRunJobStartOnlyReportsStartFailure` | Verifies that `StartOnly: true` jobs still report "Failed" if the process cannot be started. |
|
| `TestRunJobStartOnlyReportsStartFailure` | Verifies that `StartOnly: true` jobs still report "Failed" if the process cannot be started. |
|
||||||
|
|
||||||
#### Utility / Windows invocation
|
---
|
||||||
|
|
||||||
| Test | Platform | Purpose |
|
### src/runner/runner_windows_test.go
|
||||||
|------|----------|---------|
|
|
||||||
| `TestDirectCommandDoesNotHideWindow` | Windows | Verifies that direct executable commands do not request hidden-window startup. |
|
**Location:** `src/runner/runner_windows_test.go`
|
||||||
| `TestShellCommandHidesWindow` | Windows | Verifies that shell commands request hidden-window startup to prevent console flash. |
|
**Build Tags:** `//go:build windows`
|
||||||
| `TestShellCommandUsesWindowsSafeQuoting` | Windows | Verifies `cmd.exe /S /C` quoting for paths with spaces and special characters. |
|
|
||||||
| `TestWindowsShellCommandLineQuotesUnquotedProgramPath` | Windows | Verifies that unquoted program paths in shell commands are quoted while preserving already-quoted arguments. |
|
Tests the Windows shell invocation and hidden-window flags.
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestDirectCommandDoesNotHideWindow` | Verifies that direct executable commands do not request hidden-window startup. |
|
||||||
|
| `TestShellCommandHidesWindow` | Verifies that shell commands request hidden-window startup to prevent console flash. |
|
||||||
|
| `TestShellCommandUsesWindowsSafeQuoting` | Verifies `cmd.exe /S /C` quoting for paths with spaces and special characters. |
|
||||||
|
| `TestWindowsShellCommandLineQuotesUnquotedProgramPath` | Verifies that unquoted program paths in shell commands are quoted while preserving already-quoted arguments. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### src/runner/seed_test.go
|
||||||
|
|
||||||
|
**Package:** `runner`
|
||||||
|
|
||||||
|
Tests `SeedStats`, which rebuilds aggregate run statistics from the `.log` files
|
||||||
|
on disk at startup.
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestSeedStatsBasic` | Verifies run/fail counts and the last, average, and maximum durations parsed from a job's log headers. |
|
||||||
|
| `TestSeedStatsDurationLessLegacyLog` | Verifies a log written before the `duration` header still counts as a run but is excluded from the duration aggregates, so a missing duration cannot masquerade as a 0 ms run. |
|
||||||
|
| `TestSeedStatsMaxFilesHonoured` | Verifies that only the newest `MaxLogFiles` logs are parsed when the limit is positive. |
|
||||||
|
| `TestSeedStatsMissingDir` | Verifies a missing logs directory yields an empty map rather than an error or a panic. |
|
||||||
|
| `TestSeedStatsUnknownJobProducesNoEntry` | Verifies log files that match no known job are ignored. |
|
||||||
|
| `TestSeedStatsMatchesByJobID` | Verifies logs are matched by the `job_id` header even when two job names sanitize to the same filename. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -277,7 +372,6 @@ Tests Windows autostart via shortcuts in the Startup folder.
|
|||||||
|
|
||||||
| Test | Purpose |
|
| Test | Purpose |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
| `TestParseRegistryRunValue` | Verifies that legacy `HKCU\...\Run` entry values are parsed correctly from `reg query` output (for migration/cleanup). |
|
|
||||||
| `TestSameWindowsPathIgnoresCaseAndQuotes` | Verifies that Windows path comparison is case-insensitive and handles quote marks correctly. |
|
| `TestSameWindowsPathIgnoresCaseAndQuotes` | Verifies that Windows path comparison is case-insensitive and handles quote marks correctly. |
|
||||||
| `TestSameWindowsPathHandlesSpaces` | Verifies that Windows path comparison matches paths with and without surrounding quotes. |
|
| `TestSameWindowsPathHandlesSpaces` | Verifies that Windows path comparison matches paths with and without surrounding quotes. |
|
||||||
| `TestSameWindowsPathStripsExtendedLengthPrefix` | Verifies that `\\?\`-prefixed paths are compared correctly after stripping the prefix. |
|
| `TestSameWindowsPathStripsExtendedLengthPrefix` | Verifies that `\\?\`-prefixed paths are compared correctly after stripping the prefix. |
|
||||||
@@ -298,7 +392,35 @@ Tests Linux autostart via XDG Desktop Entry files.
|
|||||||
| Test | Purpose |
|
| Test | Purpose |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
| `TestLinuxAutostartStartsInTray` | Verifies that the XDG Desktop Entry is created with `--start-in-tray` in the `Exec=` field. |
|
| `TestLinuxAutostartStartsInTray` | Verifies that the XDG Desktop Entry is created with `--start-in-tray` in the `Exec=` field. |
|
||||||
| `TestLinuxAutostartRemovesLegacyDesktopEntry` | Verifies that enabling autostart also removes legacy PySentry service files left by earlier builds. |
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### src/platform/desktop/desktop_linux_test.go
|
||||||
|
|
||||||
|
**Location:** `src/platform/desktop/desktop_linux_test.go`
|
||||||
|
**Build Tags:** `//go:build linux`
|
||||||
|
|
||||||
|
Tests Linux desktop integration (`.desktop` file and icon under XDG data home).
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestInstallDesktopIntegrationWritesDesktopAndIcon` | Verifies `.desktop` and PNG icon files are written under `$XDG_DATA_HOME`. |
|
||||||
|
| `TestQuoteDesktopExecQuotesPath` | Verifies `Exec=` paths with spaces are shell-quoted. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### src/platform/filemanager/filemanager_test.go
|
||||||
|
|
||||||
|
**Package:** `filemanager`
|
||||||
|
|
||||||
|
Tests the guards around opening a folder in the desktop file manager. The
|
||||||
|
success path is not tested: it would open a real file manager window.
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestOpenRejectsMissingFolder` | Verifies that `Open` reports a missing directory (naming the path) instead of launching a handler. |
|
||||||
|
| `TestOpenRejectsFile` | Verifies that `Open` refuses a path that is a file rather than a directory. |
|
||||||
|
| `TestOpenCommandNamesPlatformHandler` | Verifies the per-platform handler (`explorer` / `xdg-open`, none elsewhere) and that the path is passed as one argument. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -306,7 +428,9 @@ Tests Linux autostart via XDG Desktop Entry files.
|
|||||||
|
|
||||||
**Package:** `ui`
|
**Package:** `ui`
|
||||||
|
|
||||||
Tests pure helper functions in the jobs view (no Fyne widget construction).
|
Tests the Jobs tab: pure filter helpers, and — through Fyne's headless
|
||||||
|
`test.NewApp()` — the geometry and redraw behaviour that only shows up once the
|
||||||
|
widgets are assembled.
|
||||||
|
|
||||||
| Test | Purpose |
|
| Test | Purpose |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
@@ -317,6 +441,94 @@ Tests pure helper functions in the jobs view (no Fyne widget construction).
|
|||||||
| `TestFilteredJobIndexesByNamedFolder` | Verifies that filtering by a named folder returns only jobs in that folder. |
|
| `TestFilteredJobIndexesByNamedFolder` | Verifies that filtering by a named folder returns only jobs in that folder. |
|
||||||
| `TestFilteredJobIndexesNoFolder` | Verifies that the "No folder" filter returns only jobs with an empty folder field. |
|
| `TestFilteredJobIndexesNoFolder` | Verifies that the "No folder" filter returns only jobs with an empty folder field. |
|
||||||
| `TestFilteredJobIndexesEmptySlice` | Verifies that filtering an empty job slice returns an empty index list. |
|
| `TestFilteredJobIndexesEmptySlice` | Verifies that filtering an empty job slice returns an empty index list. |
|
||||||
|
| `TestNextJobListViewFlipsBothWays` | Verifies the density toggle alternates between detailed and compact from either starting value. |
|
||||||
|
| `TestViewToggleTextNamesTheAction` | Verifies the toggle button is labelled with the action it performs, not the state it is in. |
|
||||||
|
| `TestJobListViewToggleShrinksRowsAndPersists` | End-to-end: one tap shrinks the row height, relabels the button, and reaches the config; tapping back undoes all three. |
|
||||||
|
| `TestJobListViewCompactConfigOpensCompact` | Verifies the persisted density is honoured at build time, not only after a tap. |
|
||||||
|
| `TestJobsSidebarWidthIsItsContent` | Regression guard: nothing but the sidebar's own toolbar row imposes a width floor on it. |
|
||||||
|
| `TestJobsSplitOpensAtTheSidebarWidth` | Verifies the derived split offset opens the divider at the sidebar's own width at the default window size — enough that the toolbar is never born clipped, and no more. |
|
||||||
|
| `TestToolbarButtonRedrawsRowAndDetails` | Regression guard: with the duplicate refreshes removed from the handlers, `refreshView` alone must re-snapshot the jobs and repopulate the details pane. |
|
||||||
|
| `TestDetailCaptionWidthCoversEveryCaption` | Verifies every caption `metadataRows` returns fits the measured caption column, which is what makes the single row list self-enforcing. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### src/ui/history_view_test.go
|
||||||
|
|
||||||
|
**Package:** `ui`
|
||||||
|
|
||||||
|
Tests the History tab: the pure activity helpers and the sorted-snapshot and
|
||||||
|
column-width behaviour of the assembled table.
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestCollectActivityMergesAndSorts` | Verifies per-job logs are merged and sorted by time. |
|
||||||
|
| `TestCollectActivitySkipsMissingRuntimes` | Verifies missing runtime entries are skipped safely. |
|
||||||
|
| `TestHistoryCellText` | Verifies table cell text for all columns; empty trigger → `Unknown`. |
|
||||||
|
| `TestLogFileName` | Verifies log path basename extraction on Windows and Unix paths. |
|
||||||
|
| `TestNewEventUsesConsistentTimestampShape` | Verifies UI events use the same timestamp layout as run records. |
|
||||||
|
| `TestLastJobLogsCapsAndCopies` | Verifies activity panel cap and defensive copy semantics. |
|
||||||
|
| `TestLastJobLogsEmpty` | Verifies nil/empty log input returns an empty slice. |
|
||||||
|
| `TestIndexOfID` | Verifies job lookup by ID returns `-1` when not found. |
|
||||||
|
| `TestHistorySortToggleKeepsRowsInSync` | Regression guard for the cached sorted snapshot: the length callback and the cells must be refilled together, or the row count and the cell contents disagree. |
|
||||||
|
| `TestHistoryCellTemplateIsPlainText` | Verifies the cell template already carries the zero `TextStyle`, since the per-cell assignment that used to reset it is gone. |
|
||||||
|
| `TestTextColumnWidthClamps` | Covers the three shapes of `textColumnWidth`: below the minimum, in range, and capped at the maximum. |
|
||||||
|
| `TestHistoryColumnsFitTheirContent` | Verifies every column is at least as wide as its widest known or present value, at the default text size and at a scaled theme. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### src/ui/settings_view_test.go
|
||||||
|
|
||||||
|
**Package:** `ui`
|
||||||
|
|
||||||
|
Tests the Settings tab helpers and the row layout.
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestSettingsFolderPath` | Verifies the folder the Logs directory "Open" button targets: blank text yields no path, a relative path resolves against the application directory, an absolute path is used as typed. |
|
||||||
|
| `TestSettingsRowStretchesItsControl` | Verifies the row's centre slot already stretches the control to the column width — the property that made a fixed-width wrapper around it redundant. |
|
||||||
|
| `TestChooseFileAppliesFilter` | Verifies the deduplicated picker opens a dialog both with a nil filter (the command browser) and with a concrete one (`chooseJSONFile`). |
|
||||||
|
| `TestSettingsCaptionsCoverEveryRow` | Verifies every caption used in a row is present in `settingsCaptions` and fits the measured caption column. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### src/ui/layout_test.go
|
||||||
|
|
||||||
|
**Package:** `ui`
|
||||||
|
|
||||||
|
Tests the theme-derived sizing helpers in `layout.go`.
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestRowOverlapMatchesInnerPadding` | Pins `rowOverlap` to `-theme.InnerPadding()` under two themes, the property that lets it follow a theme instead of drifting from a hand-tuned literal. |
|
||||||
|
| `TestCaptionColumnWidth` | Covers no captions, one, and several of varying length, at two text sizes. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### src/ui/theme_test.go
|
||||||
|
|
||||||
|
**Package:** `ui`
|
||||||
|
|
||||||
|
Tests the branded theme and the stored theme choice.
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestGoSentryThemeBrandColors` | Verifies the brand colors land on the semantically correct `ColorName`s in both the light and dark variants. |
|
||||||
|
| `TestGoSentryThemeDelegatesUnbrandedColors` | Verifies unbranded color names fall through to the base theme rather than rendering transparent. |
|
||||||
|
| `TestThemeForChoice` | Verifies the GoSentry choice yields the branded primary and every other value — including the empty legacy one — yields the default theme. |
|
||||||
|
| `TestThemeLabelRoundTrip` | Verifies the dropdown labels round-trip and that the empty value maps to the Default label rather than a blank option. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### src/ui/mainwindow_test.go
|
||||||
|
|
||||||
|
**Package:** `ui`
|
||||||
|
|
||||||
|
Tests main view construction with an injected `*app.Service`.
|
||||||
|
|
||||||
|
| Test | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `TestMainViewFitsTheDefaultWindowSize` | Verifies the assembled content's minimum fits the window size the app asks for, so Fyne never silently widens the window past it. The store's config path is deliberately long, since it was the path label that used to grow the Settings tab. |
|
||||||
|
| `TestMainViewBuilds` | Verifies `newMainView` assembles tabs without panic using `fyne.io/fyne/v2/test`. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -334,9 +546,14 @@ Tests pure helper functions in the jobs view (no Fyne widget construction).
|
|||||||
|
|
||||||
6. **Start-Only Mode** — Special handling for long-running processes that should be launched but not waited on, tested separately from normal execution flow.
|
6. **Start-Only Mode** — Special handling for long-running processes that should be launched but not waited on, tested separately from normal execution flow.
|
||||||
|
|
||||||
|
7. **Regression on serious fixes** — Any fix from an internal review with severity ≥ medium gets a targeted regression test (see `run_test.go` for examples).
|
||||||
|
|
||||||
|
8. **Geometry is measured, not eyeballed** — The `ui` tests that build widgets under `test.NewApp()` assert sizes and offsets, and several re-run under a scaled theme. That is what keeps [STANDARDS.md](STANDARDS.md)'s "measure at build time, never a pixel constant" rule enforceable rather than aspirational.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Remaining Test Coverage Gaps
|
## Remaining Test Coverage Gaps
|
||||||
|
|
||||||
- GUI integration tests — Fyne widget interaction is not yet tested end-to-end
|
- Full GUI E2E — tab navigation, dialog flows, and native file pickers are not exercised end-to-end; the `ui` tests assemble views and measure them, but nothing drives a real window.
|
||||||
- Job history on-disk retrieval — RunRecord file reading is not covered
|
- History is session-only by design — `.log` files seed aggregate stats only, not the History table (see [STANDARDS.md](STANDARDS.md))
|
||||||
|
- Fyne's headless driver cannot report a maximized window, which is why window-size persistence stays frozen in [ROADMAP.md](ROADMAP.md)
|
||||||
|
|||||||
@@ -18,12 +18,14 @@ fi
|
|||||||
docker build -f Dockerfile -t "$tag" .
|
docker build -f Dockerfile -t "$tag" .
|
||||||
|
|
||||||
mkdir -p "$(dirname "$output")"
|
mkdir -p "$(dirname "$output")"
|
||||||
|
mkdir -p "$(pwd)/.gocache"
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
"${docker_user_args[@]}" \
|
"${docker_user_args[@]}" \
|
||||||
-e "VERSION=${version}" \
|
-e "VERSION=${version}" \
|
||||||
-e "OUTPUT=${output}" \
|
-e "OUTPUT=${output}" \
|
||||||
-e "GOCACHE=/tmp/go-build-cache" \
|
-e "GOCACHE=/tmp/go-build-cache" \
|
||||||
-v "$(pwd):/src" \
|
-v "$(pwd):/src" \
|
||||||
|
-v "$(pwd)/.gocache:/tmp/go-build-cache" \
|
||||||
-w /src \
|
-w /src \
|
||||||
"$tag" \
|
"$tag" \
|
||||||
bash -c 'CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -buildvcs=false -trimpath -ldflags "-s -w -X gitea.mixdep.ru/mix/gosentry/src/app.Version=${VERSION}" -o "${OUTPUT}" ./cmd/gosentry'
|
bash -c 'CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -buildvcs=false -trimpath -ldflags "-s -w -X gitea.mixdep.ru/mix/gosentry/src/app.Version=${VERSION}" -o "${OUTPUT}" ./cmd/gosentry'
|
||||||
|
|||||||
@@ -88,11 +88,13 @@ normalize_targets() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
run_in_builder() {
|
run_in_builder() {
|
||||||
|
mkdir -p "${repo_root}/.gocache"
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
"${docker_user_args[@]}" \
|
"${docker_user_args[@]}" \
|
||||||
-e "VERSION=${version}" \
|
-e "VERSION=${version}" \
|
||||||
-e "GOCACHE=/tmp/go-build-cache" \
|
-e "GOCACHE=/tmp/go-build-cache" \
|
||||||
-v "${repo_root}:/src" \
|
-v "${repo_root}:/src" \
|
||||||
|
-v "${repo_root}/.gocache:/tmp/go-build-cache" \
|
||||||
-w /src \
|
-w /src \
|
||||||
"$tag" \
|
"$tag" \
|
||||||
bash -c "$1"
|
bash -c "$1"
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Build and package every release artifact on a Linux host that already has the
|
||||||
|
# cross toolchain installed (native gcc + X11/OpenGL headers, the aarch64 cross
|
||||||
|
# compiler, and the MinGW-w64 toolchain for the Windows GUI binary). This is the
|
||||||
|
# non-Docker counterpart to scripts/build-release-linux.sh: the CI workflows in
|
||||||
|
# .github/ and .forgejo/ install those packages directly on the runner and then
|
||||||
|
# call this script, so the exact build/package commands live in one place and do
|
||||||
|
# not drift between the two forges.
|
||||||
|
#
|
||||||
|
# The build flags mirror the other scripts intentionally: -trimpath strips local
|
||||||
|
# paths, -s -w drops symbol/debug tables to shrink the binaries, -H=windowsgui
|
||||||
|
# suppresses the console window on Windows, and -X injects the version so the
|
||||||
|
# GUI and artifact names agree.
|
||||||
|
|
||||||
|
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
repo_root="$(cd "${script_dir}/.." && pwd)"
|
||||||
|
cd "$repo_root"
|
||||||
|
|
||||||
|
# VERSION can be provided by CI (for a tagged release the workflow passes the tag
|
||||||
|
# without its leading "v"). Fall back to the source of truth in version.go so the
|
||||||
|
# script also works for a plain local invocation.
|
||||||
|
version="${VERSION:-$(sed -n 's/^var Version = "\(.*\)"/\1/p' src/app/version.go | tr -d '\r')}"
|
||||||
|
version="${version:-0.0.0-dev}"
|
||||||
|
ldflags="-s -w -X gitea.mixdep.ru/mix/gosentry/src/app.Version=${version}"
|
||||||
|
|
||||||
|
echo "Building GoSentry ${version} release artifacts"
|
||||||
|
mkdir -p dist/linux dist/windows
|
||||||
|
|
||||||
|
# --- Linux amd64 -----------------------------------------------------------
|
||||||
|
echo "==> linux/amd64"
|
||||||
|
CGO_ENABLED=1 GOOS=linux GOARCH=amd64 \
|
||||||
|
go build -buildvcs=false -trimpath -ldflags "$ldflags" \
|
||||||
|
-o "dist/linux/gosentry-${version}-linux-amd64" ./cmd/gosentry
|
||||||
|
|
||||||
|
# --- Linux arm64 (cross compiled) ------------------------------------------
|
||||||
|
echo "==> linux/arm64"
|
||||||
|
CC=aarch64-linux-gnu-gcc \
|
||||||
|
CGO_ENABLED=1 GOOS=linux GOARCH=arm64 \
|
||||||
|
CGO_CFLAGS="--sysroot=/ -I/usr/include/aarch64-linux-gnu" \
|
||||||
|
CGO_LDFLAGS="--sysroot=/ -L/usr/lib/aarch64-linux-gnu" \
|
||||||
|
PKG_CONFIG_LIBDIR=/usr/lib/aarch64-linux-gnu/pkgconfig \
|
||||||
|
go build -buildvcs=false -trimpath -ldflags "$ldflags" \
|
||||||
|
-o "dist/linux/gosentry-${version}-linux-arm64" ./cmd/gosentry
|
||||||
|
|
||||||
|
# --- Windows amd64 (cross compiled with MinGW) -----------------------------
|
||||||
|
echo "==> windows/amd64"
|
||||||
|
# windres embeds the .ico into the PE resource so Explorer/taskbar show the icon.
|
||||||
|
# The .syso is suffixed windows_amd64, so Go only links it into the Windows build
|
||||||
|
# and ignores it for the Linux targets above.
|
||||||
|
x86_64-w64-mingw32-windres -O coff \
|
||||||
|
-o cmd/gosentry/rsrc_windows_amd64.syso packaging/windows/gosentry.rc
|
||||||
|
CC=x86_64-w64-mingw32-gcc \
|
||||||
|
CGO_ENABLED=1 GOOS=windows GOARCH=amd64 \
|
||||||
|
go build -buildvcs=false -trimpath -ldflags "-H=windowsgui ${ldflags}" \
|
||||||
|
-o "dist/windows/gosentry-${version}-windows-amd64.exe" ./cmd/gosentry
|
||||||
|
|
||||||
|
# --- Package ---------------------------------------------------------------
|
||||||
|
# Each archive holds the executable plus the top-level README and CHANGELOG,
|
||||||
|
# flattened to the archive root so a user can extract straight into any folder.
|
||||||
|
# This matches the layout produced by package-linux.sh / package-windows.bat.
|
||||||
|
package_linux() {
|
||||||
|
local arch="$1"
|
||||||
|
local binary="dist/linux/gosentry-${version}-linux-${arch}"
|
||||||
|
local tarball="dist/linux/gosentry-${version}-linux-${arch}.tar.gz"
|
||||||
|
local staging="dist/linux/_staging-${arch}"
|
||||||
|
|
||||||
|
rm -rf "$staging"
|
||||||
|
mkdir -p "$staging"
|
||||||
|
cp "$binary" "$staging/gosentry"
|
||||||
|
cp README.md "$staging/README.md"
|
||||||
|
cp docs/CHANGELOG.md "$staging/CHANGELOG.md"
|
||||||
|
tar -czf "$tarball" -C "$staging" .
|
||||||
|
rm -rf "$staging"
|
||||||
|
echo "Packaged $tarball"
|
||||||
|
}
|
||||||
|
|
||||||
|
package_windows() {
|
||||||
|
local binary="dist/windows/gosentry-${version}-windows-amd64.exe"
|
||||||
|
local zipfile="gosentry-${version}-windows-amd64.zip"
|
||||||
|
local staging="dist/windows/_staging-amd64"
|
||||||
|
|
||||||
|
rm -rf "$staging"
|
||||||
|
mkdir -p "$staging"
|
||||||
|
cp "$binary" "$staging/gosentry.exe"
|
||||||
|
cp README.md "$staging/README.md"
|
||||||
|
cp docs/CHANGELOG.md "$staging/CHANGELOG.md"
|
||||||
|
# -j flattens: files land at the zip root with no staging path prefix.
|
||||||
|
( cd "$staging" && zip -j -q "../${zipfile}" ./* )
|
||||||
|
rm -rf "$staging"
|
||||||
|
echo "Packaged dist/windows/${zipfile}"
|
||||||
|
}
|
||||||
|
|
||||||
|
package_linux amd64
|
||||||
|
package_linux arm64
|
||||||
|
package_windows
|
||||||
|
|
||||||
|
echo "Release artifacts:"
|
||||||
|
find dist/linux dist/windows -maxdepth 1 -type f \( -name '*.tar.gz' -o -name '*.zip' \) -print
|
||||||
@@ -41,6 +41,17 @@ type SchedulerStateChanged struct {
|
|||||||
Paused bool
|
Paused bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// JobsLoaded signals that the whole job list was replaced by the contents of a
|
||||||
|
// jobs file the user selected in Settings. It carries the path and job count
|
||||||
|
// because that is what the user needs to see confirmed — the switch happens
|
||||||
|
// without a prompt, and the previous list is no longer on screen to compare
|
||||||
|
// against. Observers that render jobs should re-read them through the Service;
|
||||||
|
// a broad JobChanged is emitted alongside for exactly that.
|
||||||
|
type JobsLoaded struct {
|
||||||
|
Path string
|
||||||
|
Count int
|
||||||
|
}
|
||||||
|
|
||||||
// ErrorOccurred signals a background error that could not be returned to a
|
// ErrorOccurred signals a background error that could not be returned to a
|
||||||
// caller — typically a failed save or cleanup after an async run. The UI
|
// caller — typically a failed save or cleanup after an async run. The UI
|
||||||
// surfaces it in the History tab so the user is not silently left with
|
// surfaces it in the History tab so the user is not silently left with
|
||||||
@@ -50,6 +61,7 @@ type ErrorOccurred struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (JobChanged) isEvent() {}
|
func (JobChanged) isEvent() {}
|
||||||
|
func (JobsLoaded) isEvent() {}
|
||||||
func (RunRecorded) isEvent() {}
|
func (RunRecorded) isEvent() {}
|
||||||
func (SchedulerStateChanged) isEvent() {}
|
func (SchedulerStateChanged) isEvent() {}
|
||||||
func (ErrorOccurred) isEvent() {}
|
func (ErrorOccurred) isEvent() {}
|
||||||
|
|||||||
@@ -102,6 +102,24 @@ func DisplayOverlapPolicy(job domain.Job, globalPolicy domain.OverlapPolicy) str
|
|||||||
return string(globalPolicy) + " (global default)"
|
return string(globalPolicy) + " (global default)"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DisplayTimeout formats a job's effective run timeout for the details panel.
|
||||||
|
// When the job sets its own TimeoutSeconds it is shown as-is, with an explicit 0
|
||||||
|
// rendered as "no timeout"; when unset (nil), the global default is shown with
|
||||||
|
// "(global default)" appended, mirroring DisplayOverlapPolicy. A non-positive
|
||||||
|
// global default means no timeout at all.
|
||||||
|
func DisplayTimeout(job domain.Job, globalDefault int) string {
|
||||||
|
if job.TimeoutSeconds != nil {
|
||||||
|
if *job.TimeoutSeconds <= 0 {
|
||||||
|
return "no timeout"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d s", *job.TimeoutSeconds)
|
||||||
|
}
|
||||||
|
if globalDefault <= 0 {
|
||||||
|
return "no timeout (global default)"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d s (global default)", globalDefault)
|
||||||
|
}
|
||||||
|
|
||||||
// DisplayIndex returns the position of jobIndex in the given slice of indexes,
|
// DisplayIndex returns the position of jobIndex in the given slice of indexes,
|
||||||
// or 0 if not found.
|
// or 0 if not found.
|
||||||
func DisplayIndex(indexes []int, jobIndex int) int {
|
func DisplayIndex(indexes []int, jobIndex int) int {
|
||||||
|
|||||||
@@ -151,3 +151,33 @@ func TestEventLine(t *testing.T) {
|
|||||||
t.Errorf("EventLine blank trigger = %q, want %q", got, want)
|
t.Errorf("EventLine blank trigger = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDisplayOverlapPolicy(t *testing.T) {
|
||||||
|
global := domain.OverlapPolicyQueue
|
||||||
|
jobOwn := domain.Job{OverlapPolicy: string(domain.OverlapPolicySkip)}
|
||||||
|
if got, want := DisplayOverlapPolicy(jobOwn, global), "skip"; got != want {
|
||||||
|
t.Errorf("per-job policy = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
inherit := domain.Job{OverlapPolicy: ""}
|
||||||
|
if got, want := DisplayOverlapPolicy(inherit, global), "queue (global default)"; got != want {
|
||||||
|
t.Errorf("inherited policy = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDisplayTimeout(t *testing.T) {
|
||||||
|
own := domain.Job{TimeoutSeconds: domain.TimeoutSecondsPtr(45)}
|
||||||
|
if got, want := DisplayTimeout(own, 30), "45 s"; got != want {
|
||||||
|
t.Errorf("per-job timeout = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
none := domain.Job{TimeoutSeconds: domain.TimeoutSecondsPtr(0)}
|
||||||
|
if got, want := DisplayTimeout(none, 30), "no timeout"; got != want {
|
||||||
|
t.Errorf("explicit per-job zero timeout = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
inherit := domain.Job{TimeoutSeconds: nil}
|
||||||
|
if got, want := DisplayTimeout(inherit, 30), "30 s (global default)"; got != want {
|
||||||
|
t.Errorf("inherited timeout = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := DisplayTimeout(inherit, 0), "no timeout (global default)"; got != want {
|
||||||
|
t.Errorf("inherited infinite timeout = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,11 +3,13 @@ package app
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
||||||
"gitea.mixdep.ru/mix/gosentry/src/runner"
|
"gitea.mixdep.ru/mix/gosentry/src/runner"
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/storage"
|
||||||
)
|
)
|
||||||
|
|
||||||
// maxJobLogs bounds the in-memory activity list kept per job. The full history
|
// maxJobLogs bounds the in-memory activity list kept per job. The full history
|
||||||
@@ -193,6 +195,27 @@ func (s *Service) SetGlobalPause(paused bool) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetJobListView persists the Jobs list density preference. Unlike
|
||||||
|
// SetGlobalPause this touches nothing but the config: no job changed, so there
|
||||||
|
// is no SaveJobs, and no event is emitted — the choice is presentational and the
|
||||||
|
// Jobs view refreshes its own list, whereas an event would trigger a pointless
|
||||||
|
// whole-window refresh. Anything that is not "compact" is stored as detailed so
|
||||||
|
// the file never gains an unrecognised value.
|
||||||
|
func (s *Service) SetJobListView(view domain.JobListView) error {
|
||||||
|
if !view.IsCompact() {
|
||||||
|
view = domain.JobListViewDetailed
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
if s.store.Config.JobListView == view {
|
||||||
|
s.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
s.store.Config.JobListView = view
|
||||||
|
err := s.store.SaveConfig()
|
||||||
|
s.mu.Unlock()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// ShouldNotifyOnFailure reports whether the user has enabled desktop
|
// ShouldNotifyOnFailure reports whether the user has enabled desktop
|
||||||
// notifications for failed job runs. It reads the config under mu so it is
|
// notifications for failed job runs. It reads the config under mu so it is
|
||||||
// safe to call from any goroutine.
|
// safe to call from any goroutine.
|
||||||
@@ -203,30 +226,71 @@ func (s *Service) ShouldNotifyOnFailure() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// UpdateSettings validates and persists a new application configuration. The
|
// UpdateSettings validates and persists a new application configuration. The
|
||||||
// loaded jobs are re-saved because the jobs directory may have changed, and log
|
// loaded jobs are re-saved because the jobs file may have changed, and log
|
||||||
// cleanup runs so a tightened retention policy takes effect immediately.
|
// cleanup runs so a tightened retention policy takes effect immediately.
|
||||||
|
//
|
||||||
|
// Pointing the config at a different jobs file that already exists adopts that
|
||||||
|
// file: its jobs replace the loaded ones, which is the only way the user can
|
||||||
|
// switch between job lists. A path with no file there yet receives the current
|
||||||
|
// jobs instead, which is how the jobs file is renamed or relocated. Adoption
|
||||||
|
// discards all runtime state, so it is refused while a job is running.
|
||||||
func (s *Service) UpdateSettings(config domain.Config) error {
|
func (s *Service) UpdateSettings(config domain.Config) error {
|
||||||
if err := validateConfig(config); err != nil {
|
if err := validateConfig(config); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
// The path is stored exactly as it is resolved, so a hand-typed value with
|
||||||
|
// stray spaces cannot make the saved setting and the file in use disagree.
|
||||||
|
config.JobsFile = strings.TrimSpace(config.JobsFile)
|
||||||
|
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
|
jobsPath := storage.ResolveConfiguredPath(s.store.Paths.AppDir, config.JobsFile)
|
||||||
|
switching := jobsPath != s.store.Paths.JobsPath
|
||||||
|
if switching && s.anyRunningLocked() {
|
||||||
|
s.mu.Unlock()
|
||||||
|
return errors.New("cannot change the jobs file while a job is running")
|
||||||
|
}
|
||||||
|
// Read the new file before anything is written, so a file that cannot be
|
||||||
|
// parsed leaves both the config and the current jobs untouched.
|
||||||
|
var adopted []domain.Job
|
||||||
|
if switching {
|
||||||
|
jobs, found, err := storage.LoadJobsFile(jobsPath)
|
||||||
|
if err != nil {
|
||||||
|
s.mu.Unlock()
|
||||||
|
return fmt.Errorf("read jobs file %s: %w", jobsPath, err)
|
||||||
|
}
|
||||||
|
if found {
|
||||||
|
adopted = jobs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
s.store.Config = config
|
s.store.Config = config
|
||||||
if err := s.store.SaveConfig(); err != nil {
|
if err := s.store.SaveConfig(); err != nil {
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if adopted != nil {
|
||||||
|
s.adoptJobsLocked(adopted)
|
||||||
|
}
|
||||||
// SaveConfig re-resolved the paths from the new config, so SaveJobs writes to
|
// SaveConfig re-resolved the paths from the new config, so SaveJobs writes to
|
||||||
// the (possibly new) jobs directory and cleanup targets the new logs dir.
|
// the (possibly new) jobs file and cleanup targets the new logs dir. Adopted
|
||||||
|
// jobs are written back too, which persists the IDs and defaults that
|
||||||
|
// normalization filled in, exactly as loading them at startup would.
|
||||||
if err := s.store.SaveJobs(s.jobs); err != nil {
|
if err := s.store.SaveJobs(s.jobs); err != nil {
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
loaded := len(s.jobs)
|
||||||
logsDir := s.store.Paths.LogsDir
|
logsDir := s.store.Paths.LogsDir
|
||||||
maxFiles := s.store.Config.MaxLogFiles
|
maxFiles := s.store.Config.MaxLogFiles
|
||||||
maxAge := s.store.Config.MaxLogAgeDays
|
maxAge := s.store.Config.MaxLogAgeDays
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if adopted != nil {
|
||||||
|
// A broad JobChanged redraws the job list; JobsLoaded tells the user in
|
||||||
|
// History which file those jobs came from, since nothing was asked.
|
||||||
|
s.emit(JobsLoaded{Path: jobsPath, Count: loaded})
|
||||||
|
s.emit(JobChanged{})
|
||||||
|
}
|
||||||
return runner.CleanupLogs(logsDir, maxFiles, maxAge)
|
return runner.CleanupLogs(logsDir, maxFiles, maxAge)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -367,13 +431,37 @@ func validateJob(job domain.Job) error {
|
|||||||
if policy != "" && policy != string(domain.OverlapPolicySkip) && policy != string(domain.OverlapPolicyQueue) {
|
if policy != "" && policy != string(domain.OverlapPolicySkip) && policy != string(domain.OverlapPolicyQueue) {
|
||||||
return errors.New("overlap policy must be 'skip', 'queue', or empty")
|
return errors.New("overlap policy must be 'skip', 'queue', or empty")
|
||||||
}
|
}
|
||||||
|
if job.TimeoutSeconds != nil && *job.TimeoutSeconds < 0 {
|
||||||
|
return errors.New("timeout must be zero (no timeout) or a positive number of seconds, or unset to inherit the global default")
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// hasFileName reports whether a path ends in something that can be a file name.
|
||||||
|
// It is a syntax check only — an existing directory whose name looks like a file
|
||||||
|
// name still passes, and fails at write time — but it catches the shapes a user
|
||||||
|
// types when they mean a folder: a trailing separator, "." and "..".
|
||||||
|
func hasFileName(path string) bool {
|
||||||
|
if strings.HasSuffix(path, "/") || strings.HasSuffix(path, string(filepath.Separator)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
switch filepath.Base(path) {
|
||||||
|
case ".", "..", string(filepath.Separator):
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// validateConfig rejects settings that would break persistence or cleanup.
|
// validateConfig rejects settings that would break persistence or cleanup.
|
||||||
func validateConfig(config domain.Config) error {
|
func validateConfig(config domain.Config) error {
|
||||||
if strings.TrimSpace(config.JobsDir) == "" {
|
jobsFile := strings.TrimSpace(config.JobsFile)
|
||||||
return errors.New("jobs directory is required")
|
if jobsFile == "" {
|
||||||
|
return errors.New("jobs file is required")
|
||||||
|
}
|
||||||
|
// A path that names only a folder would be written to as if it were a file
|
||||||
|
// and fail later with an opaque OS error, so require a file name here.
|
||||||
|
if !hasFileName(jobsFile) {
|
||||||
|
return errors.New("jobs file must include a file name")
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(config.LogsDir) == "" {
|
if strings.TrimSpace(config.LogsDir) == "" {
|
||||||
return errors.New("logs directory is required")
|
return errors.New("logs directory is required")
|
||||||
@@ -390,5 +478,13 @@ func validateConfig(config domain.Config) error {
|
|||||||
if config.OverlapPolicy != domain.OverlapPolicySkip && config.OverlapPolicy != domain.OverlapPolicyQueue {
|
if config.OverlapPolicy != domain.OverlapPolicySkip && config.OverlapPolicy != domain.OverlapPolicyQueue {
|
||||||
return errors.New("overlap policy must be 'skip' or 'queue'")
|
return errors.New("overlap policy must be 'skip' or 'queue'")
|
||||||
}
|
}
|
||||||
|
if config.DefaultTimeoutSeconds < 0 {
|
||||||
|
return errors.New("default timeout must not be negative (0 means no timeout)")
|
||||||
|
}
|
||||||
|
// Empty Theme is accepted and normalized to the default on load, so older
|
||||||
|
// configs (and hand-built ones) stay valid without an explicit theme.
|
||||||
|
if config.Theme != "" && config.Theme != domain.ThemeDefault && config.Theme != domain.ThemeGoSentry {
|
||||||
|
return errors.New("theme must be 'default' or 'gosentry'")
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ func newTempService(t *testing.T, jobs []domain.Job) *Service {
|
|||||||
JobsPath: filepath.Join(dir, "jobs.json"),
|
JobsPath: filepath.Join(dir, "jobs.json"),
|
||||||
LogsDir: filepath.Join(dir, "logs"),
|
LogsDir: filepath.Join(dir, "logs"),
|
||||||
},
|
},
|
||||||
Config: domain.Config{JobsDir: ".", LogsDir: "logs", MaxLogFiles: 100, MaxLogAgeDays: 30, ExecutionMode: domain.ExecutionModeParallel, OverlapPolicy: domain.OverlapPolicySkip},
|
Config: domain.Config{JobsFile: "jobs.json", LogsDir: "logs", MaxLogFiles: 100, MaxLogAgeDays: 30, ExecutionMode: domain.ExecutionModeParallel, OverlapPolicy: domain.OverlapPolicySkip, DefaultTimeoutSeconds: 30},
|
||||||
}
|
}
|
||||||
return NewService(store, jobs)
|
return NewService(store, jobs)
|
||||||
}
|
}
|
||||||
@@ -103,6 +103,13 @@ func TestCreateJobValidates(t *testing.T) {
|
|||||||
if _, err := svc.CreateJob(domain.Job{Name: "A", Schedule: "@every 1m", Command: "echo", OverlapPolicy: "invalid"}); err == nil {
|
if _, err := svc.CreateJob(domain.Job{Name: "A", Schedule: "@every 1m", Command: "echo", OverlapPolicy: "invalid"}); err == nil {
|
||||||
t.Error("expected error for invalid overlap policy")
|
t.Error("expected error for invalid overlap policy")
|
||||||
}
|
}
|
||||||
|
if _, err := svc.CreateJob(domain.Job{Name: "A", Schedule: "@every 1m", Command: "echo", TimeoutSeconds: domain.TimeoutSecondsPtr(-1)}); err == nil {
|
||||||
|
t.Error("expected error for negative per-job timeout")
|
||||||
|
}
|
||||||
|
// An explicit 0 is a valid choice ("no timeout"), not a rejected one.
|
||||||
|
if _, err := svc.CreateJob(domain.Job{Name: "Zero", Schedule: "@every 1m", Command: "echo", TimeoutSeconds: domain.TimeoutSecondsPtr(0)}); err != nil {
|
||||||
|
t.Errorf("explicit zero per-job timeout should be accepted: %v", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUpdateJobKeepsRuntimeAndReflectsDisable(t *testing.T) {
|
func TestUpdateJobKeepsRuntimeAndReflectsDisable(t *testing.T) {
|
||||||
@@ -250,7 +257,7 @@ func TestRunNowUsesRunnerAndRecords(t *testing.T) {
|
|||||||
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
||||||
|
|
||||||
done := make(chan domain.RunRecord, 1)
|
done := make(chan domain.RunRecord, 1)
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, trigger string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, trigger string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
if trigger != "Manual" {
|
if trigger != "Manual" {
|
||||||
t.Errorf("trigger = %q, want Manual", trigger)
|
t.Errorf("trigger = %q, want Manual", trigger)
|
||||||
}
|
}
|
||||||
@@ -298,7 +305,7 @@ func TestRunNowRefusedWhileAlreadyRunning(t *testing.T) {
|
|||||||
entered := make(chan struct{}, 1)
|
entered := make(chan struct{}, 1)
|
||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
var calls int32
|
var calls int32
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
atomic.AddInt32(&calls, 1)
|
atomic.AddInt32(&calls, 1)
|
||||||
entered <- struct{}{}
|
entered <- struct{}{}
|
||||||
<-release
|
<-release
|
||||||
@@ -341,7 +348,7 @@ func TestRunNowRefusedWhileAlreadyRunning(t *testing.T) {
|
|||||||
func TestRunNowAllowedWhilePaused(t *testing.T) {
|
func TestRunNowAllowedWhilePaused(t *testing.T) {
|
||||||
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
||||||
done := make(chan struct{}, 1)
|
done := make(chan struct{}, 1)
|
||||||
svc.runJob = func(context.Context, *domain.Job, string, string) (domain.RunRecord, error) {
|
svc.runJob = func(context.Context, *domain.Job, string, string, time.Duration) (domain.RunRecord, error) {
|
||||||
select {
|
select {
|
||||||
case done <- struct{}{}:
|
case done <- struct{}{}:
|
||||||
default:
|
default:
|
||||||
@@ -366,7 +373,7 @@ func TestRunDueStartsDueJob(t *testing.T) {
|
|||||||
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
||||||
|
|
||||||
done := make(chan domain.RunRecord, 1)
|
done := make(chan domain.RunRecord, 1)
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, trigger string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, trigger string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
if trigger != "Schedule" {
|
if trigger != "Schedule" {
|
||||||
t.Errorf("trigger = %q, want Schedule", trigger)
|
t.Errorf("trigger = %q, want Schedule", trigger)
|
||||||
}
|
}
|
||||||
@@ -397,7 +404,7 @@ func TestRunDueStartsDueJob(t *testing.T) {
|
|||||||
func TestRunDueSkipsJobNotYetDue(t *testing.T) {
|
func TestRunDueSkipsJobNotYetDue(t *testing.T) {
|
||||||
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
||||||
var ran int32
|
var ran int32
|
||||||
svc.runJob = func(context.Context, *domain.Job, string, string) (domain.RunRecord, error) {
|
svc.runJob = func(context.Context, *domain.Job, string, string, time.Duration) (domain.RunRecord, error) {
|
||||||
atomic.AddInt32(&ran, 1)
|
atomic.AddInt32(&ran, 1)
|
||||||
return domain.RunRecord{}, nil
|
return domain.RunRecord{}, nil
|
||||||
}
|
}
|
||||||
@@ -418,7 +425,7 @@ func TestRunDueSkipsJobInRunningState(t *testing.T) {
|
|||||||
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
||||||
|
|
||||||
var calls int32
|
var calls int32
|
||||||
svc.runJob = func(context.Context, *domain.Job, string, string) (domain.RunRecord, error) {
|
svc.runJob = func(context.Context, *domain.Job, string, string, time.Duration) (domain.RunRecord, error) {
|
||||||
atomic.AddInt32(&calls, 1)
|
atomic.AddInt32(&calls, 1)
|
||||||
return domain.RunRecord{State: "Success"}, nil
|
return domain.RunRecord{State: "Success"}, nil
|
||||||
}
|
}
|
||||||
@@ -442,7 +449,7 @@ func TestRunDueSkipsJobInRunningState(t *testing.T) {
|
|||||||
func TestRunDueDoesNothingWhilePaused(t *testing.T) {
|
func TestRunDueDoesNothingWhilePaused(t *testing.T) {
|
||||||
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
||||||
var ran int32
|
var ran int32
|
||||||
svc.runJob = func(context.Context, *domain.Job, string, string) (domain.RunRecord, error) {
|
svc.runJob = func(context.Context, *domain.Job, string, string, time.Duration) (domain.RunRecord, error) {
|
||||||
atomic.AddInt32(&ran, 1)
|
atomic.AddInt32(&ran, 1)
|
||||||
return domain.RunRecord{}, nil
|
return domain.RunRecord{}, nil
|
||||||
}
|
}
|
||||||
@@ -472,7 +479,7 @@ func TestStartDrivesRunDueOnTick(t *testing.T) {
|
|||||||
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}})
|
||||||
|
|
||||||
done := make(chan struct{}, 1)
|
done := make(chan struct{}, 1)
|
||||||
svc.runJob = func(context.Context, *domain.Job, string, string) (domain.RunRecord, error) {
|
svc.runJob = func(context.Context, *domain.Job, string, string, time.Duration) (domain.RunRecord, error) {
|
||||||
select {
|
select {
|
||||||
case done <- struct{}{}:
|
case done <- struct{}{}:
|
||||||
default:
|
default:
|
||||||
@@ -520,10 +527,12 @@ func TestUpdateSettingsRejectsInvalidConfigs(t *testing.T) {
|
|||||||
name string
|
name string
|
||||||
mutate func(c *domain.Config)
|
mutate func(c *domain.Config)
|
||||||
}{
|
}{
|
||||||
{"missing jobs dir", func(c *domain.Config) { c.JobsDir = " " }},
|
{"missing jobs file", func(c *domain.Config) { c.JobsFile = " " }},
|
||||||
|
{"jobs file without a file name", func(c *domain.Config) { c.JobsFile = "jobs" + string(filepath.Separator) }},
|
||||||
{"missing logs dir", func(c *domain.Config) { c.LogsDir = "" }},
|
{"missing logs dir", func(c *domain.Config) { c.LogsDir = "" }},
|
||||||
{"non-positive max files", func(c *domain.Config) { c.MaxLogFiles = 0 }},
|
{"non-positive max files", func(c *domain.Config) { c.MaxLogFiles = 0 }},
|
||||||
{"non-positive max age", func(c *domain.Config) { c.MaxLogAgeDays = -1 }},
|
{"non-positive max age", func(c *domain.Config) { c.MaxLogAgeDays = -1 }},
|
||||||
|
{"negative default timeout", func(c *domain.Config) { c.DefaultTimeoutSeconds = -1 }},
|
||||||
}
|
}
|
||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
@@ -536,6 +545,169 @@ func TestUpdateSettingsRejectsInvalidConfigs(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHasFileName(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
path string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"jobs.json", true},
|
||||||
|
{filepath.Join("data", "team.json"), true},
|
||||||
|
{"jobs" + string(filepath.Separator), false},
|
||||||
|
{"data/", false},
|
||||||
|
{".", false},
|
||||||
|
{"..", false},
|
||||||
|
{string(filepath.Separator), false},
|
||||||
|
}
|
||||||
|
for _, tc := range tests {
|
||||||
|
if got := hasFileName(tc.path); got != tc.want {
|
||||||
|
t.Errorf("hasFileName(%q) = %v, want %v", tc.path, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Renaming or relocating the jobs file writes the loaded jobs to the new path,
|
||||||
|
// which is what makes the Settings change take effect without a restart.
|
||||||
|
func TestUpdateSettingsWritesJobsToTheNewFile(t *testing.T) {
|
||||||
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "Kept", Schedule: "@every 1m", Command: "echo hi", Enabled: true}})
|
||||||
|
|
||||||
|
config := svc.store.Config
|
||||||
|
config.JobsFile = filepath.Join("data", "team-jobs.json")
|
||||||
|
if err := svc.UpdateSettings(config); err != nil {
|
||||||
|
t.Fatalf("UpdateSettings: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
moved := filepath.Join(svc.store.Paths.AppDir, "data", "team-jobs.json")
|
||||||
|
if svc.store.Paths.JobsPath != moved {
|
||||||
|
t.Errorf("JobsPath: got %q, want %q", svc.store.Paths.JobsPath, moved)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(moved)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read moved jobs file: %v", err)
|
||||||
|
}
|
||||||
|
var file domain.JobsFile
|
||||||
|
if err := json.Unmarshal(data, &file); err != nil {
|
||||||
|
t.Fatalf("unmarshal moved jobs file: %v", err)
|
||||||
|
}
|
||||||
|
if len(file.Jobs) != 1 || file.Jobs[0].Name != "Kept" {
|
||||||
|
t.Errorf("moved jobs file: got %+v, want the single 'Kept' job", file.Jobs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pointing Settings at a jobs file that already exists must adopt that file:
|
||||||
|
// its jobs replace the loaded ones instead of being overwritten by them. This is
|
||||||
|
// the only way the user can switch between job lists, so the file's contents
|
||||||
|
// win, the job list is rebuilt around them, and History is told where they came
|
||||||
|
// from.
|
||||||
|
func TestUpdateSettingsAdoptsExistingJobsFile(t *testing.T) {
|
||||||
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "Local", Schedule: "@every 1m", Command: "echo local", Enabled: true}})
|
||||||
|
rec := &recorder{}
|
||||||
|
svc.Subscribe(rec)
|
||||||
|
|
||||||
|
shared := filepath.Join(svc.store.Paths.AppDir, "shared.json")
|
||||||
|
existing := domain.JobsFile{Jobs: []domain.Job{
|
||||||
|
{ID: 4, Name: "Adopted", Schedule: "@every 5m", Command: "echo adopted", Enabled: true},
|
||||||
|
{Name: "Needs an ID", Schedule: "@every 9m", Command: "echo second", Enabled: false},
|
||||||
|
}}
|
||||||
|
data, err := json.Marshal(existing)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(shared, data, 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
config := svc.store.Config
|
||||||
|
config.JobsFile = shared
|
||||||
|
if err := svc.UpdateSettings(config); err != nil {
|
||||||
|
t.Fatalf("UpdateSettings: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
jobs := svc.Jobs()
|
||||||
|
if len(jobs) != 2 || jobs[0].Name != "Adopted" {
|
||||||
|
t.Fatalf("jobs after adoption: got %+v, want the two jobs from the selected file", jobs)
|
||||||
|
}
|
||||||
|
// The adopted jobs must be fully live, not just listed: runtime and parsed
|
||||||
|
// schedule are rebuilt for the IDs the file brought (including the one
|
||||||
|
// normalization had to assign).
|
||||||
|
for _, job := range jobs {
|
||||||
|
if svc.Runtime(job.ID) == nil {
|
||||||
|
t.Errorf("job %d (%q) has no runtime after adoption", job.ID, job.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if svc.Runtime(1) != nil {
|
||||||
|
t.Error("runtime of the replaced job should be gone")
|
||||||
|
}
|
||||||
|
|
||||||
|
var loaded []JobsLoaded
|
||||||
|
for _, e := range rec.events {
|
||||||
|
if jl, ok := e.(JobsLoaded); ok {
|
||||||
|
loaded = append(loaded, jl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(loaded) != 1 || loaded[0].Path != shared || loaded[0].Count != 2 {
|
||||||
|
t.Errorf("JobsLoaded events: got %+v, want one for %q with 2 jobs", loaded, shared)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A path with no file behind it is the "rename or relocate" case: the current
|
||||||
|
// jobs are written there rather than an empty list being adopted.
|
||||||
|
func TestUpdateSettingsKeepsJobsWhenTheNewFileIsMissing(t *testing.T) {
|
||||||
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "Local", Schedule: "@every 1m", Command: "echo local", Enabled: true}})
|
||||||
|
|
||||||
|
config := svc.store.Config
|
||||||
|
config.JobsFile = filepath.Join("moved", "jobs.json")
|
||||||
|
if err := svc.UpdateSettings(config); err != nil {
|
||||||
|
t.Fatalf("UpdateSettings: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
jobs := svc.Jobs()
|
||||||
|
if len(jobs) != 1 || jobs[0].Name != "Local" {
|
||||||
|
t.Fatalf("jobs after the move: got %+v, want the original job", jobs)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(svc.store.Paths.AppDir, "moved", "jobs.json")); err != nil {
|
||||||
|
t.Errorf("jobs should have been written to the new path: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adoption throws away every runtime, including the state of a run in flight,
|
||||||
|
// and a finishing run would then write its result onto whichever job inherited
|
||||||
|
// its ID. Refusing the switch is what keeps that from happening.
|
||||||
|
func TestUpdateSettingsRefusesJobsFileSwitchWhileRunning(t *testing.T) {
|
||||||
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "Long", Schedule: "@every 1h", Command: "echo long", Enabled: true}})
|
||||||
|
entered := make(chan int, 1)
|
||||||
|
release := make(chan struct{})
|
||||||
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
|
entered <- job.ID
|
||||||
|
<-release
|
||||||
|
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "Success"}, nil
|
||||||
|
}
|
||||||
|
done := completions(svc)
|
||||||
|
|
||||||
|
if err := svc.RunNow(1); err != nil {
|
||||||
|
t.Fatalf("RunNow: %v", err)
|
||||||
|
}
|
||||||
|
<-entered
|
||||||
|
|
||||||
|
config := svc.store.Config
|
||||||
|
config.JobsFile = filepath.Join("elsewhere", "jobs.json")
|
||||||
|
if err := svc.UpdateSettings(config); err == nil {
|
||||||
|
t.Error("expected the jobs-file switch to be refused while a job is running")
|
||||||
|
}
|
||||||
|
if svc.Store().Config.JobsFile == config.JobsFile {
|
||||||
|
t.Error("the refused switch must not have been persisted")
|
||||||
|
}
|
||||||
|
|
||||||
|
// A setting that does not touch the jobs file still saves during a run.
|
||||||
|
unrelated := svc.Store().Config
|
||||||
|
unrelated.NotifyOnFailure = !unrelated.NotifyOnFailure
|
||||||
|
if err := svc.UpdateSettings(unrelated); err != nil {
|
||||||
|
t.Errorf("unrelated setting should still save during a run: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
close(release)
|
||||||
|
waitRecord(t, done)
|
||||||
|
}
|
||||||
|
|
||||||
func TestPrependLogCapsActivityList(t *testing.T) {
|
func TestPrependLogCapsActivityList(t *testing.T) {
|
||||||
runtime := &domain.JobRuntime{}
|
runtime := &domain.JobRuntime{}
|
||||||
for i := 0; i < maxJobLogs+10; i++ {
|
for i := 0; i < maxJobLogs+10; i++ {
|
||||||
@@ -582,6 +754,63 @@ func TestSetGlobalPausePersistsToConfigFile(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSetJobListViewPersistsToConfigFile(t *testing.T) {
|
||||||
|
svc := newTempService(t, nil)
|
||||||
|
|
||||||
|
readConfig := func(stage string) domain.Config {
|
||||||
|
t.Helper()
|
||||||
|
data, err := os.ReadFile(svc.store.Paths.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading config file %s: %v", stage, err)
|
||||||
|
}
|
||||||
|
var cfg domain.Config
|
||||||
|
if err := json.Unmarshal(data, &cfg); err != nil {
|
||||||
|
t.Fatalf("unmarshalling config %s: %v", stage, err)
|
||||||
|
}
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := svc.SetJobListView(domain.JobListViewCompact); err != nil {
|
||||||
|
t.Fatalf("SetJobListView(compact): %v", err)
|
||||||
|
}
|
||||||
|
if got := readConfig("after compact").JobListView; got != domain.JobListViewCompact {
|
||||||
|
t.Errorf("persisted JobListView = %q, want %q", got, domain.JobListViewCompact)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := svc.SetJobListView(domain.JobListViewDetailed); err != nil {
|
||||||
|
t.Fatalf("SetJobListView(detailed): %v", err)
|
||||||
|
}
|
||||||
|
if got := readConfig("after detailed").JobListView; got != domain.JobListViewDetailed {
|
||||||
|
t.Errorf("persisted JobListView = %q, want %q", got, domain.JobListViewDetailed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSetJobListViewNormalizesUnknownValue guards the config file against
|
||||||
|
// gaining a value no reader understands: anything but "compact" is stored as
|
||||||
|
// "detailed".
|
||||||
|
func TestSetJobListViewNormalizesUnknownValue(t *testing.T) {
|
||||||
|
svc := newTempService(t, nil)
|
||||||
|
|
||||||
|
if err := svc.SetJobListView(domain.JobListViewCompact); err != nil {
|
||||||
|
t.Fatalf("SetJobListView(compact): %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.SetJobListView("tiny"); err != nil {
|
||||||
|
t.Fatalf("SetJobListView(tiny): %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := os.ReadFile(svc.store.Paths.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading config file: %v", err)
|
||||||
|
}
|
||||||
|
var cfg domain.Config
|
||||||
|
if err := json.Unmarshal(data, &cfg); err != nil {
|
||||||
|
t.Fatalf("unmarshalling config: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.JobListView != domain.JobListViewDetailed {
|
||||||
|
t.Errorf("persisted JobListView = %q, want %q", cfg.JobListView, domain.JobListViewDetailed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestServiceRebuiltFromPausedStoreStartsPaused(t *testing.T) {
|
func TestServiceRebuiltFromPausedStoreStartsPaused(t *testing.T) {
|
||||||
jobs := []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}}
|
jobs := []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1m", Command: "echo", Enabled: true}}
|
||||||
svc := newTempService(t, jobs)
|
svc := newTempService(t, jobs)
|
||||||
@@ -596,7 +825,7 @@ func TestServiceRebuiltFromPausedStoreStartsPaused(t *testing.T) {
|
|||||||
|
|
||||||
var ran int32
|
var ran int32
|
||||||
runStarted := make(chan struct{}, 1)
|
runStarted := make(chan struct{}, 1)
|
||||||
svc2.runJob = func(context.Context, *domain.Job, string, string) (domain.RunRecord, error) {
|
svc2.runJob = func(context.Context, *domain.Job, string, string, time.Duration) (domain.RunRecord, error) {
|
||||||
atomic.AddInt32(&ran, 1)
|
atomic.AddInt32(&ran, 1)
|
||||||
select {
|
select {
|
||||||
case runStarted <- struct{}{}:
|
case runStarted <- struct{}{}:
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ type runEnv struct {
|
|||||||
logsDir string
|
logsDir string
|
||||||
maxFiles int
|
maxFiles int
|
||||||
maxAge int
|
maxAge int
|
||||||
|
timeout time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
// startRunLocked transitions a job to "Running", advances its NextDue to the next
|
// startRunLocked transitions a job to "Running", advances its NextDue to the next
|
||||||
@@ -142,6 +143,7 @@ func (s *Service) startRunLocked(job *domain.Job, runtime *domain.JobRuntime, tr
|
|||||||
logsDir: s.store.Paths.LogsDir,
|
logsDir: s.store.Paths.LogsDir,
|
||||||
maxFiles: s.store.Config.MaxLogFiles,
|
maxFiles: s.store.Config.MaxLogFiles,
|
||||||
maxAge: s.store.Config.MaxLogAgeDays,
|
maxAge: s.store.Config.MaxLogAgeDays,
|
||||||
|
timeout: s.effectiveTimeout(job),
|
||||||
}
|
}
|
||||||
// Capture ctx under the lock so a concurrent Start/Stop cannot swap it out
|
// Capture ctx under the lock so a concurrent Start/Stop cannot swap it out
|
||||||
// from under the goroutine after we release mu.
|
// from under the goroutine after we release mu.
|
||||||
@@ -155,7 +157,7 @@ func (s *Service) startRunLocked(job *domain.Job, runtime *domain.JobRuntime, tr
|
|||||||
// is not paused, deferred runs are started one at a time until PendingRuns reaches
|
// is not paused, deferred runs are started one at a time until PendingRuns reaches
|
||||||
// zero. Each deferred run runs on its own goroutine.
|
// zero. Each deferred run runs on its own goroutine.
|
||||||
func (s *Service) executeRun(ctx context.Context, jobCopy domain.Job, trigger string, env runEnv) {
|
func (s *Service) executeRun(ctx context.Context, jobCopy domain.Job, trigger string, env runEnv) {
|
||||||
record, logErr := s.runJob(ctx, &jobCopy, trigger, env.logsDir)
|
record, logErr := s.runJob(ctx, &jobCopy, trigger, env.logsDir, env.timeout)
|
||||||
|
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
var cleanupErr, saveErr error
|
var cleanupErr, saveErr error
|
||||||
@@ -208,6 +210,21 @@ func (s *Service) effectiveOverlapPolicy(job *domain.Job) domain.OverlapPolicy {
|
|||||||
return s.store.Config.OverlapPolicy
|
return s.store.Config.OverlapPolicy
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// effectiveTimeout resolves the run timeout that actually governs a job: the
|
||||||
|
// job's own TimeoutSeconds whenever it is set — including an explicit 0, which
|
||||||
|
// means "no timeout" and deliberately does not inherit — otherwise the global
|
||||||
|
// Config.DefaultTimeoutSeconds. A nil Job.TimeoutSeconds means "inherit the
|
||||||
|
// global default", which is why normalizeJob leaves it nil rather than
|
||||||
|
// backfilling the configured value. A resolved duration of 0 means no timeout;
|
||||||
|
// runner.RunJob treats it as "run without a deadline". The caller must hold mu.
|
||||||
|
func (s *Service) effectiveTimeout(job *domain.Job) time.Duration {
|
||||||
|
secs := s.store.Config.DefaultTimeoutSeconds
|
||||||
|
if job.TimeoutSeconds != nil {
|
||||||
|
secs = *job.TimeoutSeconds
|
||||||
|
}
|
||||||
|
return time.Duration(secs) * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
// anyRunningLocked reports whether any loaded job is currently in the "Running"
|
// anyRunningLocked reports whether any loaded job is currently in the "Running"
|
||||||
// state. It backs the sequential-mode guards in RunNow and RunDue. The caller
|
// state. It backs the sequential-mode guards in RunNow and RunDue. The caller
|
||||||
// must hold mu.
|
// must hold mu.
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package app
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"os"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -134,7 +135,7 @@ func TestRunDueParallelStartsAllDueJobs(t *testing.T) {
|
|||||||
|
|
||||||
entered := make(chan int, 2)
|
entered := make(chan int, 2)
|
||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
entered <- job.ID
|
entered <- job.ID
|
||||||
<-release
|
<-release
|
||||||
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "Success"}, nil
|
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "Success"}, nil
|
||||||
@@ -175,7 +176,7 @@ func TestRunDueSequentialSerializes(t *testing.T) {
|
|||||||
|
|
||||||
entered := make(chan int, 2)
|
entered := make(chan int, 2)
|
||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
entered <- job.ID
|
entered <- job.ID
|
||||||
<-release
|
<-release
|
||||||
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "Success"}, nil
|
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "Success"}, nil
|
||||||
@@ -212,7 +213,7 @@ func TestRunDueSkipDropsOverlap(t *testing.T) {
|
|||||||
entered := make(chan int, 2)
|
entered := make(chan int, 2)
|
||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
var calls int32
|
var calls int32
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
atomic.AddInt32(&calls, 1)
|
atomic.AddInt32(&calls, 1)
|
||||||
entered <- job.ID
|
entered <- job.ID
|
||||||
<-release
|
<-release
|
||||||
@@ -258,7 +259,7 @@ func TestRunDueQueueRerunsAfterFinish(t *testing.T) {
|
|||||||
entered := make(chan int, 2)
|
entered := make(chan int, 2)
|
||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
var calls int32
|
var calls int32
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
atomic.AddInt32(&calls, 1)
|
atomic.AddInt32(&calls, 1)
|
||||||
entered <- job.ID
|
entered <- job.ID
|
||||||
<-release
|
<-release
|
||||||
@@ -313,7 +314,7 @@ func TestRunDueQueueDrainsMultipleOverlaps(t *testing.T) {
|
|||||||
|
|
||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
var calls int32
|
var calls int32
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
if atomic.LoadInt32(&calls) == 0 {
|
if atomic.LoadInt32(&calls) == 0 {
|
||||||
<-release
|
<-release
|
||||||
}
|
}
|
||||||
@@ -365,7 +366,7 @@ func TestRunDuePerJobQueueOverridesGlobalSkip(t *testing.T) {
|
|||||||
entered := make(chan int, 2)
|
entered := make(chan int, 2)
|
||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
var calls int32
|
var calls int32
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
atomic.AddInt32(&calls, 1)
|
atomic.AddInt32(&calls, 1)
|
||||||
entered <- job.ID
|
entered <- job.ID
|
||||||
<-release
|
<-release
|
||||||
@@ -415,7 +416,7 @@ func TestRunDuePerJobSkipOverridesGlobalQueue(t *testing.T) {
|
|||||||
entered := make(chan int, 2)
|
entered := make(chan int, 2)
|
||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
var calls int32
|
var calls int32
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
atomic.AddInt32(&calls, 1)
|
atomic.AddInt32(&calls, 1)
|
||||||
entered <- job.ID
|
entered <- job.ID
|
||||||
<-release
|
<-release
|
||||||
@@ -463,7 +464,7 @@ func TestRunDueEmptyOverlapInheritsGlobal(t *testing.T) {
|
|||||||
|
|
||||||
entered := make(chan int, 2)
|
entered := make(chan int, 2)
|
||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
entered <- job.ID
|
entered <- job.ID
|
||||||
<-release
|
<-release
|
||||||
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "Success"}, nil
|
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "Success"}, nil
|
||||||
@@ -505,7 +506,7 @@ func TestRunNowSequentialGuard(t *testing.T) {
|
|||||||
|
|
||||||
entered := make(chan int, 2)
|
entered := make(chan int, 2)
|
||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string) (domain.RunRecord, error) {
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
entered <- job.ID
|
entered <- job.ID
|
||||||
<-release
|
<-release
|
||||||
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "Success"}, nil
|
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "Success"}, nil
|
||||||
@@ -532,3 +533,116 @@ func TestRunNowSequentialGuard(t *testing.T) {
|
|||||||
}
|
}
|
||||||
waitRecord(t, done)
|
waitRecord(t, done)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestStartRunLockedRollbackOnSaveFailure is a regression test for CODE_REVIEW
|
||||||
|
// finding #2: a run must not start when persisting the Running state fails.
|
||||||
|
func TestStartRunLockedRollbackOnSaveFailure(t *testing.T) {
|
||||||
|
svc := newTempService(t, []domain.Job{{ID: 1, Name: "A", Schedule: "@every 1h", Command: "echo", Enabled: true}})
|
||||||
|
if err := svc.store.SaveJobs(svc.jobs); err != nil {
|
||||||
|
t.Fatalf("seed jobs.json: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.Chmod(svc.store.Paths.JobsPath, 0o444); err != nil {
|
||||||
|
t.Fatalf("chmod jobs.json: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = os.Chmod(svc.store.Paths.JobsPath, 0o644) })
|
||||||
|
|
||||||
|
var started int32
|
||||||
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
|
atomic.AddInt32(&started, 1)
|
||||||
|
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "OK"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := svc.RunNow(1); err == nil {
|
||||||
|
t.Fatal("expected RunNow to fail when jobs.json is not writable")
|
||||||
|
}
|
||||||
|
if atomic.LoadInt32(&started) != 0 {
|
||||||
|
t.Error("run goroutine must not start when SaveJobs fails")
|
||||||
|
}
|
||||||
|
if rt := svc.Runtime(1); rt == nil || rt.LastState == "Running" {
|
||||||
|
t.Errorf("runtime should roll back from Running, got %+v", rt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRunDueQueueDrainSkippedWhenPaused verifies that queued overlap runs are not
|
||||||
|
// drained while the scheduler is globally paused.
|
||||||
|
func TestRunDueQueueDrainSkippedWhenPaused(t *testing.T) {
|
||||||
|
svc := newQueueService(t, domain.ExecutionModeParallel, domain.OverlapPolicyQueue, []domain.Job{
|
||||||
|
{ID: 1, Name: "A", Schedule: "@every 1h", Command: "echo", Enabled: true},
|
||||||
|
})
|
||||||
|
|
||||||
|
entered := make(chan int, 2)
|
||||||
|
release := make(chan struct{})
|
||||||
|
var calls int32
|
||||||
|
svc.runJob = func(_ context.Context, job *domain.Job, _ string, _ string, _ time.Duration) (domain.RunRecord, error) {
|
||||||
|
atomic.AddInt32(&calls, 1)
|
||||||
|
entered <- job.ID
|
||||||
|
<-release
|
||||||
|
return domain.RunRecord{Time: "t", JobID: job.ID, JobName: job.Name, State: "OK"}, nil
|
||||||
|
}
|
||||||
|
done := completions(svc)
|
||||||
|
|
||||||
|
primeDue(t, svc, 1)
|
||||||
|
svc.RunDue(time.Now())
|
||||||
|
if id := <-entered; id != 1 {
|
||||||
|
t.Fatalf("started job = %d, want 1", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
primeDue(t, svc, 1)
|
||||||
|
svc.RunDue(time.Now())
|
||||||
|
expectNoEntry(t, entered)
|
||||||
|
|
||||||
|
svc.mu.Lock()
|
||||||
|
pending := svc.runtimes[1].PendingRuns
|
||||||
|
svc.mu.Unlock()
|
||||||
|
if pending != 1 {
|
||||||
|
t.Fatalf("expected one queued overlap, PendingRuns = %d", pending)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := svc.SetGlobalPause(true); err != nil {
|
||||||
|
t.Fatalf("SetGlobalPause: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
close(release)
|
||||||
|
waitRecord(t, done)
|
||||||
|
expectNoEntry(t, entered)
|
||||||
|
|
||||||
|
svc.mu.Lock()
|
||||||
|
pending = svc.runtimes[1].PendingRuns
|
||||||
|
svc.mu.Unlock()
|
||||||
|
if pending != 1 {
|
||||||
|
t.Errorf("paused scheduler must not drain queue, PendingRuns = %d, want 1", pending)
|
||||||
|
}
|
||||||
|
if got := atomic.LoadInt32(&calls); got != 1 {
|
||||||
|
t.Errorf("runner called %d time(s), want 1", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEffectiveTimeout verifies the three-state resolution: an unset (nil)
|
||||||
|
// Job.TimeoutSeconds falls back to the global default, a positive value
|
||||||
|
// overrides it, and an explicit 0 means "no timeout" without inheriting.
|
||||||
|
func TestEffectiveTimeout(t *testing.T) {
|
||||||
|
svc := newTempService(t, nil)
|
||||||
|
svc.store.Config.DefaultTimeoutSeconds = 30
|
||||||
|
|
||||||
|
inherit := &domain.Job{TimeoutSeconds: nil}
|
||||||
|
if got, want := svc.effectiveTimeout(inherit), 30*time.Second; got != want {
|
||||||
|
t.Errorf("inherited timeout = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
own := &domain.Job{TimeoutSeconds: domain.TimeoutSecondsPtr(5)}
|
||||||
|
if got, want := svc.effectiveTimeout(own), 5*time.Second; got != want {
|
||||||
|
t.Errorf("per-job timeout = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An explicit per-job 0 must beat a positive global default rather than be
|
||||||
|
// mistaken for "unset".
|
||||||
|
none := &domain.Job{TimeoutSeconds: domain.TimeoutSecondsPtr(0)}
|
||||||
|
if got, want := svc.effectiveTimeout(none), time.Duration(0); got != want {
|
||||||
|
t.Errorf("explicit per-job zero timeout = %s, want %s (no timeout)", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
svc.store.Config.DefaultTimeoutSeconds = 0
|
||||||
|
if got, want := svc.effectiveTimeout(inherit), time.Duration(0); got != want {
|
||||||
|
t.Errorf("inherited timeout with no global default = %s, want %s (no timeout)", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ type Service struct {
|
|||||||
// processes. ctx is the lifecycle context passed to runs; Start replaces it
|
// processes. ctx is the lifecycle context passed to runs; Start replaces it
|
||||||
// with a cancelable context so Stop can abort in-flight runs, and until Start
|
// with a cancelable context so Stop can abort in-flight runs, and until Start
|
||||||
// it is context.Background().
|
// it is context.Background().
|
||||||
runJob func(ctx context.Context, job *domain.Job, trigger string, logsDir string) (domain.RunRecord, error)
|
runJob func(ctx context.Context, job *domain.Job, trigger string, logsDir string, timeout time.Duration) (domain.RunRecord, error)
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
|
|
||||||
// sched is the timing loop installed by Start; cancel tears down ctx on Stop.
|
// sched is the timing loop installed by Start; cancel tears down ctx on Stop.
|
||||||
@@ -70,27 +70,37 @@ type Service struct {
|
|||||||
func NewService(store *storage.Store, jobs []domain.Job) *Service {
|
func NewService(store *storage.Store, jobs []domain.Job) *Service {
|
||||||
s := &Service{
|
s := &Service{
|
||||||
store: store,
|
store: store,
|
||||||
jobs: jobs,
|
|
||||||
runtimes: domain.NewRuntimes(jobs),
|
|
||||||
schedules: make(map[int]domain.Schedule, len(jobs)),
|
|
||||||
runJob: runner.RunJob,
|
runJob: runner.RunJob,
|
||||||
ctx: context.Background(),
|
ctx: context.Background(),
|
||||||
paused: store.Config.Paused,
|
paused: store.Config.Paused,
|
||||||
}
|
}
|
||||||
// Parse every schedule once, then compute each job's first next-run so the
|
// No lock is needed here: construction is single-threaded, before Start
|
||||||
// Service is ready to schedule the moment it exists — mirroring the old
|
// launches the timing loop.
|
||||||
// scheduler's reset-on-construction. No lock is needed: construction is
|
s.adoptJobsLocked(jobs)
|
||||||
// single-threaded, before Start launches the timing loop.
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// adoptJobsLocked makes jobs the Service's durable state and rebuilds everything
|
||||||
|
// derived from it: the runtime map, the parsed-schedule cache, each job's first
|
||||||
|
// next-run — so the Service is ready to schedule the moment it exists, mirroring
|
||||||
|
// the old scheduler's reset-on-construction — and the statistics seeded from
|
||||||
|
// existing log files, so the details panel shows accumulated run history
|
||||||
|
// immediately rather than only runs since this process started.
|
||||||
|
//
|
||||||
|
// It backs both construction and a Settings change that points at a different
|
||||||
|
// jobs file. The caller must hold mu.
|
||||||
|
func (s *Service) adoptJobsLocked(jobs []domain.Job) {
|
||||||
|
s.jobs = jobs
|
||||||
|
s.runtimes = domain.NewRuntimes(jobs)
|
||||||
|
s.schedules = make(map[int]domain.Schedule, len(jobs))
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
for index := range s.jobs {
|
for index := range s.jobs {
|
||||||
job := &s.jobs[index]
|
job := &s.jobs[index]
|
||||||
s.parseScheduleLocked(job)
|
s.parseScheduleLocked(job)
|
||||||
s.refreshNextRunFromLocked(job, s.runtimes[job.ID], now)
|
s.refreshNextRunFromLocked(job, s.runtimes[job.ID], now)
|
||||||
}
|
}
|
||||||
// Seed execution-time statistics from existing log files so the details panel
|
for id, seed := range runner.SeedStats(s.store.Paths.LogsDir, s.jobs, s.store.Config.MaxLogFiles) {
|
||||||
// shows accumulated run history immediately after a restart, not just runs
|
|
||||||
// since this process started.
|
|
||||||
for id, seed := range runner.SeedStats(store.Paths.LogsDir, jobs, store.Config.MaxLogFiles) {
|
|
||||||
runtime := s.runtimes[id]
|
runtime := s.runtimes[id]
|
||||||
if runtime == nil {
|
if runtime == nil {
|
||||||
continue
|
continue
|
||||||
@@ -102,7 +112,6 @@ func NewService(store *storage.Store, jobs []domain.Job) *Service {
|
|||||||
runtime.MaxDurationMS = seed.MaxDurationMS
|
runtime.MaxDurationMS = seed.MaxDurationMS
|
||||||
runtime.TimedRunCount = seed.TimedRunCount
|
runtime.TimedRunCount = seed.TimedRunCount
|
||||||
}
|
}
|
||||||
return s
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start begins scheduling with the real wall clock. It is the production entry
|
// Start begins scheduling with the real wall clock. It is the production entry
|
||||||
|
|||||||
@@ -3,4 +3,4 @@ package app
|
|||||||
// Version is the application version shown in the GUI and used by build
|
// Version is the application version shown in the GUI and used by build
|
||||||
// scripts in artifact names. It is a var rather than a const so release builds
|
// scripts in artifact names. It is a var rather than a const so release builds
|
||||||
// can override it with Go ldflags when CI tags a build.
|
// can override it with Go ldflags when CI tags a build.
|
||||||
var Version = "0.11.4"
|
var Version = "1.0.0"
|
||||||
|
|||||||
@@ -15,6 +15,39 @@ const (
|
|||||||
ExecutionModeSequential ExecutionMode = "sequential"
|
ExecutionModeSequential ExecutionMode = "sequential"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Theme selects the application's visual appearance. It is a UI-only choice with
|
||||||
|
// no effect on scheduling; it is stored in Config so it persists across launches
|
||||||
|
// alongside the other desktop-shell preferences.
|
||||||
|
type Theme string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// ThemeDefault keeps Fyne's built-in theme — the original look.
|
||||||
|
ThemeDefault Theme = "default"
|
||||||
|
// ThemeGoSentry applies the branded teal/amber theme derived from the logo
|
||||||
|
// and app icon.
|
||||||
|
ThemeGoSentry Theme = "gosentry"
|
||||||
|
)
|
||||||
|
|
||||||
|
// JobListView selects how densely the Jobs tab renders its sidebar list. Like
|
||||||
|
// Theme it is a UI-only choice with no effect on scheduling; it lives in Config
|
||||||
|
// so the user's preference survives a restart.
|
||||||
|
type JobListView string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// JobListViewDetailed is the three-line row: name, metadata, status.
|
||||||
|
JobListViewDetailed JobListView = "detailed"
|
||||||
|
// JobListViewCompact is the one-line row: name on the left, status on the
|
||||||
|
// right, so many more jobs fit without scrolling.
|
||||||
|
JobListViewCompact JobListView = "compact"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsCompact reports whether the compact rendering is selected. Only the exact
|
||||||
|
// "compact" value counts, so empty, legacy, and unrecognised values all read as
|
||||||
|
// detailed — every consumer normalizes them the same way.
|
||||||
|
func (v JobListView) IsCompact() bool {
|
||||||
|
return v == JobListViewCompact
|
||||||
|
}
|
||||||
|
|
||||||
// OverlapPolicy decides what happens when a job's next run fires while the
|
// OverlapPolicy decides what happens when a job's next run fires while the
|
||||||
// previous run is still active.
|
// previous run is still active.
|
||||||
type OverlapPolicy string
|
type OverlapPolicy string
|
||||||
@@ -31,7 +64,15 @@ const (
|
|||||||
// application-level choices: where to read jobs from, where to write logs, and
|
// application-level choices: where to read jobs from, where to write logs, and
|
||||||
// how the desktop shell should behave.
|
// how the desktop shell should behave.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
JobsDir string `json:"jobs_dir"`
|
// JobsFile is the full path of the JSON file holding the job definitions,
|
||||||
|
// file name included, so the user can keep jobs under any name they like. A
|
||||||
|
// relative path is resolved against the program folder.
|
||||||
|
JobsFile string `json:"jobs_file"`
|
||||||
|
// JobsDir is the pre-0.15 setting that named only the directory, with the
|
||||||
|
// file name fixed to jobs.json. It is still read so an older gosentry.json
|
||||||
|
// keeps working: storage.loadOrCreateConfig turns it into JobsFile and
|
||||||
|
// clears it, so the field disappears from the file on the next save.
|
||||||
|
JobsDir string `json:"jobs_dir,omitempty"`
|
||||||
LogsDir string `json:"logs_dir"`
|
LogsDir string `json:"logs_dir"`
|
||||||
MaxLogFiles int `json:"max_log_files"`
|
MaxLogFiles int `json:"max_log_files"`
|
||||||
MaxLogAgeDays int `json:"max_log_age_days"`
|
MaxLogAgeDays int `json:"max_log_age_days"`
|
||||||
@@ -40,7 +81,39 @@ type Config struct {
|
|||||||
NotifyOnFailure bool `json:"notify_on_failure,omitempty"`
|
NotifyOnFailure bool `json:"notify_on_failure,omitempty"`
|
||||||
ExecutionMode ExecutionMode `json:"execution_mode,omitempty"`
|
ExecutionMode ExecutionMode `json:"execution_mode,omitempty"`
|
||||||
OverlapPolicy OverlapPolicy `json:"overlap_policy,omitempty"`
|
OverlapPolicy OverlapPolicy `json:"overlap_policy,omitempty"`
|
||||||
|
// DefaultTimeoutSeconds is the run timeout applied to jobs that leave their
|
||||||
|
// own Job.TimeoutSeconds unset. 0 (the default) means no timeout: such jobs
|
||||||
|
// run to completion however long that takes. It is written even when 0 —
|
||||||
|
// omitempty would hide a deliberate choice from the hand-editable config.
|
||||||
|
DefaultTimeoutSeconds int `json:"default_timeout_seconds"`
|
||||||
Paused bool `json:"paused,omitempty"`
|
Paused bool `json:"paused,omitempty"`
|
||||||
|
// Theme selects the visual appearance. Empty is treated as ThemeDefault so
|
||||||
|
// configs written before this field existed keep the original look.
|
||||||
|
Theme Theme `json:"theme,omitempty"`
|
||||||
|
// JobListView selects the Jobs list density. Empty is treated as
|
||||||
|
// JobListViewDetailed so configs written before this field existed keep the
|
||||||
|
// current three-line rows.
|
||||||
|
JobListView JobListView `json:"job_list_view,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultConfig returns the built-in default settings. It is the config used
|
||||||
|
// when gosentry.json does not yet exist, and is also what the Settings UI
|
||||||
|
// offers to restore via its "Defaults" button.
|
||||||
|
func DefaultConfig() Config {
|
||||||
|
return Config{
|
||||||
|
JobsFile: "jobs.json",
|
||||||
|
LogsDir: "logs",
|
||||||
|
MaxLogFiles: 100,
|
||||||
|
MaxLogAgeDays: 30,
|
||||||
|
StartOnLogin: false,
|
||||||
|
KeepRunningInTray: true,
|
||||||
|
NotifyOnFailure: true,
|
||||||
|
ExecutionMode: ExecutionModeParallel,
|
||||||
|
OverlapPolicy: OverlapPolicySkip,
|
||||||
|
Theme: ThemeDefault,
|
||||||
|
JobListView: JobListViewDetailed,
|
||||||
|
DefaultTimeoutSeconds: 0,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// JobsFile is the on-disk shape of jobs.json. Wrapping the slice in a top-level
|
// JobsFile is the on-disk shape of jobs.json. Wrapping the slice in a top-level
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
// TestJobListViewIsCompact pins the normalization rule: only the exact
|
||||||
|
// "compact" value selects the one-line rows, so empty and unrecognised values
|
||||||
|
// (including configs written before the field existed) keep the detailed look.
|
||||||
|
func TestJobListViewIsCompact(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
view JobListView
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{JobListViewCompact, true},
|
||||||
|
{JobListViewDetailed, false},
|
||||||
|
{"", false},
|
||||||
|
{"Compact", false},
|
||||||
|
{"tiny", false},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if got := tc.view.IsCompact(); got != tc.want {
|
||||||
|
t.Errorf("JobListView(%q).IsCompact() = %v, want %v", tc.view, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultConfigUsesDetailedJobList(t *testing.T) {
|
||||||
|
if got := DefaultConfig().JobListView; got != JobListViewDetailed {
|
||||||
|
t.Errorf("default JobListView = %q, want %q", got, JobListViewDetailed)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,4 +15,19 @@ type Job struct {
|
|||||||
StartOnly bool `json:"start_only,omitempty"`
|
StartOnly bool `json:"start_only,omitempty"`
|
||||||
Enabled bool `json:"enabled"`
|
Enabled bool `json:"enabled"`
|
||||||
OverlapPolicy string `json:"overlap_policy,omitempty"`
|
OverlapPolicy string `json:"overlap_policy,omitempty"`
|
||||||
|
// TimeoutSeconds bounds how long a run may take before it is killed. It is a
|
||||||
|
// pointer so the three states stay distinguishable on disk: absent (nil)
|
||||||
|
// means "inherit the global Config.DefaultTimeoutSeconds", mirroring
|
||||||
|
// OverlapPolicy's empty string; an explicit 0 means "no timeout" and does
|
||||||
|
// not inherit; a positive value is the per-job limit in seconds. The
|
||||||
|
// inherited global default may itself be 0, also meaning no timeout.
|
||||||
|
// normalizeJobs must leave nil untouched rather than backfilling a value.
|
||||||
|
TimeoutSeconds *int `json:"timeout_seconds,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TimeoutSecondsPtr returns a pointer suitable for Job.TimeoutSeconds. It exists
|
||||||
|
// because nil (inherit) and an explicit 0 (no timeout) are different states, so
|
||||||
|
// callers cannot just assign an int.
|
||||||
|
func TimeoutSecondsPtr(seconds int) *int {
|
||||||
|
return &seconds
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package desktop
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInstallDesktopIntegrationWritesDesktopAndIcon(t *testing.T) {
|
||||||
|
dataHome := t.TempDir()
|
||||||
|
t.Setenv("XDG_DATA_HOME", dataHome)
|
||||||
|
|
||||||
|
appID := "ru.mixeme.gosentry.desktop"
|
||||||
|
executable := filepath.Join(dataHome, "bin", "gosentry")
|
||||||
|
icon := []byte{0x89, 0x50, 0x4e, 0x47} // PNG magic prefix is enough for file presence
|
||||||
|
|
||||||
|
iconPath, err := InstallDesktopIntegration(appID, executable, icon)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("InstallDesktopIntegration: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := os.Stat(iconPath); err != nil {
|
||||||
|
t.Fatalf("icon file: %v", err)
|
||||||
|
}
|
||||||
|
iconData, err := os.ReadFile(iconPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read icon: %v", err)
|
||||||
|
}
|
||||||
|
if string(iconData) != string(icon) {
|
||||||
|
t.Fatalf("icon bytes mismatch")
|
||||||
|
}
|
||||||
|
|
||||||
|
desktopPath := filepath.Join(dataHome, "applications", appID+".desktop")
|
||||||
|
data, err := os.ReadFile(desktopPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read desktop entry: %v", err)
|
||||||
|
}
|
||||||
|
text := string(data)
|
||||||
|
if !strings.Contains(text, "Name=GoSentry") {
|
||||||
|
t.Fatalf("desktop entry missing Name: %s", text)
|
||||||
|
}
|
||||||
|
if !strings.Contains(text, "StartupWMClass="+appID) {
|
||||||
|
t.Fatalf("desktop entry missing WM class: %s", text)
|
||||||
|
}
|
||||||
|
wantExec := "Exec=" + quoteDesktopExec(executable)
|
||||||
|
if !strings.Contains(text, wantExec) {
|
||||||
|
t.Fatalf("desktop entry exec = %s, want substring %q", text, wantExec)
|
||||||
|
}
|
||||||
|
if !strings.Contains(text, "Icon="+iconPath) {
|
||||||
|
t.Fatalf("desktop entry missing Icon path: %s", text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQuoteDesktopExecQuotesPath(t *testing.T) {
|
||||||
|
got := quoteDesktopExec("/opt/Go Sentry/gosentry")
|
||||||
|
if got != `"/opt/Go Sentry/gosentry"` {
|
||||||
|
t.Errorf("quoteDesktopExec = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// Package filemanager opens a directory in the desktop file manager, so the
|
||||||
|
// UI can reveal a configured folder (logs, jobs) without knowing which handler
|
||||||
|
// the platform uses.
|
||||||
|
package filemanager
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"runtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Open shows dir in the platform file manager. A missing path, a path that is
|
||||||
|
// not a directory, and a handler that fails to start are all returned as
|
||||||
|
// errors so the caller can surface them instead of appearing to do nothing.
|
||||||
|
func Open(dir string) error {
|
||||||
|
info, err := os.Stat(dir)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return fmt.Errorf("folder does not exist: %s", dir)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !info.IsDir() {
|
||||||
|
return fmt.Errorf("not a folder: %s", dir)
|
||||||
|
}
|
||||||
|
name, args := openCommand(dir)
|
||||||
|
if name == "" {
|
||||||
|
return fmt.Errorf("opening a folder is not supported on %s", runtime.GOOS)
|
||||||
|
}
|
||||||
|
command := exec.Command(name, args...)
|
||||||
|
if err := command.Start(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// The handler hands the request to the desktop shell and exits on its own —
|
||||||
|
// Windows Explorer even exits non-zero after opening the window — so its
|
||||||
|
// status carries no information. Wait runs only to release the process
|
||||||
|
// handle, and never blocks the caller.
|
||||||
|
go func() { _ = command.Wait() }()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package filemanager
|
||||||
|
|
||||||
|
// openCommand returns the XDG invocation for dir. xdg-open picks whichever
|
||||||
|
// file manager the desktop environment has registered for directories.
|
||||||
|
func openCommand(dir string) (string, []string) {
|
||||||
|
return "xdg-open", []string{dir}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
//go:build !windows && !linux
|
||||||
|
|
||||||
|
package filemanager
|
||||||
|
|
||||||
|
// openCommand has no handler to name on platforms GoSentry does not ship for.
|
||||||
|
// An empty name makes Open report that the action is unavailable instead of
|
||||||
|
// running something arbitrary.
|
||||||
|
func openCommand(dir string) (string, []string) {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package filemanager
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The success path is deliberately not tested: it would pop a real file
|
||||||
|
// manager window on the machine running the suite. Only the guards that keep
|
||||||
|
// Open from launching anything are exercised here.
|
||||||
|
|
||||||
|
func TestOpenRejectsMissingFolder(t *testing.T) {
|
||||||
|
missing := filepath.Join(t.TempDir(), "no-such-folder")
|
||||||
|
|
||||||
|
err := Open(missing)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Open on a missing folder returned nil, want an error")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), missing) {
|
||||||
|
t.Errorf("error %q does not name the missing folder %q", err, missing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOpenRejectsFile(t *testing.T) {
|
||||||
|
file := filepath.Join(t.TempDir(), "gosentry.log")
|
||||||
|
if err := os.WriteFile(file, []byte("log"), 0o644); err != nil {
|
||||||
|
t.Fatalf("write test file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := Open(file)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Open on a file returned nil, want an error")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "not a folder") {
|
||||||
|
t.Errorf("error %q does not report that the path is not a folder", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOpenCommandNamesPlatformHandler checks the supported platforms name a
|
||||||
|
// handler (an empty name makes Open report the action as unavailable) and that
|
||||||
|
// the directory is passed as a single argument, so spaces need no quoting.
|
||||||
|
func TestOpenCommandNamesPlatformHandler(t *testing.T) {
|
||||||
|
dir := filepath.Join(t.TempDir(), "log files")
|
||||||
|
|
||||||
|
name, args := openCommand(dir)
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "windows":
|
||||||
|
if name != "explorer" {
|
||||||
|
t.Errorf("handler on windows = %q, want %q", name, "explorer")
|
||||||
|
}
|
||||||
|
case "linux":
|
||||||
|
if name != "xdg-open" {
|
||||||
|
t.Errorf("handler on linux = %q, want %q", name, "xdg-open")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if name != "" {
|
||||||
|
t.Errorf("handler on %s = %q, want no handler", runtime.GOOS, name)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(args) != 1 || args[0] != filepath.Clean(dir) {
|
||||||
|
t.Errorf("arguments = %q, want the single path %q", args, filepath.Clean(dir))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package filemanager
|
||||||
|
|
||||||
|
import "path/filepath"
|
||||||
|
|
||||||
|
// openCommand returns the Explorer invocation for dir. The path is cleaned
|
||||||
|
// because Explorer ignores an argument that mixes separators, and it is passed
|
||||||
|
// as a single argument so spaces need no quoting.
|
||||||
|
func openCommand(dir string) (string, []string) {
|
||||||
|
return "explorer", []string{filepath.Clean(dir)}
|
||||||
|
}
|
||||||
@@ -12,16 +12,23 @@ import (
|
|||||||
"gitea.mixdep.ru/mix/gosentry/src/platform/winproc"
|
"gitea.mixdep.ru/mix/gosentry/src/platform/winproc"
|
||||||
)
|
)
|
||||||
|
|
||||||
const commandTimeout = 30 * time.Second
|
|
||||||
const commandWaitDelay = 2 * time.Second
|
const commandWaitDelay = 2 * time.Second
|
||||||
|
|
||||||
func RunJob(ctx context.Context, job *domain.Job, trigger string, logsDir string) (domain.RunRecord, error) {
|
func RunJob(ctx context.Context, job *domain.Job, trigger string, logsDir string, timeout time.Duration) (domain.RunRecord, error) {
|
||||||
started := time.Now()
|
started := time.Now()
|
||||||
// Commands can hang forever if a script waits for input or a child process
|
// Commands can hang forever if a script waits for input or a child process
|
||||||
// stalls. A fixed timeout is a conservative first guardrail for a desktop
|
// stalls. The effective timeout is resolved by the caller (per-job value or
|
||||||
// scheduler; later it can become a per-job setting without changing the
|
// the global default), keeping the runner ignorant of the global config. A
|
||||||
// runner contract.
|
// non-positive timeout means "no timeout": context.WithTimeout(ctx, 0) would
|
||||||
runCtx, cancel := context.WithTimeout(ctx, commandTimeout)
|
// expire immediately, so fall back to a plain cancelable context that only
|
||||||
|
// ever ends via ctx (e.g. app shutdown).
|
||||||
|
var runCtx context.Context
|
||||||
|
var cancel context.CancelFunc
|
||||||
|
if timeout > 0 {
|
||||||
|
runCtx, cancel = context.WithTimeout(ctx, timeout)
|
||||||
|
} else {
|
||||||
|
runCtx, cancel = context.WithCancel(ctx)
|
||||||
|
}
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
var output string
|
var output string
|
||||||
@@ -49,7 +56,7 @@ func RunJob(ctx context.Context, job *domain.Job, trigger string, logsDir string
|
|||||||
duration := time.Since(started).Round(time.Millisecond)
|
duration := time.Since(started).Round(time.Millisecond)
|
||||||
durationMS = duration.Milliseconds()
|
durationMS = duration.Milliseconds()
|
||||||
output = formatOutput(stdoutBuf.String(), stderrBuf.String())
|
output = formatOutput(stdoutBuf.String(), stderrBuf.String())
|
||||||
state, detail = runStateDetail(err, runCtx.Err(), duration)
|
state, detail = runStateDetail(err, runCtx.Err(), duration, timeout)
|
||||||
}
|
}
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
@@ -106,12 +113,12 @@ func startOnlyOutput(job domain.Job, pid int) string {
|
|||||||
return builder.String()
|
return builder.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func runStateDetail(err error, runErr error, duration time.Duration) (string, string) {
|
func runStateDetail(err error, runErr error, duration time.Duration, timeout time.Duration) (string, string) {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return "OK", fmt.Sprintf("Completed in %s (exit code 0)", duration)
|
return "OK", fmt.Sprintf("Completed in %s (exit code 0)", duration)
|
||||||
}
|
}
|
||||||
if errors.Is(runErr, context.DeadlineExceeded) {
|
if errors.Is(runErr, context.DeadlineExceeded) {
|
||||||
return "Failed", fmt.Sprintf("Timed out after %s", commandTimeout)
|
return "Failed", fmt.Sprintf("Timed out after %s", timeout)
|
||||||
}
|
}
|
||||||
if errors.Is(err, exec.ErrWaitDelay) {
|
if errors.Is(err, exec.ErrWaitDelay) {
|
||||||
return "OK", fmt.Sprintf("Completed; output capture stopped after %s because a child process kept the stream open", commandWaitDelay)
|
return "OK", fmt.Sprintf("Completed; output capture stopped after %s because a child process kept the stream open", commandWaitDelay)
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ func TestRunJobLogFileAllHeaders(t *testing.T) {
|
|||||||
Command: echoCommand("header test output"),
|
Command: echoCommand("header test output"),
|
||||||
}
|
}
|
||||||
|
|
||||||
record, err := RunJob(context.Background(), &job, "Schedule", logsDir)
|
record, err := RunJob(context.Background(), &job, "Schedule", logsDir, 30*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -77,7 +77,7 @@ func TestRunJobRecordFields(t *testing.T) {
|
|||||||
Command: echoCommand("record field check"),
|
Command: echoCommand("record field check"),
|
||||||
}
|
}
|
||||||
|
|
||||||
record, err := RunJob(context.Background(), &job, "Schedule", t.TempDir())
|
record, err := RunJob(context.Background(), &job, "Schedule", t.TempDir(), 30*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -164,7 +164,7 @@ func TestRunJobWritesLogFile(t *testing.T) {
|
|||||||
Command: echoCommand("hello from test"),
|
Command: echoCommand("hello from test"),
|
||||||
}
|
}
|
||||||
|
|
||||||
record, err := RunJob(context.Background(), &job, "Manual", logsDir)
|
record, err := RunJob(context.Background(), &job, "Manual", logsDir, 30*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -202,7 +202,7 @@ func TestRunJobRunsQuotedWindowsExecutable(t *testing.T) {
|
|||||||
Command: `"C:\Windows\System32\cmd.exe" /C echo quoted command ok`,
|
Command: `"C:\Windows\System32\cmd.exe" /C echo quoted command ok`,
|
||||||
}
|
}
|
||||||
|
|
||||||
record, err := RunJob(context.Background(), &job, "Manual", logsDir)
|
record, err := RunJob(context.Background(), &job, "Manual", logsDir, 30*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -234,7 +234,7 @@ func TestRunJobRunsUnquotedWindowsProgramPathWithSpaces(t *testing.T) {
|
|||||||
Command: scriptPath,
|
Command: scriptPath,
|
||||||
}
|
}
|
||||||
|
|
||||||
record, err := RunJob(context.Background(), &job, "Manual", logsDir)
|
record, err := RunJob(context.Background(), &job, "Manual", logsDir, 30*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -259,7 +259,7 @@ func TestRunJobRunsWindowsCommandWithSeparateArguments(t *testing.T) {
|
|||||||
Arguments: "/C\necho separate arguments ok",
|
Arguments: "/C\necho separate arguments ok",
|
||||||
}
|
}
|
||||||
|
|
||||||
record, err := RunJob(context.Background(), &job, "Manual", logsDir)
|
record, err := RunJob(context.Background(), &job, "Manual", logsDir, 30*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -285,7 +285,7 @@ func TestRunJobFailsOnNonZeroExitCode(t *testing.T) {
|
|||||||
job.Arguments = "/C\nexit /b 1"
|
job.Arguments = "/C\nexit /b 1"
|
||||||
}
|
}
|
||||||
|
|
||||||
record, err := RunJob(context.Background(), &job, "Manual", t.TempDir())
|
record, err := RunJob(context.Background(), &job, "Manual", t.TempDir(), 30*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -312,7 +312,7 @@ func TestRunJobStartOnlyDoesNotWaitForExitCode(t *testing.T) {
|
|||||||
StartOnly: true,
|
StartOnly: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
record, err := RunJob(context.Background(), &job, "Manual", t.TempDir())
|
record, err := RunJob(context.Background(), &job, "Manual", t.TempDir(), 30*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -336,7 +336,7 @@ func TestRunJobStartOnlyReportsStartFailure(t *testing.T) {
|
|||||||
StartOnly: true,
|
StartOnly: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
record, err := RunJob(context.Background(), &job, "Manual", t.TempDir())
|
record, err := RunJob(context.Background(), &job, "Manual", t.TempDir(), 30*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -348,3 +348,84 @@ func TestRunJobStartOnlyReportsStartFailure(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRunJobTimesOut(t *testing.T) {
|
||||||
|
command := "sh"
|
||||||
|
arguments := "-c\nsleep 5"
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
command = `C:\Windows\System32\cmd.exe`
|
||||||
|
// timeout waits ~5s; ping to localhost is a portable stall on hosts where
|
||||||
|
// timeout refuses to run without an interactive console.
|
||||||
|
arguments = "/C\nping -n 6 127.0.0.1 >NUL"
|
||||||
|
}
|
||||||
|
job := domain.Job{
|
||||||
|
ID: 50,
|
||||||
|
Name: "Timeout Test",
|
||||||
|
Command: command,
|
||||||
|
Arguments: arguments,
|
||||||
|
}
|
||||||
|
|
||||||
|
record, err := RunJob(context.Background(), &job, "Manual", t.TempDir(), 100*time.Millisecond)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if record.State != "Failed" {
|
||||||
|
t.Fatalf("expected timed-out job to fail, got state %q detail %q", record.State, record.Detail)
|
||||||
|
}
|
||||||
|
if !strings.Contains(record.Detail, "Timed out after 100ms") {
|
||||||
|
t.Fatalf("expected timeout detail with the effective timeout, got %q", record.Detail)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunJobZeroTimeoutMeansNoTimeout(t *testing.T) {
|
||||||
|
command := "sh"
|
||||||
|
arguments := "-c\nsleep 0.2"
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
command = `C:\Windows\System32\cmd.exe`
|
||||||
|
arguments = "/C\nping -n 2 127.0.0.1 >NUL"
|
||||||
|
}
|
||||||
|
job := domain.Job{
|
||||||
|
ID: 52,
|
||||||
|
Name: "No Timeout Test",
|
||||||
|
Command: command,
|
||||||
|
Arguments: arguments,
|
||||||
|
}
|
||||||
|
|
||||||
|
// A non-positive timeout must not expire immediately (context.WithTimeout
|
||||||
|
// with a zero duration would); the job must run to completion.
|
||||||
|
record, err := RunJob(context.Background(), &job, "Manual", t.TempDir(), 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if record.State != "OK" {
|
||||||
|
t.Fatalf("expected job with no timeout to complete OK, got state %q detail %q", record.State, record.Detail)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunJobStartOnlyIgnoresTimeout(t *testing.T) {
|
||||||
|
command := "sh"
|
||||||
|
arguments := "-c\nsleep 5"
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
command = `C:\Windows\System32\cmd.exe`
|
||||||
|
arguments = "/C\nping -n 6 127.0.0.1 >NUL"
|
||||||
|
}
|
||||||
|
job := domain.Job{
|
||||||
|
ID: 51,
|
||||||
|
Name: "Start Only Timeout",
|
||||||
|
Command: command,
|
||||||
|
Arguments: arguments,
|
||||||
|
StartOnly: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// A tiny run timeout must not affect StartOnly jobs: they never wait on the
|
||||||
|
// timed run context, so the launch succeeds regardless.
|
||||||
|
record, err := RunJob(context.Background(), &job, "Manual", t.TempDir(), time.Millisecond)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if record.State != "OK" {
|
||||||
|
t.Fatalf("expected start-only job to be OK despite tiny timeout, got state %q detail %q", record.State, record.Detail)
|
||||||
|
}
|
||||||
|
if !strings.Contains(record.Detail, "not waiting for process exit") {
|
||||||
|
t.Fatalf("expected start-only detail, got %q", record.Detail)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -9,9 +9,11 @@ const (
|
|||||||
// The config file stays beside the executable so the portable build behaves
|
// The config file stays beside the executable so the portable build behaves
|
||||||
// predictably: moving the program folder moves its settings with it.
|
// predictably: moving the program folder moves its settings with it.
|
||||||
ConfigFileName = "gosentry.json"
|
ConfigFileName = "gosentry.json"
|
||||||
// Jobs are kept in a separate JSON file because the user can choose a
|
// Jobs are kept in a separate JSON file because the user can point the
|
||||||
// different jobs directory, while application settings remain local to the
|
// configuration at any jobs file they like, while application settings
|
||||||
// installed/copied program.
|
// remain local to the installed/copied program. This is only the default
|
||||||
|
// name, used before the config is read and when an older config that named
|
||||||
|
// just a directory is migrated.
|
||||||
JobsFileName = "jobs.json"
|
JobsFileName = "jobs.json"
|
||||||
|
|
||||||
)
|
)
|
||||||
@@ -23,6 +25,9 @@ type Paths struct {
|
|||||||
ExecutablePath string
|
ExecutablePath string
|
||||||
AppDir string
|
AppDir string
|
||||||
ConfigPath string
|
ConfigPath string
|
||||||
|
// JobsDir is the directory containing JobsPath. It is derived from the
|
||||||
|
// configured jobs file, never configured on its own, and exists so writers
|
||||||
|
// can create the folder before saving.
|
||||||
JobsDir string
|
JobsDir string
|
||||||
JobsPath string
|
JobsPath string
|
||||||
LogsDir string
|
LogsDir string
|
||||||
|
|||||||
@@ -68,17 +68,7 @@ func (s *Store) SaveJobs(jobs []domain.Job) error {
|
|||||||
func loadOrCreateConfig(paths Paths) (domain.Config, error) {
|
func loadOrCreateConfig(paths Paths) (domain.Config, error) {
|
||||||
// Defaults favor a portable installation: settings and jobs begin next to the
|
// Defaults favor a portable installation: settings and jobs begin next to the
|
||||||
// executable, while logs are grouped under a dedicated subdirectory.
|
// executable, while logs are grouped under a dedicated subdirectory.
|
||||||
config := domain.Config{
|
config := domain.DefaultConfig()
|
||||||
JobsDir: ".",
|
|
||||||
LogsDir: "logs",
|
|
||||||
MaxLogFiles: 100,
|
|
||||||
MaxLogAgeDays: 30,
|
|
||||||
StartOnLogin: false,
|
|
||||||
KeepRunningInTray: true,
|
|
||||||
NotifyOnFailure: true,
|
|
||||||
ExecutionMode: domain.ExecutionModeParallel,
|
|
||||||
OverlapPolicy: domain.OverlapPolicySkip,
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := os.Stat(paths.ConfigPath); errors.Is(err, os.ErrNotExist) {
|
if _, err := os.Stat(paths.ConfigPath); errors.Is(err, os.ErrNotExist) {
|
||||||
return config, writeJSON(paths.ConfigPath, config)
|
return config, writeJSON(paths.ConfigPath, config)
|
||||||
@@ -88,14 +78,25 @@ func loadOrCreateConfig(paths Paths) (domain.Config, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return domain.Config{}, err
|
return domain.Config{}, err
|
||||||
}
|
}
|
||||||
|
// Clearing the default first keeps "the file sets jobs_file" distinguishable
|
||||||
|
// from "the file omits it", which the jobs_dir migration below depends on.
|
||||||
|
// The fallbacks restore a value in either case.
|
||||||
|
config.JobsFile = ""
|
||||||
if err := json.Unmarshal(data, &config); err != nil {
|
if err := json.Unmarshal(data, &config); err != nil {
|
||||||
return domain.Config{}, err
|
return domain.Config{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.TrimSpace(config.JobsDir) == "" {
|
// A config written before the setting named a file carries jobs_dir instead
|
||||||
|
// of jobs_file. Keep its meaning by appending the fixed name that version
|
||||||
|
// used, then drop the old key so the file is rewritten in the current shape.
|
||||||
|
if strings.TrimSpace(config.JobsFile) == "" && strings.TrimSpace(config.JobsDir) != "" {
|
||||||
|
config.JobsFile = filepath.Join(config.JobsDir, JobsFileName)
|
||||||
|
}
|
||||||
|
config.JobsDir = ""
|
||||||
|
if strings.TrimSpace(config.JobsFile) == "" {
|
||||||
// Empty paths are treated as missing values rather than intentional root
|
// Empty paths are treated as missing values rather than intentional root
|
||||||
// directories. This avoids accidentally writing jobs to unexpected places.
|
// directories. This avoids accidentally writing jobs to unexpected places.
|
||||||
config.JobsDir = "."
|
config.JobsFile = JobsFileName
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(config.LogsDir) == "" {
|
if strings.TrimSpace(config.LogsDir) == "" {
|
||||||
config.LogsDir = "logs"
|
config.LogsDir = "logs"
|
||||||
@@ -112,27 +113,49 @@ func loadOrCreateConfig(paths Paths) (domain.Config, error) {
|
|||||||
if config.OverlapPolicy == "" {
|
if config.OverlapPolicy == "" {
|
||||||
config.OverlapPolicy = domain.OverlapPolicySkip
|
config.OverlapPolicy = domain.OverlapPolicySkip
|
||||||
}
|
}
|
||||||
|
// DefaultTimeoutSeconds is deliberately not normalized: 0 is a meaningful
|
||||||
|
// value ("no timeout"), not a missing one, so backfilling it here would make
|
||||||
|
// the setting impossible to persist. Negative values are rejected by
|
||||||
|
// app.validateConfig before they can be saved.
|
||||||
|
if config.Theme == "" {
|
||||||
|
config.Theme = domain.ThemeDefault
|
||||||
|
}
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadOrCreateJobs(path string) ([]domain.Job, error) {
|
// LoadJobsFile reads and normalizes the job definitions at path. The bool
|
||||||
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
|
// reports whether the file was there: a missing file is not an error but the
|
||||||
// Seed harmless sample jobs so a new user can immediately see scheduled
|
// answer to "is this file already a jobs file?", which is what the Settings tab
|
||||||
// and manual execution without inventing a command.
|
// needs when the user points the application at a different jobs file.
|
||||||
jobs := defaultJobs()
|
func LoadJobsFile(path string) ([]domain.Job, bool, error) {
|
||||||
normalizeJobs(jobs)
|
|
||||||
return jobs, writeJSON(path, domain.JobsFile{Jobs: jobs})
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
var file domain.JobsFile
|
var file domain.JobsFile
|
||||||
if err := json.Unmarshal(data, &file); err != nil {
|
if err := json.Unmarshal(data, &file); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
normalizeJobs(file.Jobs)
|
||||||
|
return file.Jobs, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOrCreateJobs(path string) ([]domain.Job, error) {
|
||||||
|
jobs, found, err := LoadJobsFile(path)
|
||||||
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return file.Jobs, nil
|
if found {
|
||||||
|
return jobs, nil
|
||||||
|
}
|
||||||
|
// Seed harmless sample jobs so a new user can immediately see scheduled
|
||||||
|
// and manual execution without inventing a command.
|
||||||
|
jobs = defaultJobs()
|
||||||
|
normalizeJobs(jobs)
|
||||||
|
return jobs, writeJSON(path, domain.JobsFile{Jobs: jobs})
|
||||||
}
|
}
|
||||||
|
|
||||||
func normalizeJobs(jobs []domain.Job) {
|
func normalizeJobs(jobs []domain.Job) {
|
||||||
@@ -165,24 +188,26 @@ func normalizeJobs(jobs []domain.Job) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveJobsDir(appDir string, jobsDir string) string {
|
// ResolveConfiguredPath turns a file or directory path from the config into the
|
||||||
return resolveConfiguredDir(appDir, jobsDir)
|
// absolute path the application will actually use. It is exported so callers
|
||||||
}
|
// outside storage — the settings tab, which opens the configured logs folder —
|
||||||
|
// apply the same rule to a path the user has typed but not yet saved.
|
||||||
func resolveConfiguredDir(appDir string, dir string) string {
|
func ResolveConfiguredPath(appDir string, path string) string {
|
||||||
if filepath.IsAbs(dir) {
|
if filepath.IsAbs(path) {
|
||||||
return dir
|
return path
|
||||||
}
|
}
|
||||||
// Relative paths are resolved against the executable directory, not the
|
// Relative paths are resolved against the executable directory, not the
|
||||||
// process working directory. This matches ResolvePaths and keeps shortcuts,
|
// process working directory. This matches ResolvePaths and keeps shortcuts,
|
||||||
// Explorer launches, and terminal launches consistent.
|
// Explorer launches, and terminal launches consistent.
|
||||||
return filepath.Clean(filepath.Join(appDir, dir))
|
return filepath.Clean(filepath.Join(appDir, path))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) applyConfigPaths() {
|
func (s *Store) applyConfigPaths() {
|
||||||
s.Paths.JobsDir = resolveConfiguredDir(s.Paths.AppDir, s.Config.JobsDir)
|
// The jobs file is configured as a whole path; its directory is derived so
|
||||||
s.Paths.JobsPath = filepath.Join(s.Paths.JobsDir, JobsFileName)
|
// SaveJobs can create the folder when the user points at a new location.
|
||||||
s.Paths.LogsDir = resolveConfiguredDir(s.Paths.AppDir, s.Config.LogsDir)
|
s.Paths.JobsPath = ResolveConfiguredPath(s.Paths.AppDir, s.Config.JobsFile)
|
||||||
|
s.Paths.JobsDir = filepath.Dir(s.Paths.JobsPath)
|
||||||
|
s.Paths.LogsDir = ResolveConfiguredPath(s.Paths.AppDir, s.Config.LogsDir)
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeJSON(path string, value any) error {
|
func writeJSON(path string, value any) error {
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ func TestConfigRoundTrip(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
want := domain.Config{
|
want := domain.Config{
|
||||||
JobsDir: "/custom/jobs",
|
JobsFile: "/custom/jobs/team.json",
|
||||||
LogsDir: "/custom/logs",
|
LogsDir: "/custom/logs",
|
||||||
MaxLogFiles: 50,
|
MaxLogFiles: 50,
|
||||||
MaxLogAgeDays: 14,
|
MaxLogAgeDays: 14,
|
||||||
@@ -94,8 +94,8 @@ func TestConfigRoundTrip(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if got.JobsDir != want.JobsDir {
|
if got.JobsFile != want.JobsFile {
|
||||||
t.Errorf("JobsDir: got %q, want %q", got.JobsDir, want.JobsDir)
|
t.Errorf("JobsFile: got %q, want %q", got.JobsFile, want.JobsFile)
|
||||||
}
|
}
|
||||||
if got.LogsDir != want.LogsDir {
|
if got.LogsDir != want.LogsDir {
|
||||||
t.Errorf("LogsDir: got %q, want %q", got.LogsDir, want.LogsDir)
|
t.Errorf("LogsDir: got %q, want %q", got.LogsDir, want.LogsDir)
|
||||||
@@ -156,8 +156,8 @@ func TestLoadOrCreateConfigCreatesDefaultsOnFirstRun(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if got.JobsDir != "." {
|
if got.JobsFile != "jobs.json" {
|
||||||
t.Errorf("default JobsDir = %q, want '.'", got.JobsDir)
|
t.Errorf("default JobsFile = %q, want 'jobs.json'", got.JobsFile)
|
||||||
}
|
}
|
||||||
if got.LogsDir != "logs" {
|
if got.LogsDir != "logs" {
|
||||||
t.Errorf("default LogsDir = %q, want 'logs'", got.LogsDir)
|
t.Errorf("default LogsDir = %q, want 'logs'", got.LogsDir)
|
||||||
@@ -168,12 +168,180 @@ func TestLoadOrCreateConfigCreatesDefaultsOnFirstRun(t *testing.T) {
|
|||||||
if got.MaxLogAgeDays != 30 {
|
if got.MaxLogAgeDays != 30 {
|
||||||
t.Errorf("default MaxLogAgeDays = %d, want 30", got.MaxLogAgeDays)
|
t.Errorf("default MaxLogAgeDays = %d, want 30", got.MaxLogAgeDays)
|
||||||
}
|
}
|
||||||
|
if got.DefaultTimeoutSeconds != 0 {
|
||||||
|
t.Errorf("default DefaultTimeoutSeconds = %d, want 0 (no timeout)", got.DefaultTimeoutSeconds)
|
||||||
|
}
|
||||||
|
if got.Theme != domain.ThemeDefault {
|
||||||
|
t.Errorf("default Theme = %q, want %q", got.Theme, domain.ThemeDefault)
|
||||||
|
}
|
||||||
|
if got.JobListView != domain.JobListViewDetailed {
|
||||||
|
t.Errorf("default JobListView = %q, want %q", got.JobListView, domain.JobListViewDetailed)
|
||||||
|
}
|
||||||
// The function must have written the defaults to gosentry.json.
|
// The function must have written the defaults to gosentry.json.
|
||||||
if _, err := os.Stat(paths.ConfigPath); err != nil {
|
if _, err := os.Stat(paths.ConfigPath); err != nil {
|
||||||
t.Errorf("gosentry.json should have been created: %v", err)
|
t.Errorf("gosentry.json should have been created: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestLoadOrCreateConfigKeepsZeroTimeoutOnReload guards the "0 = no timeout"
|
||||||
|
// setting against being normalized away when an existing gosentry.json is read
|
||||||
|
// back. Loading must not treat 0 as a missing value.
|
||||||
|
func TestLoadOrCreateConfigKeepsZeroTimeoutOnReload(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
paths := Paths{
|
||||||
|
AppDir: dir,
|
||||||
|
ConfigPath: filepath.Join(dir, ConfigFileName),
|
||||||
|
}
|
||||||
|
|
||||||
|
// First call writes the defaults (DefaultTimeoutSeconds = 0) to disk.
|
||||||
|
if _, err := loadOrCreateConfig(paths); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Second call takes the "file exists" branch, where normalization runs.
|
||||||
|
reloaded, err := loadOrCreateConfig(paths)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if reloaded.DefaultTimeoutSeconds != 0 {
|
||||||
|
t.Errorf("reloaded DefaultTimeoutSeconds = %d, want 0 (no timeout)", reloaded.DefaultTimeoutSeconds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadOrCreateConfigMigratesJobsDir covers a gosentry.json written before
|
||||||
|
// the setting named a file: the old jobs_dir keeps pointing at the same jobs
|
||||||
|
// file, and the retired key is dropped so it is not written back.
|
||||||
|
func TestLoadOrCreateConfigMigratesJobsDir(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
paths := Paths{
|
||||||
|
AppDir: dir,
|
||||||
|
ConfigPath: filepath.Join(dir, ConfigFileName),
|
||||||
|
}
|
||||||
|
legacy := map[string]any{
|
||||||
|
"jobs_dir": filepath.Join(dir, "shared"),
|
||||||
|
"logs_dir": "logs",
|
||||||
|
"max_log_files": 100,
|
||||||
|
"max_log_age_days": 30,
|
||||||
|
}
|
||||||
|
if err := writeJSON(paths.ConfigPath, legacy); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := loadOrCreateConfig(paths)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := filepath.Join(dir, "shared", JobsFileName)
|
||||||
|
if got.JobsFile != want {
|
||||||
|
t.Errorf("migrated JobsFile: got %q, want %q", got.JobsFile, want)
|
||||||
|
}
|
||||||
|
if got.JobsDir != "" {
|
||||||
|
t.Errorf("legacy JobsDir should be cleared, got %q", got.JobsDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The migrated config must not carry the retired key once it is saved.
|
||||||
|
store := &Store{Paths: paths, Config: got}
|
||||||
|
if err := store.SaveConfig(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(paths.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Contains(string(data), "jobs_dir") {
|
||||||
|
t.Errorf("saved config should not contain jobs_dir:\n%s", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadJobsFileReportsMissingWithoutCreating covers the loader the Settings
|
||||||
|
// tab uses to decide between adopting a jobs file and writing the current jobs
|
||||||
|
// to it: a missing file is reported as "not found" rather than an error, and —
|
||||||
|
// unlike the startup path — is not seeded with sample jobs.
|
||||||
|
func TestLoadJobsFileReportsMissingWithoutCreating(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
missing := filepath.Join(dir, "nothing-here.json")
|
||||||
|
|
||||||
|
jobs, found, err := LoadJobsFile(missing)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("missing file should not be an error: %v", err)
|
||||||
|
}
|
||||||
|
if found || jobs != nil {
|
||||||
|
t.Errorf("missing file: got found=%v jobs=%+v, want false/nil", found, jobs)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(missing); !os.IsNotExist(err) {
|
||||||
|
t.Error("LoadJobsFile must not create the file it was asked about")
|
||||||
|
}
|
||||||
|
|
||||||
|
// An existing file comes back normalized, so a hand-written jobs file gains
|
||||||
|
// its IDs and defaults before the application adopts it.
|
||||||
|
path := filepath.Join(dir, "hand-written.json")
|
||||||
|
if err := writeJSON(path, domain.JobsFile{Jobs: []domain.Job{{Name: "No ID"}}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
jobs, found, err = LoadJobsFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !found || len(jobs) != 1 {
|
||||||
|
t.Fatalf("existing file: got found=%v jobs=%+v, want true and one job", found, jobs)
|
||||||
|
}
|
||||||
|
if jobs[0].ID != 1 || jobs[0].Schedule == "" || jobs[0].Command == "" {
|
||||||
|
t.Errorf("loaded job should be normalized, got %+v", jobs[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestApplyConfigPathsDerivesJobsDir checks that the jobs file drives both
|
||||||
|
// resolved paths: relative values resolve against the program folder, and the
|
||||||
|
// containing directory comes from the file name the user chose.
|
||||||
|
func TestApplyConfigPathsDerivesJobsDir(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
store := &Store{
|
||||||
|
Paths: Paths{AppDir: dir},
|
||||||
|
Config: domain.Config{JobsFile: filepath.Join("shared", "team.json"), LogsDir: "logs"},
|
||||||
|
}
|
||||||
|
|
||||||
|
store.applyConfigPaths()
|
||||||
|
|
||||||
|
if want := filepath.Join(dir, "shared", "team.json"); store.Paths.JobsPath != want {
|
||||||
|
t.Errorf("JobsPath: got %q, want %q", store.Paths.JobsPath, want)
|
||||||
|
}
|
||||||
|
if want := filepath.Join(dir, "shared"); store.Paths.JobsDir != want {
|
||||||
|
t.Errorf("JobsDir: got %q, want %q", store.Paths.JobsDir, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestJobTimeoutRoundTripsThreeStates pins the on-disk encoding that keeps
|
||||||
|
// "inherit" and "no timeout" distinguishable: nil is omitted entirely, while an
|
||||||
|
// explicit 0 is written and read back as a set value.
|
||||||
|
func TestJobTimeoutRoundTripsThreeStates(t *testing.T) {
|
||||||
|
jobs := []domain.Job{
|
||||||
|
{ID: 1, Name: "Inherit", TimeoutSeconds: nil},
|
||||||
|
{ID: 2, Name: "No timeout", TimeoutSeconds: domain.TimeoutSecondsPtr(0)},
|
||||||
|
{ID: 3, Name: "Own", TimeoutSeconds: domain.TimeoutSecondsPtr(45)},
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.Marshal(domain.JobsFile{Jobs: jobs})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if want := `"timeout_seconds":0`; !strings.Contains(string(data), want) {
|
||||||
|
t.Fatalf("explicit zero timeout should be written as %s:\n%s", want, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
var got domain.JobsFile
|
||||||
|
if err := json.Unmarshal(data, &got); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got.Jobs[0].TimeoutSeconds != nil {
|
||||||
|
t.Errorf("unset timeout should stay nil, got %d", *got.Jobs[0].TimeoutSeconds)
|
||||||
|
}
|
||||||
|
if got.Jobs[1].TimeoutSeconds == nil || *got.Jobs[1].TimeoutSeconds != 0 {
|
||||||
|
t.Errorf("explicit zero timeout should survive the round trip, got %v", got.Jobs[1].TimeoutSeconds)
|
||||||
|
}
|
||||||
|
if got.Jobs[2].TimeoutSeconds == nil || *got.Jobs[2].TimeoutSeconds != 45 {
|
||||||
|
t.Errorf("per-job timeout should survive the round trip, got %v", got.Jobs[2].TimeoutSeconds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestJobsJSONDoesNotPersistRuntimeNoise(t *testing.T) {
|
func TestJobsJSONDoesNotPersistRuntimeNoise(t *testing.T) {
|
||||||
// Job carries only durable configuration; runtime state lives in
|
// Job carries only durable configuration; runtime state lives in
|
||||||
// domain.JobRuntime and is never marshalled. This guards against a future
|
// domain.JobRuntime and is never marshalled. This guards against a future
|
||||||
|
|||||||
@@ -42,37 +42,85 @@ func collectActivity(jobs []job, runtimes map[int]*domain.JobRuntime) []event {
|
|||||||
return events
|
return events
|
||||||
}
|
}
|
||||||
|
|
||||||
// logColumnMinWidth/logColumnMaxWidth bound the dynamically sized Log column.
|
// textWidth measures how wide s renders at the theme's current body text size.
|
||||||
// The minimum keeps the column readable when names are short or absent; the
|
func textWidth(s string) float32 {
|
||||||
// maximum stops a single very long file name from dominating the table (the
|
return fyne.MeasureText(s, theme.TextSize(), fyne.TextStyle{}).Width
|
||||||
// table still scrolls horizontally past it).
|
}
|
||||||
const (
|
|
||||||
logColumnMinWidth = 240
|
|
||||||
logColumnMaxWidth = 520
|
|
||||||
logColumnPadding = 24
|
|
||||||
)
|
|
||||||
|
|
||||||
// logColumnWidth measures the widest Log cell value so the column can be sized
|
// cellPadding is the horizontal space a table cell reserves around its text.
|
||||||
// to fit its content. Fyne tables do not auto-size columns, so without this the
|
// It replaces a hand-tuned pixel constant with the theme's own inner padding
|
||||||
// fixed width clips file names like "20260601-100000_SomeJobName.log".
|
// doubled (one side each), so it follows text size and DPI.
|
||||||
func logColumnWidth(events []event) float32 {
|
func cellPadding() float32 { return 2 * theme.InnerPadding() }
|
||||||
width := float32(logColumnMinWidth)
|
|
||||||
for _, current := range events {
|
// textColumnMinWidth/textColumnMaxWidth bound every content-measured History
|
||||||
text := logFileName(current.LogFile)
|
// column: the minimum keeps a column readable when its values are short or
|
||||||
|
// absent, the maximum stops one very long value from dominating the table
|
||||||
|
// (the table still scrolls horizontally past it). Expressed as measured text
|
||||||
|
// rather than raw pixels so both follow the theme instead of drifting from it.
|
||||||
|
func textColumnMinWidth() float32 { return textWidth(strings.Repeat("0", 10)) + cellPadding() }
|
||||||
|
func textColumnMaxWidth() float32 { return textWidth(strings.Repeat("0", 30)) + cellPadding() }
|
||||||
|
|
||||||
|
// textColumnWidth measures the widest of samples so a table column can be
|
||||||
|
// sized to fit its content, clamped to [min, max]. Fyne tables do not
|
||||||
|
// auto-size columns, so without this a fixed width clips values like
|
||||||
|
// "20260601-100000_SomeJobName.log" in the Log column.
|
||||||
|
func textColumnWidth(samples []string, min, max float32) float32 {
|
||||||
|
width := min
|
||||||
|
for _, text := range samples {
|
||||||
if text == "" {
|
if text == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
w := fyne.MeasureText(text, theme.TextSize(), fyne.TextStyle{}).Width + logColumnPadding
|
if w := textWidth(text) + cellPadding(); w > width {
|
||||||
if w > width {
|
|
||||||
width = w
|
width = w
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if width > logColumnMaxWidth {
|
if width > max {
|
||||||
width = logColumnMaxWidth
|
width = max
|
||||||
}
|
}
|
||||||
return width
|
return width
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// historyTriggerSamples is the closed set of Trigger values History ever
|
||||||
|
// shows (see newEvent and app.operations.go/app.run.go, which produce "UI",
|
||||||
|
// "Manual" and "Schedule"; historyCellText falls back to "Unknown"). Add a new
|
||||||
|
// trigger here too if one is introduced there, or the column may clip it.
|
||||||
|
var historyTriggerSamples = []string{"Schedule", "Manual", "UI", "Unknown"}
|
||||||
|
|
||||||
|
// historyStateSamples is the closed set of State values History ever shows:
|
||||||
|
// "OK" and "Failed" come from runner.RunJob (runStateDetail/startJobOnly);
|
||||||
|
// "Started", "Error" and "Jobs loaded" are recorded directly in mainwindow.go.
|
||||||
|
// Add a new state here too if one is introduced in either place.
|
||||||
|
var historyStateSamples = []string{"OK", "Failed", "Started", "Error", "Jobs loaded"}
|
||||||
|
|
||||||
|
// historyTimeSample is the rendered form of the timestamp layout every event
|
||||||
|
// uses (see newEvent), so the Time column needs no content scan: its width is
|
||||||
|
// fixed by the format string.
|
||||||
|
const historyTimeSample = "2026-01-02 15:04:05"
|
||||||
|
|
||||||
|
// historyColumnWidths computes every column's width from the current sorted
|
||||||
|
// rows. Time, Trigger and State are fixed-shape or closed-set columns; Job,
|
||||||
|
// Detail and Log are free text, so their width tracks the values actually
|
||||||
|
// present, bounded the same way the Log column always was.
|
||||||
|
func historyColumnWidths(rows []event) [6]float32 {
|
||||||
|
jobNames := make([]string, 0, len(rows))
|
||||||
|
details := make([]string, 0, len(rows))
|
||||||
|
logNames := make([]string, 0, len(rows))
|
||||||
|
for _, current := range rows {
|
||||||
|
jobNames = append(jobNames, current.JobName)
|
||||||
|
details = append(details, current.Detail)
|
||||||
|
logNames = append(logNames, logFileName(current.LogFile))
|
||||||
|
}
|
||||||
|
min, max := textColumnMinWidth(), textColumnMaxWidth()
|
||||||
|
return [6]float32{
|
||||||
|
textWidth(historyTimeSample) + cellPadding(),
|
||||||
|
textColumnWidth(historyTriggerSamples, min, max),
|
||||||
|
textColumnWidth(jobNames, min, max),
|
||||||
|
textColumnWidth(historyStateSamples, min, max),
|
||||||
|
textColumnWidth(details, min, max),
|
||||||
|
textColumnWidth(logNames, min, max),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// historyHeader is a bold tappable label used in the History table header row.
|
// historyHeader is a bold tappable label used in the History table header row.
|
||||||
// In Fyne 2.7+ OnSelected is not fired for header cells (Row < 0), so the sort
|
// In Fyne 2.7+ OnSelected is not fired for header cells (Row < 0), so the sort
|
||||||
// toggle is wired through the Tappable interface instead.
|
// toggle is wired through the Tappable interface instead.
|
||||||
@@ -85,7 +133,7 @@ type historyHeader struct {
|
|||||||
func newHistoryHeader() *historyHeader {
|
func newHistoryHeader() *historyHeader {
|
||||||
h := &historyHeader{label: widget.NewLabel("")}
|
h := &historyHeader{label: widget.NewLabel("")}
|
||||||
h.label.TextStyle = fyne.TextStyle{Bold: true}
|
h.label.TextStyle = fyne.TextStyle{Bold: true}
|
||||||
h.label.Wrapping = fyne.TextTruncate
|
h.label.Truncation = fyne.TextTruncateClip
|
||||||
h.ExtendBaseWidget(h)
|
h.ExtendBaseWidget(h)
|
||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
@@ -104,46 +152,54 @@ func (h *historyHeader) SetText(text string) {
|
|||||||
h.label.SetText(text)
|
h.label.SetText(text)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// historyHeaders are the History table's column captions, in column order. The
|
||||||
|
// Time caption is built per update because it carries the sort direction arrow.
|
||||||
|
var historyHeaders = [...]string{"Time", "Trigger", "Job", "State", "Detail", "Log"}
|
||||||
|
|
||||||
func newHistoryView(events *[]event) (*fyne.Container, func()) {
|
func newHistoryView(events *[]event) (*fyne.Container, func()) {
|
||||||
descending := false
|
descending := false
|
||||||
headerText := func(id widget.TableCellID) string {
|
headerText := func(id widget.TableCellID) string {
|
||||||
headers := []string{"Time", "Trigger", "Job", "State", "Detail", "Log"}
|
|
||||||
if id.Row < 0 && id.Col == 0 {
|
if id.Row < 0 && id.Col == 0 {
|
||||||
if descending {
|
if descending {
|
||||||
return "Time ▼"
|
return "Time ▼"
|
||||||
}
|
}
|
||||||
return "Time ▲"
|
return "Time ▲"
|
||||||
}
|
}
|
||||||
if id.Row < 0 && id.Col >= 0 && id.Col < len(headers) {
|
if id.Row < 0 && id.Col >= 0 && id.Col < len(historyHeaders) {
|
||||||
return headers[id.Col]
|
return historyHeaders[id.Col]
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
sortedEvents := func() []event {
|
|
||||||
result := append([]event(nil), (*events)...)
|
// rows is the sorted snapshot every callback below reads — both the length
|
||||||
sort.SliceStable(result, func(left int, right int) bool {
|
// callback and the cells, which must agree on the same slice. A full redraw
|
||||||
|
// issues one update call per visible cell, so sorting inside the cell
|
||||||
|
// callback re-sorted the whole event list a hundred times per Refresh.
|
||||||
|
// resort() is therefore the only place the order changes, and it runs once
|
||||||
|
// per redraw: at build time, on a sort toggle, and from refresh().
|
||||||
|
var rows []event
|
||||||
|
resort := func() {
|
||||||
|
rows = append(rows[:0], (*events)...)
|
||||||
|
sort.SliceStable(rows, func(left int, right int) bool {
|
||||||
if descending {
|
if descending {
|
||||||
return result[left].Time > result[right].Time
|
return rows[left].Time > rows[right].Time
|
||||||
}
|
}
|
||||||
return result[left].Time < result[right].Time
|
return rows[left].Time < rows[right].Time
|
||||||
})
|
})
|
||||||
return result
|
|
||||||
}
|
}
|
||||||
|
resort()
|
||||||
|
|
||||||
table := widget.NewTable(
|
table := widget.NewTable(
|
||||||
func() (int, int) {
|
func() (int, int) {
|
||||||
return len(*events), 6
|
return len(rows), len(historyHeaders)
|
||||||
},
|
},
|
||||||
func() fyne.CanvasObject {
|
func() fyne.CanvasObject {
|
||||||
label := widget.NewLabel("")
|
label := widget.NewLabel("")
|
||||||
label.Wrapping = fyne.TextTruncate
|
label.Truncation = fyne.TextTruncateClip
|
||||||
return label
|
return label
|
||||||
},
|
},
|
||||||
func(id widget.TableCellID, item fyne.CanvasObject) {
|
func(id widget.TableCellID, item fyne.CanvasObject) {
|
||||||
label := item.(*widget.Label)
|
item.(*widget.Label).SetText(historyCellText(id, rows))
|
||||||
label.SetText(historyCellText(id, sortedEvents()))
|
|
||||||
label.TextStyle = fyne.TextStyle{}
|
|
||||||
label.Refresh()
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
table.ShowHeaderRow = true
|
table.ShowHeaderRow = true
|
||||||
@@ -156,6 +212,7 @@ func newHistoryView(events *[]event) (*fyne.Container, func()) {
|
|||||||
if id.Row < 0 && id.Col == 0 {
|
if id.Row < 0 && id.Col == 0 {
|
||||||
h.OnTapped = func() {
|
h.OnTapped = func() {
|
||||||
descending = !descending
|
descending = !descending
|
||||||
|
resort()
|
||||||
table.Refresh()
|
table.Refresh()
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -166,18 +223,20 @@ func newHistoryView(events *[]event) (*fyne.Container, func()) {
|
|||||||
table.OnSelected = func(id widget.TableCellID) {
|
table.OnSelected = func(id widget.TableCellID) {
|
||||||
table.Unselect(id)
|
table.Unselect(id)
|
||||||
}
|
}
|
||||||
table.SetColumnWidth(0, 150)
|
setColumnWidths := func() {
|
||||||
table.SetColumnWidth(1, 90)
|
for col, width := range historyColumnWidths(rows) {
|
||||||
table.SetColumnWidth(2, 170)
|
table.SetColumnWidth(col, width)
|
||||||
table.SetColumnWidth(3, 90)
|
}
|
||||||
table.SetColumnWidth(4, 260)
|
}
|
||||||
table.SetColumnWidth(5, logColumnWidth(*events))
|
setColumnWidths()
|
||||||
|
|
||||||
// refresh recomputes the content-fit Log column width before redrawing, so
|
// refresh re-reads the event list into the sorted snapshot and recomputes
|
||||||
// newly recorded events with longer file names widen the column instead of
|
// every content-fit column width before redrawing, so newly recorded events
|
||||||
// being truncated.
|
// appear in the current sort order and longer values widen their column
|
||||||
|
// instead of being truncated.
|
||||||
refresh := func() {
|
refresh := func() {
|
||||||
table.SetColumnWidth(5, logColumnWidth(*events))
|
resort()
|
||||||
|
setColumnWidths()
|
||||||
table.Refresh()
|
table.Refresh()
|
||||||
}
|
}
|
||||||
return container.NewPadded(table), refresh
|
return container.NewPadded(table), refresh
|
||||||
|
|||||||
@@ -0,0 +1,303 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
||||||
|
|
||||||
|
"fyne.io/fyne/v2"
|
||||||
|
"fyne.io/fyne/v2/test"
|
||||||
|
"fyne.io/fyne/v2/widget"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLastJobLogsCapsAndCopies(t *testing.T) {
|
||||||
|
logs := []event{
|
||||||
|
{Time: "1", JobName: "a"},
|
||||||
|
{Time: "2", JobName: "b"},
|
||||||
|
{Time: "3", JobName: "c"},
|
||||||
|
{Time: "4", JobName: "d"},
|
||||||
|
}
|
||||||
|
got := lastJobLogs(logs)
|
||||||
|
if len(got) != maxJobActivityRows {
|
||||||
|
t.Fatalf("len = %d, want %d", len(got), maxJobActivityRows)
|
||||||
|
}
|
||||||
|
for i, want := range []string{"1", "2", "3"} {
|
||||||
|
if got[i].Time != want {
|
||||||
|
t.Errorf("got[%d].Time = %q, want %q", i, got[i].Time, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
logs[0].Time = "mutated"
|
||||||
|
if got[0].Time == "mutated" {
|
||||||
|
t.Error("lastJobLogs must return a defensive copy")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLastJobLogsEmpty(t *testing.T) {
|
||||||
|
if got := lastJobLogs(nil); len(got) != 0 {
|
||||||
|
t.Errorf("nil input: got %v, want empty", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIndexOfID(t *testing.T) {
|
||||||
|
jobs := []job{
|
||||||
|
{ID: 10, Name: "A"},
|
||||||
|
{ID: 20, Name: "B"},
|
||||||
|
}
|
||||||
|
if got := indexOfID(jobs, 20); got != 1 {
|
||||||
|
t.Errorf("found: got %d, want 1", got)
|
||||||
|
}
|
||||||
|
if got := indexOfID(jobs, 99); got != -1 {
|
||||||
|
t.Errorf("missing: got %d, want -1", got)
|
||||||
|
}
|
||||||
|
if got := indexOfID(nil, 1); got != -1 {
|
||||||
|
t.Errorf("empty slice: got %d, want -1", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCollectActivityMergesAndSorts(t *testing.T) {
|
||||||
|
jobs := []job{
|
||||||
|
{ID: 1, Name: "A"},
|
||||||
|
{ID: 2, Name: "B"},
|
||||||
|
}
|
||||||
|
runtimes := map[int]*domain.JobRuntime{
|
||||||
|
1: {Logs: []domain.RunRecord{{Time: "2026-01-02 10:00:00", JobID: 1}}},
|
||||||
|
2: {Logs: []domain.RunRecord{{Time: "2026-01-01 09:00:00", JobID: 2}}},
|
||||||
|
}
|
||||||
|
got := collectActivity(jobs, runtimes)
|
||||||
|
if len(got) != 2 {
|
||||||
|
t.Fatalf("len = %d, want 2", len(got))
|
||||||
|
}
|
||||||
|
if got[0].Time != "2026-01-01 09:00:00" || got[1].Time != "2026-01-02 10:00:00" {
|
||||||
|
t.Errorf("sort order = %v, want ascending by Time", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCollectActivitySkipsMissingRuntimes(t *testing.T) {
|
||||||
|
jobs := []job{{ID: 1, Name: "A"}}
|
||||||
|
if got := collectActivity(jobs, nil); len(got) != 0 {
|
||||||
|
t.Errorf("nil runtimes: got %v, want empty", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHistoryCellText(t *testing.T) {
|
||||||
|
events := []event{{
|
||||||
|
Time: "2026-06-01 12:00:00",
|
||||||
|
Trigger: "",
|
||||||
|
JobName: "Job",
|
||||||
|
State: "OK",
|
||||||
|
Detail: "done",
|
||||||
|
LogFile: `/logs/20260601-120000_Job.log`,
|
||||||
|
}}
|
||||||
|
cases := []struct {
|
||||||
|
col int
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{0, "2026-06-01 12:00:00"},
|
||||||
|
{1, "Unknown"},
|
||||||
|
{2, "Job"},
|
||||||
|
{3, "OK"},
|
||||||
|
{4, "done"},
|
||||||
|
{5, "20260601-120000_Job.log"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
got := historyCellText(widget.TableCellID{Row: 0, Col: tc.col}, events)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("col %d: got %q, want %q", tc.col, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := historyCellText(widget.TableCellID{Row: -1, Col: 0}, events); got != "" {
|
||||||
|
t.Errorf("header row: got %q, want empty", got)
|
||||||
|
}
|
||||||
|
if got := historyCellText(widget.TableCellID{Row: 99, Col: 0}, events); got != "" {
|
||||||
|
t.Errorf("out of range row: got %q, want empty", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogFileName(t *testing.T) {
|
||||||
|
cases := []struct{ path, want string }{
|
||||||
|
{"", ""},
|
||||||
|
{" ", ""},
|
||||||
|
{`C:\logs\run.log`, "run.log"},
|
||||||
|
{"/var/logs/2026/job.log", "job.log"},
|
||||||
|
{"plain.log", "plain.log"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if got := logFileName(tc.path); got != tc.want {
|
||||||
|
t.Errorf("logFileName(%q) = %q, want %q", tc.path, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestHistorySortToggleKeepsRowsInSync is the regression guard for F11: the
|
||||||
|
// table now reads one cached sorted snapshot instead of re-sorting inside every
|
||||||
|
// cell callback, so the length callback and the cells have to be refilled
|
||||||
|
// together. If either the sort toggle or refresh stops calling resort(), the
|
||||||
|
// row count and the cell contents disagree — which no compiler check catches.
|
||||||
|
func TestHistorySortToggleKeepsRowsInSync(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
events := []event{
|
||||||
|
{Time: "2026-06-01 10:00:00", JobName: "A"},
|
||||||
|
{Time: "2026-06-01 11:00:00", JobName: "B"},
|
||||||
|
{Time: "2026-06-01 12:00:00", JobName: "C"},
|
||||||
|
}
|
||||||
|
content, refresh := newHistoryView(&events)
|
||||||
|
table, ok := content.Objects[0].(*widget.Table)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("history view does not wrap a table")
|
||||||
|
}
|
||||||
|
|
||||||
|
rowCount := func() int {
|
||||||
|
t.Helper()
|
||||||
|
rows, cols := table.Length()
|
||||||
|
if cols != len(historyHeaders) {
|
||||||
|
t.Errorf("column count = %d, want %d", cols, len(historyHeaders))
|
||||||
|
}
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
// Column 2 is the Job name, the field these fixtures vary.
|
||||||
|
jobAt := func(row int) string {
|
||||||
|
t.Helper()
|
||||||
|
cell := table.CreateCell()
|
||||||
|
table.UpdateCell(widget.TableCellID{Row: row, Col: 2}, cell)
|
||||||
|
return cell.(*widget.Label).Text
|
||||||
|
}
|
||||||
|
// The sort toggle lives on the Time header cell, which is only wired up
|
||||||
|
// when UpdateHeader runs for it.
|
||||||
|
header := table.CreateHeader()
|
||||||
|
table.UpdateHeader(widget.TableCellID{Row: -1, Col: 0}, header)
|
||||||
|
timeHeader, ok := header.(*historyHeader)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("history table header is not a historyHeader")
|
||||||
|
}
|
||||||
|
assertOrder := func(when string, want ...string) {
|
||||||
|
t.Helper()
|
||||||
|
if got := rowCount(); got != len(want) {
|
||||||
|
t.Fatalf("%s: row count = %d, want %d", when, got, len(want))
|
||||||
|
}
|
||||||
|
for row, name := range want {
|
||||||
|
if got := jobAt(row); got != name {
|
||||||
|
t.Errorf("%s: row %d = %q, want %q", when, row, got, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertOrder("ascending", "A", "B", "C")
|
||||||
|
|
||||||
|
test.Tap(timeHeader)
|
||||||
|
assertOrder("descending", "C", "B", "A")
|
||||||
|
|
||||||
|
// A new run arrives while the table is sorted newest-first: it must be
|
||||||
|
// counted and placed in the order currently on screen, not the build-time one.
|
||||||
|
events = append(events, event{Time: "2026-06-01 13:00:00", JobName: "D"})
|
||||||
|
refresh()
|
||||||
|
assertOrder("descending after refresh", "D", "C", "B", "A")
|
||||||
|
|
||||||
|
test.Tap(timeHeader)
|
||||||
|
assertOrder("ascending after refresh", "A", "B", "C", "D")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestHistoryCellTemplateIsPlainText guards the dropped per-cell TextStyle
|
||||||
|
// assignment: the template must already carry the zero style, since nothing
|
||||||
|
// resets it any more.
|
||||||
|
func TestHistoryCellTemplateIsPlainText(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
var events []event
|
||||||
|
content, _ := newHistoryView(&events)
|
||||||
|
table := content.Objects[0].(*widget.Table)
|
||||||
|
label, ok := table.CreateCell().(*widget.Label)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("history cell template is not a label")
|
||||||
|
}
|
||||||
|
if label.TextStyle != (fyne.TextStyle{}) {
|
||||||
|
t.Errorf("cell template TextStyle = %+v, want the zero value", label.TextStyle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTextColumnWidthClamps covers the three shapes textColumnWidth has to
|
||||||
|
// handle: a sample narrower than min, one that lands between the bounds, and
|
||||||
|
// one wide enough to hit the max cap.
|
||||||
|
func TestTextColumnWidthClamps(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
min, max := float32(50), float32(120)
|
||||||
|
if got := textColumnWidth([]string{"x"}, min, max); got != min {
|
||||||
|
t.Errorf("below-min sample: got %v, want the floor %v", got, min)
|
||||||
|
}
|
||||||
|
inRange := textWidth("mid-sized value") + cellPadding()
|
||||||
|
if inRange <= min || inRange >= max {
|
||||||
|
t.Skip("fixture sample no longer lands strictly between the bounds under this theme")
|
||||||
|
}
|
||||||
|
if got := textColumnWidth([]string{"mid-sized value"}, min, max); got != inRange {
|
||||||
|
t.Errorf("in-range sample: got %v, want %v", got, inRange)
|
||||||
|
}
|
||||||
|
if got := textColumnWidth([]string{strings.Repeat("0", 200)}, min, max); got != max {
|
||||||
|
t.Errorf("above-max sample: got %v, want the cap %v", got, max)
|
||||||
|
}
|
||||||
|
if got := textColumnWidth(nil, min, max); got != min {
|
||||||
|
t.Errorf("no samples: got %v, want the floor %v", got, min)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestHistoryColumnsFitTheirContent guards F6/F14: every column must be at
|
||||||
|
// least as wide as its widest known or actually-present value, at the default
|
||||||
|
// theme and at a scaled one, so nothing that used to be a pixel constant
|
||||||
|
// clips again.
|
||||||
|
func TestHistoryColumnsFitTheirContent(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
rows := []event{
|
||||||
|
{
|
||||||
|
Time: "2026-06-01 12:00:00",
|
||||||
|
Trigger: "Schedule",
|
||||||
|
JobName: "A moderately long job name for width testing",
|
||||||
|
State: "Jobs loaded",
|
||||||
|
Detail: "A somewhat longer detail message describing what happened",
|
||||||
|
LogFile: `/logs/20260601-120000_SomeJobName.log`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
check := func(when string) {
|
||||||
|
t.Helper()
|
||||||
|
widths := historyColumnWidths(rows)
|
||||||
|
samples := [][]string{
|
||||||
|
{historyTimeSample},
|
||||||
|
historyTriggerSamples,
|
||||||
|
{rows[0].JobName},
|
||||||
|
historyStateSamples,
|
||||||
|
{rows[0].Detail},
|
||||||
|
{logFileName(rows[0].LogFile)},
|
||||||
|
}
|
||||||
|
min, max := textColumnMinWidth(), textColumnMaxWidth()
|
||||||
|
for col, colSamples := range samples {
|
||||||
|
want := textColumnWidth(colSamples, min, max)
|
||||||
|
if col == 0 {
|
||||||
|
want = textWidth(historyTimeSample) + cellPadding()
|
||||||
|
}
|
||||||
|
if widths[col] < want {
|
||||||
|
t.Errorf("%s: column %d width = %v, want at least %v", when, col, widths[col], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
check("default theme")
|
||||||
|
testApp.Settings().SetTheme(test.NewTheme())
|
||||||
|
check("scaled theme")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewEventUsesConsistentTimestampShape(t *testing.T) {
|
||||||
|
ev := newEvent(1, "Job", "OK", "detail")
|
||||||
|
if _, err := time.Parse("2006-01-02 15:04:05", ev.Time); err != nil {
|
||||||
|
t.Errorf("timestamp %q is not in expected layout: %v", ev.Time, err)
|
||||||
|
}
|
||||||
|
if ev.Trigger != "UI" || ev.JobID != 1 || ev.JobName != "Job" {
|
||||||
|
t.Errorf("unexpected event fields: %+v", ev)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package ui
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
||||||
@@ -34,11 +35,13 @@ func showJobDialog(w fyne.Window, title string, current job, onSave func(job)) {
|
|||||||
commandEntry.SetPlaceHolder(`C:\Program Files\App\App.exe`)
|
commandEntry.SetPlaceHolder(`C:\Program Files\App\App.exe`)
|
||||||
commandEntry.SetText(current.Command)
|
commandEntry.SetText(current.Command)
|
||||||
commandBrowse := widget.NewButtonWithIcon("Browse", theme.FolderOpenIcon(), func() {
|
commandBrowse := widget.NewButtonWithIcon("Browse", theme.FolderOpenIcon(), func() {
|
||||||
chooseFile(w, commandEntry)
|
chooseFile(w, commandEntry, nil)
|
||||||
})
|
})
|
||||||
commandRow := container.NewBorder(nil, nil, nil, commandBrowse, commandEntry)
|
commandRow := container.NewBorder(nil, nil, nil, commandBrowse, commandEntry)
|
||||||
argumentsEntry := widget.NewMultiLineEntry()
|
argumentsEntry := widget.NewMultiLineEntry()
|
||||||
argumentsEntry.SetPlaceHolder(`D:\Local\Jobs\Auto.ffs_batch`)
|
// One argument per line is the whole point of the field: each line is passed
|
||||||
|
// to the process verbatim, so paths with spaces need no quoting.
|
||||||
|
argumentsEntry.SetPlaceHolder("One argument per line, no quotes:\n--input\n" + `C:\Data\My Files\input.txt`)
|
||||||
argumentsEntry.SetText(current.Arguments)
|
argumentsEntry.SetText(current.Arguments)
|
||||||
startOnly := widget.NewCheck("Start only, do not wait for exit", nil)
|
startOnly := widget.NewCheck("Start only, do not wait for exit", nil)
|
||||||
startOnly.SetChecked(current.StartOnly)
|
startOnly.SetChecked(current.StartOnly)
|
||||||
@@ -53,6 +56,11 @@ func showJobDialog(w fyne.Window, title string, current job, onSave func(job)) {
|
|||||||
overlapSelected = current.OverlapPolicy
|
overlapSelected = current.OverlapPolicy
|
||||||
}
|
}
|
||||||
overlapSelect.SetSelected(overlapSelected)
|
overlapSelect.SetSelected(overlapSelected)
|
||||||
|
timeoutEntry := widget.NewEntry()
|
||||||
|
timeoutEntry.SetPlaceHolder("Empty = global default, 0 = no timeout")
|
||||||
|
if current.TimeoutSeconds != nil {
|
||||||
|
timeoutEntry.SetText(strconv.Itoa(*current.TimeoutSeconds))
|
||||||
|
}
|
||||||
|
|
||||||
form := dialog.NewForm(
|
form := dialog.NewForm(
|
||||||
title,
|
title,
|
||||||
@@ -66,6 +74,7 @@ func showJobDialog(w fyne.Window, title string, current job, onSave func(job)) {
|
|||||||
widget.NewFormItem("Arguments", argumentsEntry),
|
widget.NewFormItem("Arguments", argumentsEntry),
|
||||||
widget.NewFormItem("", startOnly),
|
widget.NewFormItem("", startOnly),
|
||||||
widget.NewFormItem("Overlap policy", overlapSelect),
|
widget.NewFormItem("Overlap policy", overlapSelect),
|
||||||
|
widget.NewFormItem("Timeout (s)", timeoutEntry),
|
||||||
widget.NewFormItem("", enabled),
|
widget.NewFormItem("", enabled),
|
||||||
},
|
},
|
||||||
func(saved bool) {
|
func(saved bool) {
|
||||||
@@ -82,6 +91,18 @@ func showJobDialog(w fyne.Window, title string, current job, onSave func(job)) {
|
|||||||
dialog.ShowError(fmt.Errorf("invalid schedule: %w", err), w)
|
dialog.ShowError(fmt.Errorf("invalid schedule: %w", err), w)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// An empty timeout inherits the global default (nil); an explicit 0
|
||||||
|
// means "no timeout" and does not inherit; anything else must be a
|
||||||
|
// positive whole number of seconds.
|
||||||
|
var timeoutSeconds *int
|
||||||
|
if trimmed := strings.TrimSpace(timeoutEntry.Text); trimmed != "" {
|
||||||
|
parsed, err := strconv.Atoi(trimmed)
|
||||||
|
if err != nil || parsed < 0 {
|
||||||
|
dialog.ShowError(fmt.Errorf("timeout must be 0 (no timeout) or a positive number of seconds, or empty to use the global default"), w)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
timeoutSeconds = domain.TimeoutSecondsPtr(parsed)
|
||||||
|
}
|
||||||
current.Name = strings.TrimSpace(name.Text)
|
current.Name = strings.TrimSpace(name.Text)
|
||||||
current.Folder = strings.TrimSpace(folderEntry.Text)
|
current.Folder = strings.TrimSpace(folderEntry.Text)
|
||||||
current.Schedule = strings.TrimSpace(scheduleEntry.Text)
|
current.Schedule = strings.TrimSpace(scheduleEntry.Text)
|
||||||
@@ -93,6 +114,7 @@ func showJobDialog(w fyne.Window, title string, current job, onSave func(job)) {
|
|||||||
if current.OverlapPolicy == overlapPolicyInherit {
|
if current.OverlapPolicy == overlapPolicyInherit {
|
||||||
current.OverlapPolicy = ""
|
current.OverlapPolicy = ""
|
||||||
}
|
}
|
||||||
|
current.TimeoutSeconds = timeoutSeconds
|
||||||
// The dialog only edits durable configuration. Runtime status is
|
// The dialog only edits durable configuration. Runtime status is
|
||||||
// initialized (new jobs) or updated (edits) by the caller against the
|
// initialized (new jobs) or updated (edits) by the caller against the
|
||||||
// runtime map, keyed by job ID.
|
// runtime map, keyed by job ID.
|
||||||
@@ -100,6 +122,6 @@ func showJobDialog(w fyne.Window, title string, current job, onSave func(job)) {
|
|||||||
},
|
},
|
||||||
w,
|
w,
|
||||||
)
|
)
|
||||||
form.Resize(fyne.NewSize(640, 460))
|
form.Resize(fyne.NewSize(640, 500))
|
||||||
form.Show()
|
form.Show()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,24 +16,12 @@ import (
|
|||||||
|
|
||||||
const allFolders = "All"
|
const allFolders = "All"
|
||||||
const noFolder = "No folder"
|
const noFolder = "No folder"
|
||||||
const minJobsSidebarWidth float32 = 400
|
|
||||||
|
|
||||||
// maxJobActivityRows caps the "Selected job activity" panel to the most recent
|
// maxJobActivityRows caps the "Selected job activity" panel to the most recent
|
||||||
// entries. The full per-job history (up to maxJobLogs) remains in the History
|
// entries. The full per-job history (up to maxJobLogs) remains in the History
|
||||||
// view; this panel is a quick at-a-glance summary anchored below the output.
|
// view; this panel is a quick at-a-glance summary anchored below the output.
|
||||||
const maxJobActivityRows = 3
|
const maxJobActivityRows = 3
|
||||||
|
|
||||||
// detailRowSpacing is the (negative) gap applied between metadata rows in the
|
|
||||||
// details panel. Pulling rows together overlaps the labels' built-in vertical
|
|
||||||
// padding, tightening the block so it fits comfortably on 720p screens.
|
|
||||||
const detailRowSpacing float32 = -8
|
|
||||||
|
|
||||||
// jobRowSpacing is the (negative) gap between the name, metadata, and status
|
|
||||||
// lines within each job list row. Like the details panel, it overlaps the
|
|
||||||
// labels' built-in vertical padding so each row reads as one compact block and
|
|
||||||
// more jobs are visible without scrolling.
|
|
||||||
const jobRowSpacing float32 = -8
|
|
||||||
|
|
||||||
// newJobsView builds the Jobs tab: list sidebar, details panel, and toolbar.
|
// newJobsView builds the Jobs tab: list sidebar, details panel, and toolbar.
|
||||||
// It returns the assembled panel and a refresh function the caller invokes
|
// It returns the assembled panel and a refresh function the caller invokes
|
||||||
// whenever the service state may have changed (e.g., from the event subscriber
|
// whenever the service state may have changed (e.g., from the event subscriber
|
||||||
@@ -65,11 +53,20 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
selected := 0
|
selected := 0
|
||||||
|
if len(jobs) == 0 {
|
||||||
|
selected = -1
|
||||||
|
}
|
||||||
selectedFolder := allFolders
|
selectedFolder := allFolders
|
||||||
schedulerPaused := svc.Store().Config.Paused
|
schedulerPaused := svc.Store().Config.Paused
|
||||||
|
listView := svc.Store().Config.JobListView
|
||||||
filteredJobs := filteredJobIndexes(jobs, selectedFolder)
|
filteredJobs := filteredJobIndexes(jobs, selectedFolder)
|
||||||
|
|
||||||
dp := newDetailsPanel(jobs[selected], runtimeFor(selected), svc.Store().Config.OverlapPolicy)
|
dp := newDetailsPanel(job{}, &domain.JobRuntime{}, svc.Store().Config.OverlapPolicy, svc.Store().Config.DefaultTimeoutSeconds)
|
||||||
|
if selected >= 0 {
|
||||||
|
dp.update(jobs[selected], runtimeFor(selected), svc.Store().Config.OverlapPolicy, svc.Store().Config.DefaultTimeoutSeconds)
|
||||||
|
} else {
|
||||||
|
dp.clear()
|
||||||
|
}
|
||||||
|
|
||||||
updateDetails := func(index int) {
|
updateDetails := func(index int) {
|
||||||
if index < 0 || index >= len(jobs) {
|
if index < 0 || index >= len(jobs) {
|
||||||
@@ -79,7 +76,7 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
selected = index
|
selected = index
|
||||||
dp.update(jobs[selected], runtimeFor(selected), svc.Store().Config.OverlapPolicy)
|
dp.update(jobs[selected], runtimeFor(selected), svc.Store().Config.OverlapPolicy, svc.Store().Config.DefaultTimeoutSeconds)
|
||||||
}
|
}
|
||||||
|
|
||||||
// list and folderSelect are declared early so closures below can reference
|
// list and folderSelect are declared early so closures below can reference
|
||||||
@@ -97,17 +94,45 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// applyRowMode expresses the current view mode as visibility on the row's
|
||||||
|
// four labels. widget.List caches the row template's MinSize, and
|
||||||
|
// list.Refresh() re-creates the template and recomputes it, so hiding lines
|
||||||
|
// is what actually shrinks the rows: layout.NewCustomPaddedVBoxLayout and the
|
||||||
|
// border layout both skip hidden children when measuring.
|
||||||
|
applyRowMode := func(inlineStatus, meta, status fyne.CanvasObject) {
|
||||||
|
if listView.IsCompact() {
|
||||||
|
inlineStatus.Show()
|
||||||
|
meta.Hide()
|
||||||
|
status.Hide()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
inlineStatus.Hide()
|
||||||
|
meta.Show()
|
||||||
|
status.Show()
|
||||||
|
}
|
||||||
|
|
||||||
list = widget.NewList(
|
list = widget.NewList(
|
||||||
func() int { return len(filteredJobs) },
|
func() int { return len(filteredJobs) },
|
||||||
func() fyne.CanvasObject {
|
func() fyne.CanvasObject {
|
||||||
name := widget.NewLabelWithStyle("Job name", fyne.TextAlignLeading, fyne.TextStyle{Bold: true})
|
name := widget.NewLabelWithStyle("Job name", fyne.TextAlignLeading, fyne.TextStyle{Bold: true})
|
||||||
|
// Truncating stops a long name from pushing the compact row's status
|
||||||
|
// off the right-hand edge. Labels default to TextWrapOff, which grows
|
||||||
|
// the widget to fit instead.
|
||||||
|
name.Truncation = fyne.TextTruncateClip
|
||||||
|
inlineStatus := widget.NewLabel("status")
|
||||||
meta := widget.NewLabel("schedule")
|
meta := widget.NewLabel("schedule")
|
||||||
status := widget.NewLabel("status")
|
status := widget.NewLabel("status")
|
||||||
return container.New(compactVBoxLayout{spacing: jobRowSpacing}, name, meta, status)
|
applyRowMode(inlineStatus, meta, status)
|
||||||
|
nameLine := container.NewBorder(nil, nil, nil, inlineStatus, name)
|
||||||
|
return container.New(layout.NewCustomPaddedVBoxLayout(rowOverlap()), nameLine, meta, status)
|
||||||
},
|
},
|
||||||
func(id widget.ListItemID, item fyne.CanvasObject) {
|
func(id widget.ListItemID, item fyne.CanvasObject) {
|
||||||
row := item.(*fyne.Container)
|
row := item.(*fyne.Container)
|
||||||
name := row.Objects[0].(*widget.Label)
|
// NewBorder keeps the center object first and appends the border slots
|
||||||
|
// after it, so nameLine is [name, inlineStatus].
|
||||||
|
nameLine := row.Objects[0].(*fyne.Container)
|
||||||
|
name := nameLine.Objects[0].(*widget.Label)
|
||||||
|
inlineStatus := nameLine.Objects[1].(*widget.Label)
|
||||||
meta := row.Objects[1].(*widget.Label)
|
meta := row.Objects[1].(*widget.Label)
|
||||||
status := row.Objects[2].(*widget.Label)
|
status := row.Objects[2].(*widget.Label)
|
||||||
|
|
||||||
@@ -116,7 +141,12 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
// Keep each row compact: folder, schedule, and command are shown in one
|
// Keep each row compact: folder, schedule, and command are shown in one
|
||||||
// metadata line so the left pane stays useful even with many jobs.
|
// metadata line so the left pane stays useful even with many jobs.
|
||||||
meta.SetText(app.DisplayFolder(current.Folder) + " " + current.Schedule + " " + app.DisplayInvocation(current))
|
meta.SetText(app.DisplayFolder(current.Folder) + " " + current.Schedule + " " + app.DisplayInvocation(current))
|
||||||
status.SetText(app.StatusText(current, runtimes[current.ID]))
|
statusText := app.StatusText(current, runtimes[current.ID])
|
||||||
|
status.SetText(statusText)
|
||||||
|
inlineStatus.SetText(statusText)
|
||||||
|
// A full Refresh reuses rows built under the previous mode, so
|
||||||
|
// visibility cannot be left to the create callback alone.
|
||||||
|
applyRowMode(inlineStatus, meta, status)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
list.OnSelected = func(id widget.ListItemID) {
|
list.OnSelected = func(id widget.ListItemID) {
|
||||||
@@ -126,7 +156,9 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
}
|
}
|
||||||
updateDetails(filteredJobs[id])
|
updateDetails(filteredJobs[id])
|
||||||
}
|
}
|
||||||
list.Select(selected)
|
if len(filteredJobs) > 0 && selected >= 0 {
|
||||||
|
list.Select(app.DisplayIndex(filteredJobs, selected))
|
||||||
|
}
|
||||||
|
|
||||||
folderSelect = widget.NewSelect(folderOptions(jobs), func(value string) {
|
folderSelect = widget.NewSelect(folderOptions(jobs), func(value string) {
|
||||||
if value == "" {
|
if value == "" {
|
||||||
@@ -134,12 +166,14 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
}
|
}
|
||||||
selectedFolder = value
|
selectedFolder = value
|
||||||
filteredJobs = filteredJobIndexes(jobs, selectedFolder)
|
filteredJobs = filteredJobIndexes(jobs, selectedFolder)
|
||||||
list.Refresh()
|
|
||||||
if len(filteredJobs) == 0 {
|
if len(filteredJobs) == 0 {
|
||||||
// The "No folder" filter is intentionally allowed to be empty. It is a
|
// The "No folder" filter is intentionally allowed to be empty. It is a
|
||||||
// real filter choice, not an error state, so the selection is cleared.
|
// real filter choice, not an error state, so the selection is cleared.
|
||||||
|
// This path returns without reaching refreshView(), so it is the one
|
||||||
|
// place the list has to be redrawn by hand.
|
||||||
selected = -1
|
selected = -1
|
||||||
updateDetails(-1)
|
updateDetails(-1)
|
||||||
|
list.Refresh()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
selected = filteredJobs[0]
|
selected = filteredJobs[0]
|
||||||
@@ -148,6 +182,32 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
})
|
})
|
||||||
folderSelect.SetSelected(selectedFolder)
|
folderSelect.SetSelected(selectedFolder)
|
||||||
|
|
||||||
|
// viewToggleIcon pairs with viewToggleText: both name the action the button
|
||||||
|
// performs, not the state it is in, matching stopAllButton's convention.
|
||||||
|
viewToggleIcon := func(current domain.JobListView) fyne.Resource {
|
||||||
|
if current.IsCompact() {
|
||||||
|
return theme.ViewFullScreenIcon()
|
||||||
|
}
|
||||||
|
return theme.ListIcon()
|
||||||
|
}
|
||||||
|
viewButton := widget.NewButtonWithIcon(viewToggleText(listView), viewToggleIcon(listView), nil)
|
||||||
|
viewButton.OnTapped = func() {
|
||||||
|
next := nextJobListView(listView)
|
||||||
|
listView = next
|
||||||
|
if err := svc.SetJobListView(next); err != nil {
|
||||||
|
// Roll the mode back and leave the button as it was, so the button
|
||||||
|
// never claims a preference that did not reach disk.
|
||||||
|
listView = nextJobListView(next)
|
||||||
|
dialog.ShowError(err, w)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
viewButton.SetText(viewToggleText(listView))
|
||||||
|
viewButton.SetIcon(viewToggleIcon(listView))
|
||||||
|
// Refresh re-creates the row template, which is what recomputes the
|
||||||
|
// cached row height for the new mode. Selection is untouched.
|
||||||
|
list.Refresh()
|
||||||
|
}
|
||||||
|
|
||||||
addButton := widget.NewButtonWithIcon("New job", theme.ContentAddIcon(), func() {
|
addButton := widget.NewButtonWithIcon("New job", theme.ContentAddIcon(), func() {
|
||||||
showJobDialog(w, "New job", job{Schedule: "@every 1m", Command: "echo GoSentry job ran", Enabled: true}, func(saved job) {
|
showJobDialog(w, "New job", job{Schedule: "@every 1m", Command: "echo GoSentry job ran", Enabled: true}, func(saved job) {
|
||||||
created, err := svc.CreateJob(saved)
|
created, err := svc.CreateJob(saved)
|
||||||
@@ -165,7 +225,6 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
}
|
}
|
||||||
selected = indexOfID(jobs, created.ID)
|
selected = indexOfID(jobs, created.ID)
|
||||||
filteredJobs = filteredJobIndexes(jobs, selectedFolder)
|
filteredJobs = filteredJobIndexes(jobs, selectedFolder)
|
||||||
list.Refresh()
|
|
||||||
list.Select(app.DisplayIndex(filteredJobs, selected))
|
list.Select(app.DisplayIndex(filteredJobs, selected))
|
||||||
refreshView()
|
refreshView()
|
||||||
})
|
})
|
||||||
@@ -183,7 +242,6 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
syncFromService()
|
syncFromService()
|
||||||
folderSelect.Options = folderOptions(jobs)
|
folderSelect.Options = folderOptions(jobs)
|
||||||
folderSelect.Refresh()
|
folderSelect.Refresh()
|
||||||
list.Refresh()
|
|
||||||
refreshView()
|
refreshView()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -193,12 +251,10 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
}
|
}
|
||||||
// A manual run is allowed even while the scheduler is paused: pause only
|
// A manual run is allowed even while the scheduler is paused: pause only
|
||||||
// stops automatic scheduled runs, not the user's explicit "Run now".
|
// stops automatic scheduled runs, not the user's explicit "Run now".
|
||||||
// RunNow still refuses an already-running job (it returns an error); the UI
|
|
||||||
// has always ignored that case silently, so the run simply does not start.
|
|
||||||
if err := svc.RunNow(jobs[selected].ID); err != nil {
|
if err := svc.RunNow(jobs[selected].ID); err != nil {
|
||||||
|
dialog.ShowError(err, w)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
list.Refresh()
|
|
||||||
refreshView()
|
refreshView()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -230,7 +286,6 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
stopAllButton.SetText("Disable auto")
|
stopAllButton.SetText("Disable auto")
|
||||||
stopAllButton.SetIcon(theme.MediaPauseIcon())
|
stopAllButton.SetIcon(theme.MediaPauseIcon())
|
||||||
}
|
}
|
||||||
list.Refresh()
|
|
||||||
refreshView()
|
refreshView()
|
||||||
}
|
}
|
||||||
pauseButton := widget.NewButtonWithIcon("Pause", theme.MediaPauseIcon(), func() {
|
pauseButton := widget.NewButtonWithIcon("Pause", theme.MediaPauseIcon(), func() {
|
||||||
@@ -242,8 +297,6 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
dialog.ShowError(err, w)
|
dialog.ShowError(err, w)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
syncFromService()
|
|
||||||
list.Refresh()
|
|
||||||
refreshView()
|
refreshView()
|
||||||
})
|
})
|
||||||
deleteButton := widget.NewButtonWithIcon("Delete", theme.DeleteIcon(), func() {
|
deleteButton := widget.NewButtonWithIcon("Delete", theme.DeleteIcon(), func() {
|
||||||
@@ -275,7 +328,6 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
} else {
|
} else {
|
||||||
selected = filteredJobs[0]
|
selected = filteredJobs[0]
|
||||||
}
|
}
|
||||||
list.Refresh()
|
|
||||||
if selected >= 0 {
|
if selected >= 0 {
|
||||||
list.Select(app.DisplayIndex(filteredJobs, selected))
|
list.Select(app.DisplayIndex(filteredJobs, selected))
|
||||||
}
|
}
|
||||||
@@ -285,10 +337,19 @@ func newJobsView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func()) {
|
|||||||
|
|
||||||
toolbar := container.NewHBox(addButton, editButton, runButton, pauseButton, deleteButton, layout.NewSpacer())
|
toolbar := container.NewHBox(addButton, editButton, runButton, pauseButton, deleteButton, layout.NewSpacer())
|
||||||
globalControls := container.NewHBox(stopAllButton, schedulerState, layout.NewSpacer())
|
globalControls := container.NewHBox(stopAllButton, schedulerState, layout.NewSpacer())
|
||||||
sidebarHeader := container.NewVBox(globalControls, widget.NewSeparator(), widget.NewLabelWithStyle("Folder", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}), folderSelect, toolbar)
|
// The whole filter is one row: caption on the left, view toggle on the right,
|
||||||
|
// select filling what is left. The border layout gives both edges their
|
||||||
|
// MinSize, so the header is a line shorter than a stacked caption would make it.
|
||||||
|
folderCaption := widget.NewLabelWithStyle("Folder", fyne.TextAlignLeading, fyne.TextStyle{Bold: true})
|
||||||
|
filterRow := container.NewBorder(nil, nil, folderCaption, viewButton, folderSelect)
|
||||||
|
sidebarHeader := container.NewVBox(globalControls, widget.NewSeparator(), filterRow, toolbar)
|
||||||
sidebar := container.NewBorder(sidebarHeader, nil, nil, nil, list)
|
sidebar := container.NewBorder(sidebarHeader, nil, nil, nil, list)
|
||||||
|
|
||||||
fixedSidebar := container.New(minWidthLayout{width: minJobsSidebarWidth}, sidebar)
|
// A split rather than a Border left slot: the border pinned the sidebar at its
|
||||||
panel := container.NewBorder(nil, nil, fixedSidebar, nil, container.NewPadded(dp.container()))
|
// MinSize forever, so the user could never trade list width for detail width.
|
||||||
|
// The divider lets either pane grow, and neither can be dragged below its own
|
||||||
|
// content minimum.
|
||||||
|
panel := container.NewHSplit(sidebar, container.NewPadded(dp.container()))
|
||||||
|
panel.SetOffset(initialSplitOffset(sidebar.MinSize().Width))
|
||||||
return panel, refreshView
|
return panel, refreshView
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
"fyne.io/fyne/v2"
|
"fyne.io/fyne/v2"
|
||||||
"fyne.io/fyne/v2/container"
|
"fyne.io/fyne/v2/container"
|
||||||
|
"fyne.io/fyne/v2/layout"
|
||||||
"fyne.io/fyne/v2/theme"
|
"fyne.io/fyne/v2/theme"
|
||||||
"fyne.io/fyne/v2/widget"
|
"fyne.io/fyne/v2/widget"
|
||||||
)
|
)
|
||||||
@@ -22,6 +23,7 @@ type detailsPanel struct {
|
|||||||
arguments *widget.Label
|
arguments *widget.Label
|
||||||
runMode *widget.Label
|
runMode *widget.Label
|
||||||
overlapPolicy *widget.Label
|
overlapPolicy *widget.Label
|
||||||
|
timeout *widget.Label
|
||||||
lastRun *widget.Label
|
lastRun *widget.Label
|
||||||
nextRun *widget.Label
|
nextRun *widget.Label
|
||||||
state *widget.Label
|
state *widget.Label
|
||||||
@@ -34,7 +36,7 @@ type detailsPanel struct {
|
|||||||
selectedLogs []event
|
selectedLogs []event
|
||||||
}
|
}
|
||||||
|
|
||||||
func newDetailsPanel(firstJob job, rt *domain.JobRuntime, globalOverlapPolicy domain.OverlapPolicy) *detailsPanel {
|
func newDetailsPanel(firstJob job, rt *domain.JobRuntime, globalOverlapPolicy domain.OverlapPolicy, globalTimeout int) *detailsPanel {
|
||||||
d := &detailsPanel{
|
d := &detailsPanel{
|
||||||
title: widget.NewLabelWithStyle("", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
|
title: widget.NewLabelWithStyle("", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
|
||||||
folder: newJobDetailLabel(""),
|
folder: newJobDetailLabel(""),
|
||||||
@@ -43,6 +45,7 @@ func newDetailsPanel(firstJob job, rt *domain.JobRuntime, globalOverlapPolicy do
|
|||||||
arguments: newJobDetailLabel(""),
|
arguments: newJobDetailLabel(""),
|
||||||
runMode: newJobDetailLabel(""),
|
runMode: newJobDetailLabel(""),
|
||||||
overlapPolicy: newJobDetailLabel(""),
|
overlapPolicy: newJobDetailLabel(""),
|
||||||
|
timeout: newJobDetailLabel(""),
|
||||||
lastRun: newJobDetailLabel(""),
|
lastRun: newJobDetailLabel(""),
|
||||||
nextRun: newJobDetailLabel(""),
|
nextRun: newJobDetailLabel(""),
|
||||||
state: newJobDetailLabel(""),
|
state: newJobDetailLabel(""),
|
||||||
@@ -57,23 +60,29 @@ func newDetailsPanel(firstJob job, rt *domain.JobRuntime, globalOverlapPolicy do
|
|||||||
// The height here is only a floor: the scroll grows to fill whatever space the
|
// The height here is only a floor: the scroll grows to fill whatever space the
|
||||||
// border layout gives it, so keep the minimum small so the whole window can be
|
// border layout gives it, so keep the minimum small so the whole window can be
|
||||||
// shrunk on short (720p) screens. Long output stays reachable by scrolling.
|
// shrunk on short (720p) screens. Long output stays reachable by scrolling.
|
||||||
|
// The width, unlike the height, is load-bearing outside this widget: it is the
|
||||||
|
// details pane's widest minimum, so it is also what keeps the metadata value
|
||||||
|
// column non-empty — captionValueLayout hands the value whatever is left after
|
||||||
|
// the caption and has no floor of its own (see its comment in layout.go).
|
||||||
|
// Lowering it narrows those values with nothing to warn about it; the user can
|
||||||
|
// only widen them, by dragging the jobs split divider left.
|
||||||
d.commandOutputScroll.SetMinSize(fyne.NewSize(460, 70))
|
d.commandOutputScroll.SetMinSize(fyne.NewSize(460, 70))
|
||||||
d.logs = widget.NewList(
|
d.logs = widget.NewList(
|
||||||
func() int { return len(d.selectedLogs) },
|
func() int { return len(d.selectedLogs) },
|
||||||
func() fyne.CanvasObject {
|
func() fyne.CanvasObject {
|
||||||
l := widget.NewLabel("log")
|
l := widget.NewLabel("log")
|
||||||
l.Wrapping = fyne.TextTruncate
|
l.Truncation = fyne.TextTruncateClip
|
||||||
return l
|
return l
|
||||||
},
|
},
|
||||||
func(id widget.ListItemID, item fyne.CanvasObject) {
|
func(id widget.ListItemID, item fyne.CanvasObject) {
|
||||||
item.(*widget.Label).SetText(app.EventLine(d.selectedLogs[id]))
|
item.(*widget.Label).SetText(app.EventLine(d.selectedLogs[id]))
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
d.update(firstJob, rt, globalOverlapPolicy)
|
d.update(firstJob, rt, globalOverlapPolicy, globalTimeout)
|
||||||
return d
|
return d
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *detailsPanel) update(j job, rt *domain.JobRuntime, globalOverlapPolicy domain.OverlapPolicy) {
|
func (d *detailsPanel) update(j job, rt *domain.JobRuntime, globalOverlapPolicy domain.OverlapPolicy, globalTimeout int) {
|
||||||
d.title.SetText(j.Name)
|
d.title.SetText(j.Name)
|
||||||
d.folder.SetText(app.DisplayFolder(j.Folder))
|
d.folder.SetText(app.DisplayFolder(j.Folder))
|
||||||
d.schedule.SetText(j.Schedule)
|
d.schedule.SetText(j.Schedule)
|
||||||
@@ -81,6 +90,7 @@ func (d *detailsPanel) update(j job, rt *domain.JobRuntime, globalOverlapPolicy
|
|||||||
d.arguments.SetText(app.DisplayArguments(j.Arguments))
|
d.arguments.SetText(app.DisplayArguments(j.Arguments))
|
||||||
d.runMode.SetText(app.DisplayRunMode(j))
|
d.runMode.SetText(app.DisplayRunMode(j))
|
||||||
d.overlapPolicy.SetText(app.DisplayOverlapPolicy(j, globalOverlapPolicy))
|
d.overlapPolicy.SetText(app.DisplayOverlapPolicy(j, globalOverlapPolicy))
|
||||||
|
d.timeout.SetText(app.DisplayTimeout(j, globalTimeout))
|
||||||
d.lastRun.SetText(rt.LastRun)
|
d.lastRun.SetText(rt.LastRun)
|
||||||
d.nextRun.SetText(rt.NextRun)
|
d.nextRun.SetText(rt.NextRun)
|
||||||
d.state.SetText(rt.LastState)
|
d.state.SetText(rt.LastState)
|
||||||
@@ -101,6 +111,7 @@ func (d *detailsPanel) clear() {
|
|||||||
d.arguments.SetText("")
|
d.arguments.SetText("")
|
||||||
d.runMode.SetText("")
|
d.runMode.SetText("")
|
||||||
d.overlapPolicy.SetText("")
|
d.overlapPolicy.SetText("")
|
||||||
|
d.timeout.SetText("")
|
||||||
d.lastRun.SetText("")
|
d.lastRun.SetText("")
|
||||||
d.nextRun.SetText("")
|
d.nextRun.SetText("")
|
||||||
d.state.SetText("")
|
d.state.SetText("")
|
||||||
@@ -110,20 +121,59 @@ func (d *detailsPanel) clear() {
|
|||||||
d.logs.Refresh()
|
d.logs.Refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// detailRowSpec pairs a metadata caption with the widget that shows its value.
|
||||||
|
// metadataRows and container derive both the caption column width and the row
|
||||||
|
// layout from this single list, so a row added to one is never forgotten in
|
||||||
|
// the other.
|
||||||
|
type detailRowSpec struct {
|
||||||
|
caption string
|
||||||
|
value fyne.CanvasObject
|
||||||
|
}
|
||||||
|
|
||||||
|
// metadataRows lists the details pane's metadata rows in display order. It is
|
||||||
|
// the single source both the caption width measurement and the row layout in
|
||||||
|
// container() read, so a twelfth row added here cannot silently go unmeasured
|
||||||
|
// or unlaid-out the way two separately maintained lists could.
|
||||||
|
func (d *detailsPanel) metadataRows() []detailRowSpec {
|
||||||
|
return []detailRowSpec{
|
||||||
|
{"Folder", d.folder},
|
||||||
|
{"Schedule", d.schedule},
|
||||||
|
{"Command", d.command},
|
||||||
|
{"Arguments", d.arguments},
|
||||||
|
{"Run mode", d.runMode},
|
||||||
|
{"Overlap policy", d.overlapPolicy},
|
||||||
|
{"Timeout", d.timeout},
|
||||||
|
{"State", d.state},
|
||||||
|
{"Last run", d.lastRun},
|
||||||
|
{"Next run", d.nextRun},
|
||||||
|
{"Statistics", d.stats},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// container assembles the details pane layout: metadata rows pin to the top,
|
// container assembles the details pane layout: metadata rows pin to the top,
|
||||||
// the activity panel pins to the bottom, and command output fills the remainder.
|
// the activity panel pins to the bottom, and command output fills the remainder.
|
||||||
func (d *detailsPanel) container() fyne.CanvasObject {
|
func (d *detailsPanel) container() fyne.CanvasObject {
|
||||||
// Metadata is laid out in two columns so the block stays half as tall,
|
// Metadata is laid out in two columns so the block stays half as tall,
|
||||||
// keeping the details pane usable on 720p screens where a single column of
|
// keeping the details pane usable on 720p screens where a single column of
|
||||||
// ten rows pushes the minimum window height past the available space.
|
// ten rows pushes the minimum window height past the available space.
|
||||||
capW := detailCaptionWidth()
|
specs := d.metadataRows()
|
||||||
rows := container.New(compactVBoxLayout{spacing: detailRowSpacing},
|
captions := make([]string, len(specs))
|
||||||
detailRowPair(capW, "Folder", d.folder, "Schedule", d.schedule),
|
for i, spec := range specs {
|
||||||
detailRowPair(capW, "Command", d.command, "Arguments", d.arguments),
|
captions[i] = spec.caption
|
||||||
detailRowPair(capW, "Run mode", d.runMode, "Overlap policy", d.overlapPolicy),
|
}
|
||||||
detailRowPair(capW, "Last run", d.lastRun, "Next run", d.nextRun),
|
capW := captionColumnWidth(captions...)
|
||||||
detailRowPair(capW, "State", d.state, "Statistics", d.stats),
|
rowObjects := make([]fyne.CanvasObject, 0, (len(specs)+1)/2)
|
||||||
)
|
for i := 0; i+1 < len(specs); i += 2 {
|
||||||
|
rowObjects = append(rowObjects, detailRowPair(capW, specs[i].caption, specs[i].value, specs[i+1].caption, specs[i+1].value))
|
||||||
|
}
|
||||||
|
// An odd row count leaves one caption without a partner (Statistics, today);
|
||||||
|
// it falls through to a single-column row rather than being paired with
|
||||||
|
// nothing.
|
||||||
|
if len(specs)%2 == 1 {
|
||||||
|
last := specs[len(specs)-1]
|
||||||
|
rowObjects = append(rowObjects, detailRow(capW, last.caption, last.value))
|
||||||
|
}
|
||||||
|
rows := container.New(layout.NewCustomPaddedVBoxLayout(rowOverlap()), rowObjects...)
|
||||||
top := container.NewVBox(
|
top := container.NewVBox(
|
||||||
d.title,
|
d.title,
|
||||||
widget.NewSeparator(),
|
widget.NewSeparator(),
|
||||||
@@ -147,30 +197,12 @@ func (d *detailsPanel) container() fyne.CanvasObject {
|
|||||||
// absorbs sub-pixel rounding so the last row is never clipped behind a scrollbar.
|
// absorbs sub-pixel rounding so the last row is never clipped behind a scrollbar.
|
||||||
func activityRowsHeight(rows int) float32 {
|
func activityRowsHeight(rows int) float32 {
|
||||||
sample := widget.NewLabel("log")
|
sample := widget.NewLabel("log")
|
||||||
sample.Wrapping = fyne.TextTruncate
|
sample.Truncation = fyne.TextTruncateClip
|
||||||
itemHeight := sample.MinSize().Height
|
itemHeight := sample.MinSize().Height
|
||||||
padding := theme.Padding()
|
padding := theme.Padding()
|
||||||
return (itemHeight+padding)*float32(rows) - padding + 1
|
return (itemHeight+padding)*float32(rows) - padding + 1
|
||||||
}
|
}
|
||||||
|
|
||||||
// detailCaptionWidth returns the width reserved for every metadata caption,
|
|
||||||
// derived from the widest caption label so the value columns all start at the
|
|
||||||
// same x and no caption truncates. Measuring a real label keeps it DPI- and
|
|
||||||
// theme-aware instead of relying on a hand-tuned constant.
|
|
||||||
func detailCaptionWidth() float32 {
|
|
||||||
captions := []string{
|
|
||||||
"Folder", "Schedule", "Command", "Arguments", "Run mode",
|
|
||||||
"Overlap policy", "Last run", "Next run", "State", "Statistics",
|
|
||||||
}
|
|
||||||
var width float32
|
|
||||||
for _, c := range captions {
|
|
||||||
if w := widget.NewLabelWithStyle(c, fyne.TextAlignLeading, fyne.TextStyle{Bold: true}).MinSize().Width; w > width {
|
|
||||||
width = w
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return width
|
|
||||||
}
|
|
||||||
|
|
||||||
// detailRowPair places two label/value pairs side by side, producing the
|
// detailRowPair places two label/value pairs side by side, producing the
|
||||||
// four-column caption|value|caption|value rows the compact metadata grid uses.
|
// four-column caption|value|caption|value rows the compact metadata grid uses.
|
||||||
func detailRowPair(captionWidth float32, l1 string, v1 fyne.CanvasObject, l2 string, v2 fyne.CanvasObject) fyne.CanvasObject {
|
func detailRowPair(captionWidth float32, l1 string, v1 fyne.CanvasObject, l2 string, v2 fyne.CanvasObject) fyne.CanvasObject {
|
||||||
@@ -179,7 +211,7 @@ func detailRowPair(captionWidth float32, l1 string, v1 fyne.CanvasObject, l2 str
|
|||||||
|
|
||||||
func detailRow(captionWidth float32, label string, value fyne.CanvasObject) fyne.CanvasObject {
|
func detailRow(captionWidth float32, label string, value fyne.CanvasObject) fyne.CanvasObject {
|
||||||
caption := widget.NewLabelWithStyle(label, fyne.TextAlignLeading, fyne.TextStyle{Bold: true})
|
caption := widget.NewLabelWithStyle(label, fyne.TextAlignLeading, fyne.TextStyle{Bold: true})
|
||||||
caption.Wrapping = fyne.TextTruncate
|
caption.Truncation = fyne.TextTruncateClip
|
||||||
// A fixed caption width (rather than an even split) means widening the window
|
// A fixed caption width (rather than an even split) means widening the window
|
||||||
// feeds the extra space to the value, not the short caption.
|
// feeds the extra space to the value, not the short caption.
|
||||||
return container.New(captionValueLayout{captionWidth: captionWidth}, caption, value)
|
return container.New(captionValueLayout{captionWidth: captionWidth}, caption, value)
|
||||||
@@ -187,6 +219,6 @@ func detailRow(captionWidth float32, label string, value fyne.CanvasObject) fyne
|
|||||||
|
|
||||||
func newJobDetailLabel(text string) *widget.Label {
|
func newJobDetailLabel(text string) *widget.Label {
|
||||||
label := widget.NewLabel(text)
|
label := widget.NewLabel(text)
|
||||||
label.Wrapping = fyne.TextTruncate
|
label.Truncation = fyne.TextTruncateClip
|
||||||
return label
|
return label
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
package ui
|
package ui
|
||||||
|
|
||||||
import "strings"
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
||||||
|
)
|
||||||
|
|
||||||
// lastJobLogs returns a fresh slice of the most recent activity entries for the
|
// lastJobLogs returns a fresh slice of the most recent activity entries for the
|
||||||
// "Selected job activity" panel. Logs are stored newest-first (see
|
// "Selected job activity" panel. Logs are stored newest-first (see
|
||||||
@@ -47,11 +51,31 @@ func filterValue(folder string) string {
|
|||||||
return strings.TrimSpace(folder)
|
return strings.TrimSpace(folder)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nextJobListView returns the mode the view toggle switches to. Anything that
|
||||||
|
// is not compact reads as detailed, so unknown and legacy values flip to
|
||||||
|
// compact just as an explicit "detailed" does.
|
||||||
|
func nextJobListView(current domain.JobListView) domain.JobListView {
|
||||||
|
if current.IsCompact() {
|
||||||
|
return domain.JobListViewDetailed
|
||||||
|
}
|
||||||
|
return domain.JobListViewCompact
|
||||||
|
}
|
||||||
|
|
||||||
|
// viewToggleText labels the view toggle with the action it performs, not the
|
||||||
|
// current state — the same convention as the "Disable auto"/"Enable auto"
|
||||||
|
// button. It also keeps the on-disk strings away from the user.
|
||||||
|
func viewToggleText(current domain.JobListView) string {
|
||||||
|
if current.IsCompact() {
|
||||||
|
return "Detailed"
|
||||||
|
}
|
||||||
|
return "Compact"
|
||||||
|
}
|
||||||
|
|
||||||
func indexOfID(jobs []job, id int) int {
|
func indexOfID(jobs []job, id int) int {
|
||||||
for index, current := range jobs {
|
for index, current := range jobs {
|
||||||
if current.ID == id {
|
if current.ID == id {
|
||||||
return index
|
return index
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return 0
|
return -1
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,13 @@ package ui
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/app"
|
||||||
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
||||||
|
|
||||||
|
"fyne.io/fyne/v2"
|
||||||
|
"fyne.io/fyne/v2/container"
|
||||||
|
"fyne.io/fyne/v2/test"
|
||||||
|
"fyne.io/fyne/v2/widget"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestFilterValue(t *testing.T) {
|
func TestFilterValue(t *testing.T) {
|
||||||
@@ -93,3 +99,389 @@ func TestFilteredJobIndexesEmptySlice(t *testing.T) {
|
|||||||
t.Errorf("empty job list should return empty indexes, got %v", got)
|
t.Errorf("empty job list should return empty indexes, got %v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestNextJobListViewFlipsBothWays(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
current, want domain.JobListView
|
||||||
|
}{
|
||||||
|
{domain.JobListViewDetailed, domain.JobListViewCompact},
|
||||||
|
{domain.JobListViewCompact, domain.JobListViewDetailed},
|
||||||
|
// Empty and unknown values read as detailed, so they flip to compact.
|
||||||
|
{"", domain.JobListViewCompact},
|
||||||
|
{"tiny", domain.JobListViewCompact},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if got := nextJobListView(tc.current); got != tc.want {
|
||||||
|
t.Errorf("nextJobListView(%q) = %q, want %q", tc.current, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// findFirst walks a widget tree depth-first and returns the first object the
|
||||||
|
// match function accepts. Tests use it to reach widgets newJobsView builds
|
||||||
|
// internally rather than returning.
|
||||||
|
func findFirst(root fyne.CanvasObject, match func(fyne.CanvasObject) bool) fyne.CanvasObject {
|
||||||
|
if match(root) {
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
container, ok := root.(*fyne.Container)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, child := range container.Objects {
|
||||||
|
if found := findFirst(child, match); found != nil {
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// jobsSplit returns the view's master/detail split. newJobsView assembles the
|
||||||
|
// panel as container.NewHSplit(sidebar, details), so the two panes are reached
|
||||||
|
// through Leading and Trailing.
|
||||||
|
func jobsSplit(t *testing.T, content fyne.CanvasObject) *container.Split {
|
||||||
|
t.Helper()
|
||||||
|
split, ok := content.(*container.Split)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("jobs view is not the expected Split container")
|
||||||
|
}
|
||||||
|
return split
|
||||||
|
}
|
||||||
|
|
||||||
|
// jobsSidebar narrows the search to the left pane. The details panel has a
|
||||||
|
// widget.List of its own (the activity log), so a search from the whole view
|
||||||
|
// would find the wrong one.
|
||||||
|
func jobsSidebar(t *testing.T, content fyne.CanvasObject) fyne.CanvasObject {
|
||||||
|
t.Helper()
|
||||||
|
return jobsSplit(t, content).Leading
|
||||||
|
}
|
||||||
|
|
||||||
|
func jobsList(t *testing.T, content fyne.CanvasObject) *widget.List {
|
||||||
|
t.Helper()
|
||||||
|
found := findFirst(jobsSidebar(t, content), func(o fyne.CanvasObject) bool {
|
||||||
|
_, ok := o.(*widget.List)
|
||||||
|
return ok
|
||||||
|
})
|
||||||
|
if found == nil {
|
||||||
|
t.Fatal("jobs sidebar contains no list widget")
|
||||||
|
}
|
||||||
|
return found.(*widget.List)
|
||||||
|
}
|
||||||
|
|
||||||
|
// jobsToolbar finds the add/edit/run/pause/delete button row inside the
|
||||||
|
// sidebar, identified by its first child being the "New job" button.
|
||||||
|
func jobsToolbar(t *testing.T, content fyne.CanvasObject) fyne.CanvasObject {
|
||||||
|
t.Helper()
|
||||||
|
found := findFirst(jobsSidebar(t, content), func(o fyne.CanvasObject) bool {
|
||||||
|
wrapper, ok := o.(*fyne.Container)
|
||||||
|
if !ok || len(wrapper.Objects) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
button, ok := wrapper.Objects[0].(*widget.Button)
|
||||||
|
return ok && button.Text == "New job"
|
||||||
|
})
|
||||||
|
if found == nil {
|
||||||
|
t.Fatal("jobs sidebar has no toolbar row")
|
||||||
|
}
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
// jobsToolbarButton returns the toolbar button with the given caption.
|
||||||
|
func jobsToolbarButton(t *testing.T, content fyne.CanvasObject, text string) *widget.Button {
|
||||||
|
t.Helper()
|
||||||
|
found := findFirst(jobsToolbar(t, content), func(o fyne.CanvasObject) bool {
|
||||||
|
button, ok := o.(*widget.Button)
|
||||||
|
return ok && button.Text == text
|
||||||
|
})
|
||||||
|
if found == nil {
|
||||||
|
t.Fatalf("jobs toolbar has no %q button", text)
|
||||||
|
}
|
||||||
|
return found.(*widget.Button)
|
||||||
|
}
|
||||||
|
|
||||||
|
// jobsDetails narrows the search to the right pane (see jobsSidebar).
|
||||||
|
func jobsDetails(t *testing.T, content fyne.CanvasObject) fyne.CanvasObject {
|
||||||
|
t.Helper()
|
||||||
|
return jobsSplit(t, content).Trailing
|
||||||
|
}
|
||||||
|
|
||||||
|
// jobsDetailsActivity returns the "Selected job activity" list, the only
|
||||||
|
// widget.List in the details pane.
|
||||||
|
func jobsDetailsActivity(t *testing.T, content fyne.CanvasObject) *widget.List {
|
||||||
|
t.Helper()
|
||||||
|
found := findFirst(jobsDetails(t, content), func(o fyne.CanvasObject) bool {
|
||||||
|
_, ok := o.(*widget.List)
|
||||||
|
return ok
|
||||||
|
})
|
||||||
|
if found == nil {
|
||||||
|
t.Fatal("details pane has no activity list")
|
||||||
|
}
|
||||||
|
return found.(*widget.List)
|
||||||
|
}
|
||||||
|
|
||||||
|
// jobsDetailsTitle reads the details pane's heading, which detailsPanel builds
|
||||||
|
// as the first bold label in the pane.
|
||||||
|
func jobsDetailsTitle(t *testing.T, content fyne.CanvasObject) string {
|
||||||
|
t.Helper()
|
||||||
|
found := findFirst(jobsDetails(t, content), func(o fyne.CanvasObject) bool {
|
||||||
|
label, ok := o.(*widget.Label)
|
||||||
|
return ok && label.TextStyle.Bold
|
||||||
|
})
|
||||||
|
if found == nil {
|
||||||
|
t.Fatal("details pane has no title label")
|
||||||
|
}
|
||||||
|
return found.(*widget.Label).Text
|
||||||
|
}
|
||||||
|
|
||||||
|
func jobsViewToggle(t *testing.T, content fyne.CanvasObject) *widget.Button {
|
||||||
|
t.Helper()
|
||||||
|
found := findFirst(jobsSidebar(t, content), func(o fyne.CanvasObject) bool {
|
||||||
|
button, ok := o.(*widget.Button)
|
||||||
|
return ok && (button.Text == "Compact" || button.Text == "Detailed")
|
||||||
|
})
|
||||||
|
if found == nil {
|
||||||
|
t.Fatal("jobs sidebar has no view toggle button")
|
||||||
|
}
|
||||||
|
return found.(*widget.Button)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestJobListViewToggleShrinksRowsAndPersists is the end-to-end guard for the
|
||||||
|
// compact view: one tap must shrink the list rows, relabel the button with the
|
||||||
|
// opposite action, and reach the config — and toggling back must undo all
|
||||||
|
// three. Row height is measured through List.CreateItem/UpdateItem because
|
||||||
|
// that is exactly what widget.List caches as the row height.
|
||||||
|
func TestJobListViewToggleShrinksRowsAndPersists(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
w := testApp.NewWindow("test")
|
||||||
|
defer w.Close()
|
||||||
|
|
||||||
|
store := newTestStore(t)
|
||||||
|
jobs := []domain.Job{
|
||||||
|
{ID: 1, Name: "Nightly backup", Folder: "Maintenance", Schedule: "@every 1m", Command: "echo hi", Enabled: true},
|
||||||
|
}
|
||||||
|
svc := app.NewService(store, jobs)
|
||||||
|
defer svc.Stop()
|
||||||
|
|
||||||
|
content, _ := newJobsView(w, svc)
|
||||||
|
w.SetContent(content)
|
||||||
|
|
||||||
|
list := jobsList(t, content)
|
||||||
|
viewButton := jobsViewToggle(t, content)
|
||||||
|
if viewButton.Text != "Compact" {
|
||||||
|
t.Fatalf("a default config should open detailed: button text = %q, want %q", viewButton.Text, "Compact")
|
||||||
|
}
|
||||||
|
|
||||||
|
rowHeight := func() float32 {
|
||||||
|
t.Helper()
|
||||||
|
row := list.CreateItem()
|
||||||
|
list.UpdateItem(0, row)
|
||||||
|
return row.MinSize().Height
|
||||||
|
}
|
||||||
|
detailedHeight := rowHeight()
|
||||||
|
|
||||||
|
test.Tap(viewButton)
|
||||||
|
if store.Config.JobListView != domain.JobListViewCompact {
|
||||||
|
t.Errorf("after tapping, Config.JobListView = %q, want %q", store.Config.JobListView, domain.JobListViewCompact)
|
||||||
|
}
|
||||||
|
if viewButton.Text != "Detailed" {
|
||||||
|
t.Errorf("after tapping, button text = %q, want %q", viewButton.Text, "Detailed")
|
||||||
|
}
|
||||||
|
compactHeight := rowHeight()
|
||||||
|
if compactHeight >= detailedHeight {
|
||||||
|
t.Errorf("compact row height = %v, want less than detailed %v", compactHeight, detailedHeight)
|
||||||
|
}
|
||||||
|
|
||||||
|
test.Tap(viewButton)
|
||||||
|
if store.Config.JobListView != domain.JobListViewDetailed {
|
||||||
|
t.Errorf("after tapping back, Config.JobListView = %q, want %q", store.Config.JobListView, domain.JobListViewDetailed)
|
||||||
|
}
|
||||||
|
if viewButton.Text != "Compact" {
|
||||||
|
t.Errorf("after tapping back, button text = %q, want %q", viewButton.Text, "Compact")
|
||||||
|
}
|
||||||
|
if got := rowHeight(); got != detailedHeight {
|
||||||
|
t.Errorf("row height after switching back = %v, want the original %v", got, detailedHeight)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestJobListViewCompactConfigOpensCompact checks the persisted preference is
|
||||||
|
// honoured at build time, not just after a tap.
|
||||||
|
func TestJobListViewCompactConfigOpensCompact(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
w := testApp.NewWindow("test")
|
||||||
|
defer w.Close()
|
||||||
|
|
||||||
|
store := newTestStore(t)
|
||||||
|
store.Config.JobListView = domain.JobListViewCompact
|
||||||
|
svc := app.NewService(store, nil)
|
||||||
|
defer svc.Stop()
|
||||||
|
|
||||||
|
content, _ := newJobsView(w, svc)
|
||||||
|
w.SetContent(content)
|
||||||
|
|
||||||
|
if got := jobsViewToggle(t, content).Text; got != "Detailed" {
|
||||||
|
t.Errorf("button text for a compact config = %q, want %q", got, "Detailed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestJobsSidebarWidthIsItsContent is the regression guard for F7: nothing
|
||||||
|
// but the sidebar's own content (here, the toolbar row) should impose a
|
||||||
|
// width floor on it.
|
||||||
|
func TestJobsSidebarWidthIsItsContent(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
w := testApp.NewWindow("test")
|
||||||
|
defer w.Close()
|
||||||
|
|
||||||
|
store := newTestStore(t)
|
||||||
|
svc := app.NewService(store, nil)
|
||||||
|
defer svc.Stop()
|
||||||
|
|
||||||
|
content, _ := newJobsView(w, svc)
|
||||||
|
w.SetContent(content)
|
||||||
|
|
||||||
|
sidebarWidth := jobsSidebar(t, content).MinSize().Width
|
||||||
|
toolbarWidth := jobsToolbar(t, content).MinSize().Width
|
||||||
|
if sidebarWidth != toolbarWidth {
|
||||||
|
t.Errorf("sidebar MinSize().Width = %v, want it to equal the toolbar row's %v", sidebarWidth, toolbarWidth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestJobsSplitOpensAtTheSidebarWidth is the guard for the derived initial
|
||||||
|
// offset (F15): at the default window width the divider must open at the
|
||||||
|
// sidebar's own width — enough that the toolbar is never born clipped, and no
|
||||||
|
// more, since every extra pixel is taken from the details pane. Split's own
|
||||||
|
// clamp guarantees the lower bound, so the upper bound is what actually proves
|
||||||
|
// the offset was derived rather than left at the 0.5 default.
|
||||||
|
func TestJobsSplitOpensAtTheSidebarWidth(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
w := testApp.NewWindow("test")
|
||||||
|
defer w.Close()
|
||||||
|
|
||||||
|
store := newTestStore(t)
|
||||||
|
svc := app.NewService(store, nil)
|
||||||
|
defer svc.Stop()
|
||||||
|
|
||||||
|
content, _ := newJobsView(w, svc)
|
||||||
|
w.SetContent(content)
|
||||||
|
|
||||||
|
split := jobsSplit(t, content)
|
||||||
|
split.Resize(fyne.NewSize(defaultWindowWidth, defaultWindowHeight))
|
||||||
|
|
||||||
|
want := split.Leading.MinSize().Width
|
||||||
|
got := split.Leading.Size().Width
|
||||||
|
// One pixel of slack for the float32 round trip through the offset ratio.
|
||||||
|
if got < want || got > want+1 {
|
||||||
|
t.Errorf("leading pane opens at %v, want its content minimum %v", got, want)
|
||||||
|
}
|
||||||
|
if trailing := split.Trailing.Size().Width; trailing < split.Trailing.MinSize().Width {
|
||||||
|
t.Errorf("trailing pane opens at %v, below its minimum %v", trailing, split.Trailing.MinSize().Width)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestToolbarButtonRedrawsRowAndDetails is the regression guard for F12: the
|
||||||
|
// toolbar handlers no longer re-read the service or refresh the list
|
||||||
|
// themselves, so refreshView alone has to re-snapshot the jobs and repopulate
|
||||||
|
// the details pane. If it ever stops doing either, the row renders a stale
|
||||||
|
// status and the details lose the selection — neither is a compile error.
|
||||||
|
func TestToolbarButtonRedrawsRowAndDetails(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
w := testApp.NewWindow("test")
|
||||||
|
defer w.Close()
|
||||||
|
|
||||||
|
store := newTestStore(t)
|
||||||
|
jobs := []domain.Job{
|
||||||
|
{ID: 1, Name: "First", Schedule: "@every 1m", Command: "echo one", Enabled: true},
|
||||||
|
{ID: 2, Name: "Second", Schedule: "@every 2m", Command: "echo two", Enabled: true},
|
||||||
|
}
|
||||||
|
svc := app.NewService(store, jobs)
|
||||||
|
defer svc.Stop()
|
||||||
|
|
||||||
|
content, _ := newJobsView(w, svc)
|
||||||
|
w.SetContent(content)
|
||||||
|
|
||||||
|
list := jobsList(t, content)
|
||||||
|
// Row layout: VBox(nameLine, meta, status), nameLine = Border(name, inlineStatus).
|
||||||
|
rowText := func(id int) (name string, status string) {
|
||||||
|
t.Helper()
|
||||||
|
row := list.CreateItem().(*fyne.Container)
|
||||||
|
list.UpdateItem(id, row)
|
||||||
|
nameLine := row.Objects[0].(*fyne.Container)
|
||||||
|
return nameLine.Objects[0].(*widget.Label).Text, row.Objects[2].(*widget.Label).Text
|
||||||
|
}
|
||||||
|
|
||||||
|
activity := jobsDetailsActivity(t, content)
|
||||||
|
|
||||||
|
list.Select(1)
|
||||||
|
if got := jobsDetailsTitle(t, content); got != "Second" {
|
||||||
|
t.Fatalf("details title after selecting row 1 = %q, want %q", got, "Second")
|
||||||
|
}
|
||||||
|
if _, status := rowText(1); status == "Paused" {
|
||||||
|
t.Fatal("the second job should start enabled")
|
||||||
|
}
|
||||||
|
if got := activity.Length(); got != 0 {
|
||||||
|
t.Fatalf("activity rows before the tap = %d, want 0", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
test.Tap(jobsToolbarButton(t, content, "Pause"))
|
||||||
|
|
||||||
|
if svc.Jobs()[1].Enabled {
|
||||||
|
t.Fatal("tapping Pause did not reach the service")
|
||||||
|
}
|
||||||
|
name, status := rowText(1)
|
||||||
|
if name != "Second" || status != "Paused" {
|
||||||
|
t.Errorf("row 1 after Pause = (%q, %q), want (%q, %q)", name, status, "Second", "Paused")
|
||||||
|
}
|
||||||
|
if got := jobsDetailsTitle(t, content); got != "Second" {
|
||||||
|
t.Errorf("details title after Pause = %q, want the selection kept at %q", got, "Second")
|
||||||
|
}
|
||||||
|
// The pause writes an activity record. Seeing it here is what proves
|
||||||
|
// refreshView repopulated the details pane rather than leaving the panel on
|
||||||
|
// the snapshot it held before the tap.
|
||||||
|
if got := activity.Length(); got != 1 {
|
||||||
|
t.Errorf("activity rows after the tap = %d, want the pause record", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDetailCaptionWidthCoversEveryCaption is the guard that makes the single
|
||||||
|
// metadataRows list self-enforcing (F10): every caption it returns must
|
||||||
|
// measure no wider than captionColumnWidth's result for that same list, or a
|
||||||
|
// row added to metadataRows without updating the width measurement would
|
||||||
|
// silently truncate.
|
||||||
|
func TestDetailCaptionWidthCoversEveryCaption(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
d := newDetailsPanel(job{}, &domain.JobRuntime{}, domain.OverlapPolicySkip, 0)
|
||||||
|
specs := d.metadataRows()
|
||||||
|
captions := make([]string, len(specs))
|
||||||
|
for i, spec := range specs {
|
||||||
|
captions[i] = spec.caption
|
||||||
|
}
|
||||||
|
capW := captionColumnWidth(captions...)
|
||||||
|
for _, c := range captions {
|
||||||
|
if w := widget.NewLabelWithStyle(c, fyne.TextAlignLeading, fyne.TextStyle{Bold: true}).MinSize().Width; w > capW {
|
||||||
|
t.Errorf("caption %q measures %v, wider than captionColumnWidth's %v", c, w, capW)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestViewToggleTextNamesTheAction(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
current domain.JobListView
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{domain.JobListViewDetailed, "Compact"},
|
||||||
|
{domain.JobListViewCompact, "Detailed"},
|
||||||
|
{"", "Compact"},
|
||||||
|
{"tiny", "Compact"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if got := viewToggleText(tc.current); got != tc.want {
|
||||||
|
t.Errorf("viewToggleText(%q) = %q, want %q", tc.current, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,9 +2,25 @@ package ui
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fyne.io/fyne/v2"
|
"fyne.io/fyne/v2"
|
||||||
|
"fyne.io/fyne/v2/container"
|
||||||
|
"fyne.io/fyne/v2/layout"
|
||||||
"fyne.io/fyne/v2/theme"
|
"fyne.io/fyne/v2/theme"
|
||||||
|
"fyne.io/fyne/v2/widget"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// captionColumnWidth returns the width to reserve for a column of bold
|
||||||
|
// captions: the widest of them, measured under the current theme so it tracks
|
||||||
|
// text size and DPI instead of a hand-tuned constant.
|
||||||
|
func captionColumnWidth(captions ...string) float32 {
|
||||||
|
var width float32
|
||||||
|
for _, caption := range captions {
|
||||||
|
if w := widget.NewLabelWithStyle(caption, fyne.TextAlignLeading, fyne.TextStyle{Bold: true}).MinSize().Width; w > width {
|
||||||
|
width = w
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return width
|
||||||
|
}
|
||||||
|
|
||||||
type minWidthLayout struct {
|
type minWidthLayout struct {
|
||||||
width float32
|
width float32
|
||||||
}
|
}
|
||||||
@@ -37,46 +53,42 @@ func (l minWidthLayout) Layout(objects []fyne.CanvasObject, size fyne.Size) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// compactVBoxLayout stacks children vertically with a configurable gap between
|
// rowOverlap is the (negative) gap that pulls stacked label rows together by
|
||||||
// them, producing tighter rows than container.NewVBox (which inserts
|
// exactly one label's vertical inner padding. Two adjacent labels each inset
|
||||||
// theme.Padding() between every child). A negative spacing pulls neighbouring
|
// their text by theme.InnerPadding(), so the whitespace between two lines of
|
||||||
// rows together so they overlap the labels' built-in vertical padding, which is
|
// text is double what a single row needs; removing one label's worth
|
||||||
// how the details metadata is condensed to fit 720p screens.
|
// condenses the block without letting the text lines touch. Derived rather
|
||||||
type compactVBoxLayout struct {
|
// than hard-coded so it follows a theme that changes SizeNameInnerPadding.
|
||||||
spacing float32
|
func rowOverlap() float32 { return -theme.InnerPadding() }
|
||||||
|
|
||||||
|
// cancelRowOverlap exempts one row from the rowOverlap() spacing of the section
|
||||||
|
// it sits in, by padding its top edge with exactly what rowOverlap takes away.
|
||||||
|
// The overlap assumes both neighbours are text rows: each insets its text, so
|
||||||
|
// one padding's worth is duplicated and can go. A row whose value paints its own
|
||||||
|
// box to the row's edge — a Select, an Entry, a Button — has no such inset, so
|
||||||
|
// the overlap eats the visible gap instead and the box ends up flush against the
|
||||||
|
// row above it.
|
||||||
|
func cancelRowOverlap(row fyne.CanvasObject) fyne.CanvasObject {
|
||||||
|
return container.New(layout.NewCustomPaddedLayout(-rowOverlap(), 0, 0, 0), row)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l compactVBoxLayout) MinSize(objects []fyne.CanvasObject) fyne.Size {
|
// initialSplitOffset returns the container.Split offset that opens a horizontal
|
||||||
var w, h float32
|
// split with its leading pane at the given natural width. SetOffset takes a
|
||||||
var visible int
|
// ratio, but a pane's natural width is absolute, so the ratio is derived from
|
||||||
for _, o := range objects {
|
// the window width the app opens at rather than written as a literal: 0.44 fits
|
||||||
if !o.Visible() {
|
// 1024 px but would hand a 448 px sidebar 700 px on a 1600 px-wide window.
|
||||||
continue
|
//
|
||||||
}
|
// The divider sits between the panes and is excluded from the ratio, matching
|
||||||
min := o.MinSize()
|
// container.Split's own arithmetic (its divider is two theme paddings thick).
|
||||||
if min.Width > w {
|
// Split clamps the offset to both panes' minimums when it lays out, so a result
|
||||||
w = min.Width
|
// that is slightly off — the window is a little wider than its content area —
|
||||||
}
|
// costs at most a few pixels and can never clip either pane.
|
||||||
h += min.Height
|
func initialSplitOffset(leadingWidth float32) float64 {
|
||||||
visible++
|
available := float64(defaultWindowWidth - 2*theme.Padding())
|
||||||
}
|
if available <= 0 {
|
||||||
if visible > 1 {
|
return 0
|
||||||
h += l.spacing * float32(visible-1)
|
|
||||||
}
|
|
||||||
return fyne.NewSize(w, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l compactVBoxLayout) Layout(objects []fyne.CanvasObject, size fyne.Size) {
|
|
||||||
var y float32
|
|
||||||
for _, o := range objects {
|
|
||||||
if !o.Visible() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
h := o.MinSize().Height
|
|
||||||
o.Move(fyne.NewPos(0, y))
|
|
||||||
o.Resize(fyne.NewSize(size.Width, h))
|
|
||||||
y += h + l.spacing
|
|
||||||
}
|
}
|
||||||
|
return float64(leadingWidth) / available
|
||||||
}
|
}
|
||||||
|
|
||||||
// fixedHeightLayout forces its contents to a fixed height while leaving the
|
// fixedHeightLayout forces its contents to a fixed height while leaving the
|
||||||
@@ -114,10 +126,21 @@ func (l fixedHeightLayout) Layout(objects []fyne.CanvasObject, size fyne.Size) {
|
|||||||
// stops it from growing with the window (as an even two-column grid would), so
|
// stops it from growing with the window (as an even two-column grid would), so
|
||||||
// the extra space a wider window provides goes entirely to the value column. It
|
// the extra space a wider window provides goes entirely to the value column. It
|
||||||
// expects exactly two children: caption first, value second.
|
// expects exactly two children: caption first, value second.
|
||||||
|
//
|
||||||
|
// The value column has no minimum of its own: it gets whatever the container's
|
||||||
|
// width leaves, down to zero. What keeps it readable in the details pane is the
|
||||||
|
// 460 px minimum on commandOutputScroll (jobs_view_details.go), which is that
|
||||||
|
// pane's widest minimum and therefore its floor — a constant that exists for an
|
||||||
|
// unrelated reason. A new caller that gives this layout less width gets a value
|
||||||
|
// column that silently renders narrow or empty rather than one that clips.
|
||||||
type captionValueLayout struct {
|
type captionValueLayout struct {
|
||||||
captionWidth float32
|
captionWidth float32
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MinSize and Layout both return silently when given anything but two
|
||||||
|
// objects. That is acceptable here because the type is package-private with a
|
||||||
|
// single constructor (detailRow), which always supplies exactly a caption and
|
||||||
|
// a value — there is no external caller that could pass the wrong count.
|
||||||
func (l captionValueLayout) MinSize(objects []fyne.CanvasObject) fyne.Size {
|
func (l captionValueLayout) MinSize(objects []fyne.CanvasObject) fyne.Size {
|
||||||
if len(objects) != 2 {
|
if len(objects) != 2 {
|
||||||
return fyne.Size{}
|
return fyne.Size{}
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"fyne.io/fyne/v2/test"
|
||||||
|
"fyne.io/fyne/v2/theme"
|
||||||
|
"fyne.io/fyne/v2/widget"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestRowOverlapMatchesInnerPadding pins rowOverlap to theme.InnerPadding, the
|
||||||
|
// property that lets it follow a theme with a different SizeNameInnerPadding
|
||||||
|
// instead of drifting from a hand-tuned literal.
|
||||||
|
func TestRowOverlapMatchesInnerPadding(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
if got, want := rowOverlap(), -theme.InnerPadding(); got != want {
|
||||||
|
t.Errorf("rowOverlap() = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if rowOverlap() >= 0 {
|
||||||
|
t.Errorf("rowOverlap() = %v, want a negative value", rowOverlap())
|
||||||
|
}
|
||||||
|
|
||||||
|
testApp.Settings().SetTheme(test.NewTheme())
|
||||||
|
if got, want := rowOverlap(), -theme.InnerPadding(); got != want {
|
||||||
|
t.Errorf("under a different theme, rowOverlap() = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCancelRowOverlapAddsBackOneInnerPadding is the regression guard for the
|
||||||
|
// Settings tab's Theme row sitting flush against the Notifications checkbox:
|
||||||
|
// the wrapper must add exactly the padding rowOverlap removes, on the top edge
|
||||||
|
// only, so the row below is unaffected and the width does not change.
|
||||||
|
func TestCancelRowOverlapAddsBackOneInnerPadding(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
child := widget.NewSelect([]string{"System"}, nil)
|
||||||
|
wrapped := cancelRowOverlap(child)
|
||||||
|
|
||||||
|
childMin, wrappedMin := child.MinSize(), wrapped.MinSize()
|
||||||
|
if got, want := wrappedMin.Height, childMin.Height-rowOverlap(); got != want {
|
||||||
|
t.Errorf("wrapped height = %v, want %v (child %v plus one inner padding)", got, want, childMin.Height)
|
||||||
|
}
|
||||||
|
if got, want := wrappedMin.Width, childMin.Width; got != want {
|
||||||
|
t.Errorf("wrapped width = %v, want the child's %v", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
wrapped.Resize(wrappedMin)
|
||||||
|
if got, want := child.Position().Y, -rowOverlap(); got != want {
|
||||||
|
t.Errorf("child Y = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got := child.Position().X; got != 0 {
|
||||||
|
t.Errorf("child X = %v, want 0", got)
|
||||||
|
}
|
||||||
|
if got, want := child.Size().Height, childMin.Height; got != want {
|
||||||
|
t.Errorf("child height = %v, want %v: the padding must not be taken out of the row", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCaptionColumnWidth covers the shapes F10's shared helper has to handle:
|
||||||
|
// no captions, one, and several of varying length at two text sizes.
|
||||||
|
func TestCaptionColumnWidth(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
if got := captionColumnWidth(); got != 0 {
|
||||||
|
t.Errorf("no captions: got %v, want 0", got)
|
||||||
|
}
|
||||||
|
solo := captionColumnWidth("Solo")
|
||||||
|
if solo <= 0 {
|
||||||
|
t.Errorf("one caption: got %v, want > 0", solo)
|
||||||
|
}
|
||||||
|
widest := captionColumnWidth("Short", "A Much Longer Caption")
|
||||||
|
if widest <= solo {
|
||||||
|
t.Errorf("widest of several captions = %v, want it wider than a single short one (%v)", widest, solo)
|
||||||
|
}
|
||||||
|
|
||||||
|
testApp.Settings().SetTheme(test.NewTheme())
|
||||||
|
if got := captionColumnWidth("Short", "A Much Longer Caption"); got <= 0 {
|
||||||
|
t.Errorf("under a different theme: got %v, want > 0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package ui
|
package ui
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.mixdep.ru/mix/gosentry/assets"
|
"gitea.mixdep.ru/mix/gosentry/assets"
|
||||||
@@ -10,7 +11,6 @@ import (
|
|||||||
"fyne.io/fyne/v2"
|
"fyne.io/fyne/v2"
|
||||||
"fyne.io/fyne/v2/container"
|
"fyne.io/fyne/v2/container"
|
||||||
"fyne.io/fyne/v2/theme"
|
"fyne.io/fyne/v2/theme"
|
||||||
"fyne.io/fyne/v2/widget"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// The UI package aliases domain types to keep widget callbacks short. The actual
|
// The UI package aliases domain types to keep widget callbacks short. The actual
|
||||||
@@ -19,11 +19,7 @@ import (
|
|||||||
type job = domain.Job
|
type job = domain.Job
|
||||||
type event = domain.RunRecord
|
type event = domain.RunRecord
|
||||||
|
|
||||||
func newMainView(w fyne.Window) (fyne.CanvasObject, func(time.Duration, bool)) {
|
func newMainView(w fyne.Window, svc *app.Service) (fyne.CanvasObject, func(time.Duration, bool)) {
|
||||||
svc, err := app.Open()
|
|
||||||
if err != nil {
|
|
||||||
return container.NewPadded(widget.NewLabel("Failed to load GoSentry configuration: " + err.Error())), func(time.Duration, bool) {}
|
|
||||||
}
|
|
||||||
svc.InstallDesktopIcon(appID, assets.IconBytes())
|
svc.InstallDesktopIcon(appID, assets.IconBytes())
|
||||||
|
|
||||||
// Build the initial event history from the current runtime state. Jobs and
|
// Build the initial event history from the current runtime state. Jobs and
|
||||||
@@ -69,6 +65,7 @@ func newMainView(w fyne.Window) (fyne.CanvasObject, func(time.Duration, bool)) {
|
|||||||
svc.Subscribe(app.ObserverFunc(func(ev app.Event) {
|
svc.Subscribe(app.ObserverFunc(func(ev app.Event) {
|
||||||
recorded, isRecorded := ev.(app.RunRecorded)
|
recorded, isRecorded := ev.(app.RunRecorded)
|
||||||
errOccurred, isError := ev.(app.ErrorOccurred)
|
errOccurred, isError := ev.(app.ErrorOccurred)
|
||||||
|
jobsLoaded, isJobsLoaded := ev.(app.JobsLoaded)
|
||||||
fyne.Do(func() {
|
fyne.Do(func() {
|
||||||
if isRecorded {
|
if isRecorded {
|
||||||
events = append(events, recorded.Record)
|
events = append(events, recorded.Record)
|
||||||
@@ -85,6 +82,12 @@ func newMainView(w fyne.Window) (fyne.CanvasObject, func(time.Duration, bool)) {
|
|||||||
if isError {
|
if isError {
|
||||||
events = append(events, newEvent(0, "Service", "Error", errOccurred.Err.Error()))
|
events = append(events, newEvent(0, "Service", "Error", errOccurred.Err.Error()))
|
||||||
}
|
}
|
||||||
|
if isJobsLoaded {
|
||||||
|
// Selecting an existing jobs file replaces the job list without a
|
||||||
|
// prompt, so History carries the receipt: how many jobs, from where.
|
||||||
|
detail := strconv.Itoa(jobsLoaded.Count) + " jobs from " + jobsLoaded.Path
|
||||||
|
events = append(events, newEvent(0, "Service", "Jobs loaded", detail))
|
||||||
|
}
|
||||||
refresh()
|
refresh()
|
||||||
})
|
})
|
||||||
}))
|
}))
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/app"
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/storage"
|
||||||
|
|
||||||
|
"fyne.io/fyne/v2/test"
|
||||||
|
)
|
||||||
|
|
||||||
|
// newTestStore builds a Store rooted in a temp directory. It is separate from
|
||||||
|
// newTestService so tests that need a non-default Config (or their own jobs)
|
||||||
|
// can adjust it before handing it to app.NewService.
|
||||||
|
func newTestStore(t *testing.T) *storage.Store {
|
||||||
|
t.Helper()
|
||||||
|
dir := t.TempDir()
|
||||||
|
return &storage.Store{
|
||||||
|
Paths: storage.Paths{
|
||||||
|
ExecutablePath: filepath.Join(dir, "gosentry"),
|
||||||
|
AppDir: dir,
|
||||||
|
ConfigPath: filepath.Join(dir, "gosentry.json"),
|
||||||
|
JobsDir: dir,
|
||||||
|
JobsPath: filepath.Join(dir, "jobs.json"),
|
||||||
|
LogsDir: filepath.Join(dir, "logs"),
|
||||||
|
},
|
||||||
|
Config: domain.Config{
|
||||||
|
JobsFile: "jobs.json",
|
||||||
|
LogsDir: "logs",
|
||||||
|
MaxLogFiles: 100,
|
||||||
|
MaxLogAgeDays: 30,
|
||||||
|
ExecutionMode: domain.ExecutionModeParallel,
|
||||||
|
OverlapPolicy: domain.OverlapPolicySkip,
|
||||||
|
DefaultTimeoutSeconds: 30,
|
||||||
|
KeepRunningInTray: true,
|
||||||
|
NotifyOnFailure: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTestService(t *testing.T) *app.Service {
|
||||||
|
t.Helper()
|
||||||
|
return app.NewService(newTestStore(t), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMainViewFitsTheDefaultWindowSize is the regression guard for F1: the
|
||||||
|
// assembled content must fit within the window size the app asks for, so Fyne
|
||||||
|
// never silently widens the window past it. The store's ConfigPath is
|
||||||
|
// deliberately long so the test also covers F3 — the config path label must
|
||||||
|
// not grow the Settings tab's minimum width with it.
|
||||||
|
func TestMainViewFitsTheDefaultWindowSize(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
w := testApp.NewWindow("test")
|
||||||
|
defer w.Close()
|
||||||
|
|
||||||
|
store := newTestStore(t)
|
||||||
|
store.Paths.ConfigPath = filepath.Join(t.TempDir(), "a-deliberately-long-directory-name-to-stress-the-config-path-label", "gosentry.json")
|
||||||
|
svc := app.NewService(store, nil)
|
||||||
|
defer svc.Stop()
|
||||||
|
|
||||||
|
content, _ := newMainView(w, svc)
|
||||||
|
min := content.MinSize()
|
||||||
|
if min.Width > defaultWindowWidth || min.Height > defaultWindowHeight {
|
||||||
|
t.Errorf("content.MinSize() = %v, want within %vx%v", min, defaultWindowWidth, defaultWindowHeight)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMainViewBuilds(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
w := testApp.NewWindow("test")
|
||||||
|
defer w.Close()
|
||||||
|
|
||||||
|
svc := newTestService(t)
|
||||||
|
defer svc.Stop()
|
||||||
|
|
||||||
|
content, recordStartup := newMainView(w, svc)
|
||||||
|
if content == nil {
|
||||||
|
t.Fatal("newMainView returned nil content")
|
||||||
|
}
|
||||||
|
w.SetContent(content)
|
||||||
|
recordStartup(0, true)
|
||||||
|
}
|
||||||
@@ -9,10 +9,19 @@ import (
|
|||||||
|
|
||||||
"fyne.io/fyne/v2"
|
"fyne.io/fyne/v2"
|
||||||
fyneapp "fyne.io/fyne/v2/app"
|
fyneapp "fyne.io/fyne/v2/app"
|
||||||
|
"fyne.io/fyne/v2/container"
|
||||||
|
"fyne.io/fyne/v2/widget"
|
||||||
)
|
)
|
||||||
|
|
||||||
const appID = "ru.mixeme.gosentry.desktop"
|
const appID = "ru.mixeme.gosentry.desktop"
|
||||||
|
|
||||||
|
// defaultWindowWidth and defaultWindowHeight are the size the window opens at
|
||||||
|
// on first launch (later launches restore the last size from preferences).
|
||||||
|
// Fyne enforces the assembled content's MinSize as a hard floor over these, so
|
||||||
|
// they only take effect if the content actually fits within them.
|
||||||
|
const defaultWindowWidth = 1024
|
||||||
|
const defaultWindowHeight = 660
|
||||||
|
|
||||||
// Run is the application entry point. It owns the process lifecycle — single
|
// Run is the application entry point. It owns the process lifecycle — single
|
||||||
// instance arbitration, Fyne app + window construction, tray wiring, and the
|
// instance arbitration, Fyne app + window construction, tray wiring, and the
|
||||||
// startup-timing record — and delegates all view construction to newMainView in
|
// startup-timing record — and delegates all view construction to newMainView in
|
||||||
@@ -49,10 +58,19 @@ func Run(startInTray bool) {
|
|||||||
w := a.NewWindow("GoSentry " + app.Version)
|
w := a.NewWindow("GoSentry " + app.Version)
|
||||||
configureSystemTray(a, w)
|
configureSystemTray(a, w)
|
||||||
prefs := a.Preferences()
|
prefs := a.Preferences()
|
||||||
winW := float32(prefs.FloatWithFallback("window.width", 1024))
|
winW := float32(prefs.FloatWithFallback("window.width", defaultWindowWidth))
|
||||||
winH := float32(prefs.FloatWithFallback("window.height", 660))
|
winH := float32(prefs.FloatWithFallback("window.height", defaultWindowHeight))
|
||||||
w.Resize(fyne.NewSize(winW, winH))
|
w.Resize(fyne.NewSize(winW, winH))
|
||||||
content, recordStartup := newMainView(w)
|
svc, err := app.Open()
|
||||||
|
if err != nil {
|
||||||
|
w.SetContent(container.NewPadded(widget.NewLabel("Failed to load GoSentry configuration: " + err.Error())))
|
||||||
|
a.Run()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Apply the persisted theme before building content so the window renders in
|
||||||
|
// the chosen theme from the first frame rather than flashing the default one.
|
||||||
|
applyTheme(a, svc.Store().Config.Theme)
|
||||||
|
content, recordStartup := newMainView(w, svc)
|
||||||
w.SetContent(content)
|
w.SetContent(content)
|
||||||
serveSingleInstance(instanceListener, w)
|
serveSingleInstance(instanceListener, w)
|
||||||
if startInTray {
|
if startInTray {
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
package ui
|
package ui
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/url"
|
|
||||||
"runtime"
|
|
||||||
"runtime/debug"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -11,23 +8,23 @@ import (
|
|||||||
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
||||||
|
|
||||||
"fyne.io/fyne/v2"
|
"fyne.io/fyne/v2"
|
||||||
"fyne.io/fyne/v2/container"
|
|
||||||
"fyne.io/fyne/v2/dialog"
|
|
||||||
"fyne.io/fyne/v2/theme"
|
"fyne.io/fyne/v2/theme"
|
||||||
"fyne.io/fyne/v2/widget"
|
"fyne.io/fyne/v2/widget"
|
||||||
)
|
)
|
||||||
|
|
||||||
// settingsLabelWidth is wide enough to show the longest caption ("Default
|
|
||||||
// overlap policy") in full; the captions truncate, so a narrower width would
|
|
||||||
// clip it. All rows share this width so their value controls stay aligned.
|
|
||||||
const settingsLabelWidth float32 = 180
|
|
||||||
const settingsControlWidth float32 = 330
|
|
||||||
const projectRepositoryURL = "https://gitea.mixdep.ru/mix/gosentry"
|
const projectRepositoryURL = "https://gitea.mixdep.ru/mix/gosentry"
|
||||||
|
|
||||||
// settingsRowSpacing is the (negative) gap between rows of the settings form,
|
// settingsCaptions lists every settingsRow caption in the tab, in no
|
||||||
// overlapping each control's built-in vertical padding so the column is tighter
|
// particular order. settingsView measures this once with captionColumnWidth
|
||||||
// and more compact, matching the condensed job details panel.
|
// so every row's value column starts at the same x; a caption added to a row
|
||||||
const settingsRowSpacing float32 = -6
|
// below without being added here is the one way a row would silently fall out
|
||||||
|
// of alignment.
|
||||||
|
var settingsCaptions = []string{
|
||||||
|
"Autostart", "Tray", "Notifications", "Theme",
|
||||||
|
"Execution mode", "Default overlap policy", "Default timeout (s)",
|
||||||
|
"Config JSON", "Jobs file", "Logs directory", "Max log files", "Max log age days",
|
||||||
|
"GoSentry", "Go", "Fyne", "Repository",
|
||||||
|
}
|
||||||
|
|
||||||
func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
||||||
store := svc.Store()
|
store := svc.Store()
|
||||||
@@ -35,6 +32,9 @@ func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
|||||||
// when something differs. It is defined below (once Save and every field
|
// when something differs. It is defined below (once Save and every field
|
||||||
// exist) but declared here so the field change handlers can reference it.
|
// exist) but declared here so the field change handlers can reference it.
|
||||||
var updateSaveState func()
|
var updateSaveState func()
|
||||||
|
// loadFields populates every form control from the given config. It backs
|
||||||
|
// both the initial load and the Cancel/Defaults buttons below.
|
||||||
|
var loadFields func(domain.Config)
|
||||||
startOnLogin := widget.NewCheck("Start on login", nil)
|
startOnLogin := widget.NewCheck("Start on login", nil)
|
||||||
startOnLogin.SetChecked(store.Config.StartOnLogin)
|
startOnLogin.SetChecked(store.Config.StartOnLogin)
|
||||||
autostartStatus := widget.NewLabel("")
|
autostartStatus := widget.NewLabel("")
|
||||||
@@ -61,6 +61,15 @@ func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
|||||||
notifications := widget.NewCheck("Show desktop notifications for failed jobs", nil)
|
notifications := widget.NewCheck("Show desktop notifications for failed jobs", nil)
|
||||||
notifications.SetChecked(store.Config.NotifyOnFailure)
|
notifications.SetChecked(store.Config.NotifyOnFailure)
|
||||||
notifications.OnChanged = func(bool) { updateSaveState() }
|
notifications.OnChanged = func(bool) { updateSaveState() }
|
||||||
|
themeSelect := widget.NewSelect([]string{themeLabelDefault, themeLabelGoSentry}, nil)
|
||||||
|
themeSelect.SetSelected(themeLabel(store.Config.Theme))
|
||||||
|
// Preview the theme the moment it is picked so the choice is visible before
|
||||||
|
// saving; Save persists it. Reverting the selection reverts the preview, and
|
||||||
|
// closing without saving falls back to the stored theme on next launch.
|
||||||
|
themeSelect.OnChanged = func(string) {
|
||||||
|
applyTheme(fyne.CurrentApp(), themeFromLabel(themeSelect.Selected))
|
||||||
|
updateSaveState()
|
||||||
|
}
|
||||||
executionModeSelect := widget.NewSelect(
|
executionModeSelect := widget.NewSelect(
|
||||||
[]string{string(domain.ExecutionModeParallel), string(domain.ExecutionModeSequential)},
|
[]string{string(domain.ExecutionModeParallel), string(domain.ExecutionModeSequential)},
|
||||||
nil,
|
nil,
|
||||||
@@ -73,11 +82,17 @@ func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
|||||||
)
|
)
|
||||||
overlapPolicySelect.SetSelected(string(store.Config.OverlapPolicy))
|
overlapPolicySelect.SetSelected(string(store.Config.OverlapPolicy))
|
||||||
overlapPolicySelect.OnChanged = func(string) { updateSaveState() }
|
overlapPolicySelect.OnChanged = func(string) { updateSaveState() }
|
||||||
jobsDir := widget.NewEntry()
|
defaultTimeout := widget.NewEntry()
|
||||||
jobsDir.SetText(store.Config.JobsDir)
|
defaultTimeout.SetPlaceHolder("0 = no timeout")
|
||||||
jobsDir.OnChanged = func(string) { updateSaveState() }
|
defaultTimeout.SetText(strconv.Itoa(store.Config.DefaultTimeoutSeconds))
|
||||||
jobsDirBrowse := widget.NewButtonWithIcon("Browse", theme.FolderOpenIcon(), func() {
|
defaultTimeout.OnChanged = func(string) { updateSaveState() }
|
||||||
chooseFolder(w, jobsDir)
|
jobsFile := widget.NewEntry()
|
||||||
|
jobsFile.SetText(store.Config.JobsFile)
|
||||||
|
jobsFile.OnChanged = func(string) { updateSaveState() }
|
||||||
|
// The picker only offers existing files; a jobs file that does not exist yet
|
||||||
|
// is entered by typing its path, which Save then creates.
|
||||||
|
jobsFileBrowse := widget.NewButtonWithIcon("Browse", theme.FileIcon(), func() {
|
||||||
|
chooseJSONFile(w, jobsFile)
|
||||||
})
|
})
|
||||||
logsDir := widget.NewEntry()
|
logsDir := widget.NewEntry()
|
||||||
logsDir.SetText(store.Config.LogsDir)
|
logsDir.SetText(store.Config.LogsDir)
|
||||||
@@ -85,6 +100,13 @@ func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
|||||||
logsDirBrowse := widget.NewButtonWithIcon("Browse", theme.FolderOpenIcon(), func() {
|
logsDirBrowse := widget.NewButtonWithIcon("Browse", theme.FolderOpenIcon(), func() {
|
||||||
chooseFolder(w, logsDir)
|
chooseFolder(w, logsDir)
|
||||||
})
|
})
|
||||||
|
// Log files are read outside the app, so the folder gets a direct shortcut
|
||||||
|
// beside its path instead of making the user copy the path into a file
|
||||||
|
// manager. It reveals whatever the field currently holds, so an edit can be
|
||||||
|
// checked before Save.
|
||||||
|
logsDirOpen := widget.NewButtonWithIcon("Open", theme.FolderIcon(), func() {
|
||||||
|
openFolder(w, settingsFolderPath(store.Paths.AppDir, logsDir.Text))
|
||||||
|
})
|
||||||
maxLogFiles := widget.NewEntry()
|
maxLogFiles := widget.NewEntry()
|
||||||
maxLogFiles.SetText(strconv.Itoa(store.Config.MaxLogFiles))
|
maxLogFiles.SetText(strconv.Itoa(store.Config.MaxLogFiles))
|
||||||
maxLogFiles.OnChanged = func(string) { updateSaveState() }
|
maxLogFiles.OnChanged = func(string) { updateSaveState() }
|
||||||
@@ -94,7 +116,7 @@ func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
|||||||
// Autostart status sits on its own row beneath the checkbox (rather than
|
// Autostart status sits on its own row beneath the checkbox (rather than
|
||||||
// beside it) so the Application section fits within a half-width column.
|
// beside it) so the Application section fits within a half-width column.
|
||||||
// Truncating keeps a long status message from forcing the column wider.
|
// Truncating keeps a long status message from forcing the column wider.
|
||||||
autostartStatus.Wrapping = fyne.TextTruncate
|
autostartStatus.Truncation = fyne.TextTruncateClip
|
||||||
settingsStatus := widget.NewLabel("")
|
settingsStatus := widget.NewLabel("")
|
||||||
|
|
||||||
saveSettings := widget.NewButtonWithIcon("Save settings", theme.DocumentSaveIcon(), func() {
|
saveSettings := widget.NewButtonWithIcon("Save settings", theme.DocumentSaveIcon(), func() {
|
||||||
@@ -108,19 +130,24 @@ func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
|||||||
settingsStatus.SetText("Max log age days must be a positive number")
|
settingsStatus.SetText("Max log age days must be a positive number")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(jobsDir.Text) == "" {
|
if strings.TrimSpace(jobsFile.Text) == "" {
|
||||||
settingsStatus.SetText("Jobs directory is required")
|
settingsStatus.SetText("Jobs file is required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(logsDir.Text) == "" {
|
if strings.TrimSpace(logsDir.Text) == "" {
|
||||||
settingsStatus.SetText("Logs directory is required")
|
settingsStatus.SetText("Logs directory is required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
timeout, err := strconv.Atoi(strings.TrimSpace(defaultTimeout.Text))
|
||||||
|
if err != nil || timeout < 0 {
|
||||||
|
settingsStatus.SetText("Default timeout must not be negative (0 = no timeout)")
|
||||||
|
return
|
||||||
|
}
|
||||||
// Build the new config from the form and hand it to the Service, which
|
// Build the new config from the form and hand it to the Service, which
|
||||||
// validates it, persists config and jobs to the (possibly new) directory,
|
// validates it, persists config and jobs to the (possibly new) directory,
|
||||||
// and runs log cleanup so tightened retention limits take effect at once.
|
// and runs log cleanup so tightened retention limits take effect at once.
|
||||||
config := store.Config
|
config := store.Config
|
||||||
config.JobsDir = strings.TrimSpace(jobsDir.Text)
|
config.JobsFile = strings.TrimSpace(jobsFile.Text)
|
||||||
config.LogsDir = strings.TrimSpace(logsDir.Text)
|
config.LogsDir = strings.TrimSpace(logsDir.Text)
|
||||||
config.MaxLogFiles = files
|
config.MaxLogFiles = files
|
||||||
config.MaxLogAgeDays = days
|
config.MaxLogAgeDays = days
|
||||||
@@ -129,6 +156,8 @@ func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
|||||||
config.NotifyOnFailure = notifications.Checked
|
config.NotifyOnFailure = notifications.Checked
|
||||||
config.ExecutionMode = domain.ExecutionMode(executionModeSelect.Selected)
|
config.ExecutionMode = domain.ExecutionMode(executionModeSelect.Selected)
|
||||||
config.OverlapPolicy = domain.OverlapPolicy(overlapPolicySelect.Selected)
|
config.OverlapPolicy = domain.OverlapPolicy(overlapPolicySelect.Selected)
|
||||||
|
config.DefaultTimeoutSeconds = timeout
|
||||||
|
config.Theme = themeFromLabel(themeSelect.Selected)
|
||||||
if err := svc.UpdateSettings(config); err != nil {
|
if err := svc.UpdateSettings(config); err != nil {
|
||||||
settingsStatus.SetText("Save failed: " + err.Error())
|
settingsStatus.SetText("Save failed: " + err.Error())
|
||||||
return
|
return
|
||||||
@@ -155,10 +184,12 @@ func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
|||||||
notifications.Checked != c.NotifyOnFailure ||
|
notifications.Checked != c.NotifyOnFailure ||
|
||||||
executionModeSelect.Selected != string(c.ExecutionMode) ||
|
executionModeSelect.Selected != string(c.ExecutionMode) ||
|
||||||
overlapPolicySelect.Selected != string(c.OverlapPolicy) ||
|
overlapPolicySelect.Selected != string(c.OverlapPolicy) ||
|
||||||
strings.TrimSpace(jobsDir.Text) != c.JobsDir ||
|
strings.TrimSpace(defaultTimeout.Text) != strconv.Itoa(c.DefaultTimeoutSeconds) ||
|
||||||
|
strings.TrimSpace(jobsFile.Text) != c.JobsFile ||
|
||||||
strings.TrimSpace(logsDir.Text) != c.LogsDir ||
|
strings.TrimSpace(logsDir.Text) != c.LogsDir ||
|
||||||
strings.TrimSpace(maxLogFiles.Text) != strconv.Itoa(c.MaxLogFiles) ||
|
strings.TrimSpace(maxLogFiles.Text) != strconv.Itoa(c.MaxLogFiles) ||
|
||||||
strings.TrimSpace(maxLogAgeDays.Text) != strconv.Itoa(c.MaxLogAgeDays)
|
strings.TrimSpace(maxLogAgeDays.Text) != strconv.Itoa(c.MaxLogAgeDays) ||
|
||||||
|
themeSelect.Selected != themeLabel(c.Theme)
|
||||||
if changed {
|
if changed {
|
||||||
saveSettings.Enable()
|
saveSettings.Enable()
|
||||||
} else {
|
} else {
|
||||||
@@ -167,130 +198,80 @@ func settingsView(w fyne.Window, svc *app.Service) fyne.CanvasObject {
|
|||||||
}
|
}
|
||||||
updateSaveState()
|
updateSaveState()
|
||||||
|
|
||||||
// The form is split into two columns so a wide window uses its horizontal
|
// loadFields populates every form control from a config without saving it,
|
||||||
// space instead of stretching into one tall strip. The left column holds the
|
// backing both the Cancel button (reload the saved config, discarding edits)
|
||||||
// toggles (Application, Queue); the right holds the editable Storage fields and
|
// and the Defaults button (load the built-in defaults for review before
|
||||||
// the read-only About block. Save spans the full width below both columns.
|
// Save is clicked).
|
||||||
leftColumn := container.NewVBox(
|
loadFields = func(c domain.Config) {
|
||||||
settingsSection("Application",
|
startOnLogin.SetChecked(c.StartOnLogin)
|
||||||
settingsRow("Autostart", container.New(minWidthLayout{width: settingsControlWidth}, startOnLogin)),
|
minimizeToTray.SetChecked(c.KeepRunningInTray)
|
||||||
// Autostart status sits on its own row, aligned under the checkbox via an
|
notifications.SetChecked(c.NotifyOnFailure)
|
||||||
// empty caption, so the Application section fits in a half-width column.
|
themeSelect.SetSelected(themeLabel(c.Theme))
|
||||||
settingsRow("", autostartStatus),
|
applyTheme(fyne.CurrentApp(), themeFromLabel(themeSelect.Selected))
|
||||||
settingsRow("Tray", container.New(minWidthLayout{width: settingsControlWidth}, minimizeToTray)),
|
executionModeSelect.SetSelected(string(c.ExecutionMode))
|
||||||
settingsRow("Notifications", container.New(minWidthLayout{width: settingsControlWidth}, notifications)),
|
overlapPolicySelect.SetSelected(string(c.OverlapPolicy))
|
||||||
),
|
defaultTimeout.SetText(strconv.Itoa(c.DefaultTimeoutSeconds))
|
||||||
widget.NewSeparator(),
|
jobsFile.SetText(c.JobsFile)
|
||||||
// Queue holds the execution mode and overlap policy comboboxes. Like
|
logsDir.SetText(c.LogsDir)
|
||||||
// Storage, it uses the default VBox spacing (not the condensed section
|
maxLogFiles.SetText(strconv.Itoa(c.MaxLogFiles))
|
||||||
// layout) so the comboboxes keep a visible gap between them.
|
maxLogAgeDays.SetText(strconv.Itoa(c.MaxLogAgeDays))
|
||||||
container.NewVBox(
|
if startOnLogin.Checked != store.Config.StartOnLogin {
|
||||||
widget.NewLabelWithStyle("Queue", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
|
autostartStatus.SetText("Pending: save settings to apply")
|
||||||
settingsRow("Execution mode", container.New(minWidthLayout{width: settingsControlWidth}, executionModeSelect)),
|
} else {
|
||||||
settingsRow("Default overlap policy", container.New(minWidthLayout{width: settingsControlWidth}, overlapPolicySelect)),
|
refreshAutostartStatus()
|
||||||
),
|
}
|
||||||
)
|
settingsStatus.SetText("")
|
||||||
rightColumn := container.NewVBox(
|
updateSaveState()
|
||||||
// Storage holds editable entry fields. It uses the default VBox spacing
|
}
|
||||||
// (not the condensed section layout) so the entry boxes keep a visible
|
cancelSettings := widget.NewButtonWithIcon("Cancel", theme.CancelIcon(), func() {
|
||||||
// gap between them instead of merging into one block.
|
loadFields(store.Config)
|
||||||
container.NewVBox(
|
})
|
||||||
widget.NewLabelWithStyle("Storage", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
|
restoreDefaults := widget.NewButtonWithIcon("Defaults", theme.MediaReplayIcon(), func() {
|
||||||
settingsRow("Config JSON", widget.NewLabel(store.Paths.ConfigPath)),
|
loadFields(domain.DefaultConfig())
|
||||||
settingsRow("Jobs directory", container.NewBorder(nil, nil, nil, jobsDirBrowse, jobsDir)),
|
})
|
||||||
settingsRow("Logs directory", container.NewBorder(nil, nil, nil, logsDirBrowse, logsDir)),
|
|
||||||
settingsRow("Max log files", maxLogFiles),
|
return newSettingsLayout(settingsFormFields{
|
||||||
settingsRow("Max log age days", maxLogAgeDays),
|
startOnLogin: startOnLogin,
|
||||||
),
|
autostartStatus: autostartStatus,
|
||||||
widget.NewSeparator(),
|
minimizeToTray: minimizeToTray,
|
||||||
settingsSection("About",
|
notifications: notifications,
|
||||||
settingsRow("GoSentry", widget.NewLabel(app.Version)),
|
themeSelect: themeSelect,
|
||||||
settingsRow("Go", widget.NewLabel(runtime.Version())),
|
executionModeSelect: executionModeSelect,
|
||||||
settingsRow("Fyne", widget.NewLabel(fyneVersion())),
|
overlapPolicySelect: overlapPolicySelect,
|
||||||
settingsRow("Repository", widget.NewHyperlink(projectRepositoryURL, mustParseURL(projectRepositoryURL))),
|
defaultTimeout: defaultTimeout,
|
||||||
),
|
configPath: store.Paths.ConfigPath,
|
||||||
|
jobsFile: jobsFile,
|
||||||
|
jobsFileBrowse: jobsFileBrowse,
|
||||||
|
logsDir: logsDir,
|
||||||
|
logsDirOpen: logsDirOpen,
|
||||||
|
logsDirBrowse: logsDirBrowse,
|
||||||
|
maxLogFiles: maxLogFiles,
|
||||||
|
maxLogAgeDays: maxLogAgeDays,
|
||||||
|
saveSettings: saveSettings,
|
||||||
|
cancelSettings: cancelSettings,
|
||||||
|
restoreDefaults: restoreDefaults,
|
||||||
|
settingsStatus: settingsStatus,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Theme dropdown labels. These are the human-facing captions; themeLabel and
|
||||||
|
// themeFromLabel translate between them and the stored domain.Theme values so the
|
||||||
|
// select never leaks the on-disk "default"/"gosentry" strings to the user.
|
||||||
|
const (
|
||||||
|
themeLabelDefault = "Default"
|
||||||
|
themeLabelGoSentry = "GoSentry"
|
||||||
)
|
)
|
||||||
|
|
||||||
// The two columns sit in a top-aligned grid; Save spans the full width below.
|
func themeLabel(choice domain.Theme) string {
|
||||||
// Wrapping the whole thing in a vertical scroll keeps its minimum height small
|
if choice == domain.ThemeGoSentry {
|
||||||
// so it does not dictate the window's minimum height (AppTabs sizes to the
|
return themeLabelGoSentry
|
||||||
// tallest tab) and it scrolls on short 720p screens.
|
}
|
||||||
return container.NewVScroll(container.NewPadded(container.NewVBox(
|
return themeLabelDefault
|
||||||
container.NewGridWithColumns(2, leftColumn, rightColumn),
|
|
||||||
widget.NewSeparator(),
|
|
||||||
// Save button and its status share one row so an empty status (the common
|
|
||||||
// case) does not leave a blank line above the separator. The status appears
|
|
||||||
// beside the button once a save reports a result.
|
|
||||||
container.NewHBox(saveSettings, settingsStatus),
|
|
||||||
)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// settingsSection groups a bold header above its rows using the tight
|
func themeFromLabel(label string) domain.Theme {
|
||||||
// settingsRowSpacing so a block of label rows reads as one compact unit. The
|
if label == themeLabelGoSentry {
|
||||||
// caller keeps separators and entry-heavy sections in the surrounding VBox so
|
return domain.ThemeGoSentry
|
||||||
// they retain the theme's normal spacing.
|
|
||||||
func settingsSection(title string, rows ...fyne.CanvasObject) fyne.CanvasObject {
|
|
||||||
children := make([]fyne.CanvasObject, 0, len(rows)+1)
|
|
||||||
children = append(children, widget.NewLabelWithStyle(title, fyne.TextAlignLeading, fyne.TextStyle{Bold: true}))
|
|
||||||
children = append(children, rows...)
|
|
||||||
return container.New(compactVBoxLayout{spacing: settingsRowSpacing}, children...)
|
|
||||||
}
|
}
|
||||||
|
return domain.ThemeDefault
|
||||||
func fyneVersion() string {
|
|
||||||
info, ok := debug.ReadBuildInfo()
|
|
||||||
if !ok {
|
|
||||||
return "unknown"
|
|
||||||
}
|
}
|
||||||
for _, dependency := range info.Deps {
|
|
||||||
if dependency.Path == "fyne.io/fyne/v2" {
|
|
||||||
if dependency.Replace != nil && dependency.Replace.Version != "" {
|
|
||||||
return dependency.Replace.Version
|
|
||||||
}
|
|
||||||
if dependency.Version != "" {
|
|
||||||
return dependency.Version
|
|
||||||
}
|
|
||||||
return "local"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "unknown"
|
|
||||||
}
|
|
||||||
|
|
||||||
func mustParseURL(raw string) *url.URL {
|
|
||||||
parsed, err := url.Parse(raw)
|
|
||||||
if err != nil {
|
|
||||||
return &url.URL{}
|
|
||||||
}
|
|
||||||
return parsed
|
|
||||||
}
|
|
||||||
|
|
||||||
func chooseFile(w fyne.Window, target *widget.Entry) {
|
|
||||||
fileDialog := dialog.NewFileOpen(func(uri fyne.URIReadCloser, err error) {
|
|
||||||
if err != nil || uri == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
target.SetText(uri.URI().Path())
|
|
||||||
}, w)
|
|
||||||
fileDialog.Resize(fyne.NewSize(900, 640))
|
|
||||||
fileDialog.Show()
|
|
||||||
}
|
|
||||||
|
|
||||||
func chooseFolder(w fyne.Window, target *widget.Entry) {
|
|
||||||
folderDialog := dialog.NewFolderOpen(func(uri fyne.ListableURI, err error) {
|
|
||||||
if err != nil || uri == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
target.SetText(uri.Path())
|
|
||||||
}, w)
|
|
||||||
// The default folder picker can be cramped on Windows. A larger size makes
|
|
||||||
// long paths readable and avoids forcing the user to resize it every time.
|
|
||||||
folderDialog.Resize(fyne.NewSize(900, 640))
|
|
||||||
folderDialog.Show()
|
|
||||||
}
|
|
||||||
|
|
||||||
func settingsRow(label string, value fyne.CanvasObject) fyne.CanvasObject {
|
|
||||||
caption := widget.NewLabelWithStyle(label, fyne.TextAlignLeading, fyne.TextStyle{Bold: true})
|
|
||||||
caption.Wrapping = fyne.TextTruncate
|
|
||||||
captionBox := container.New(minWidthLayout{width: settingsLabelWidth}, caption)
|
|
||||||
return container.NewBorder(nil, nil, captionBox, nil, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/url"
|
||||||
|
"runtime/debug"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/platform/filemanager"
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/storage"
|
||||||
|
|
||||||
|
"fyne.io/fyne/v2"
|
||||||
|
"fyne.io/fyne/v2/dialog"
|
||||||
|
fynestorage "fyne.io/fyne/v2/storage"
|
||||||
|
"fyne.io/fyne/v2/widget"
|
||||||
|
)
|
||||||
|
|
||||||
|
func fyneVersion() string {
|
||||||
|
info, ok := debug.ReadBuildInfo()
|
||||||
|
if !ok {
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
for _, dependency := range info.Deps {
|
||||||
|
if dependency.Path == "fyne.io/fyne/v2" {
|
||||||
|
if dependency.Replace != nil && dependency.Replace.Version != "" {
|
||||||
|
return dependency.Replace.Version
|
||||||
|
}
|
||||||
|
if dependency.Version != "" {
|
||||||
|
return dependency.Version
|
||||||
|
}
|
||||||
|
return "local"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustParseURL(raw string) *url.URL {
|
||||||
|
parsed, err := url.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
return &url.URL{}
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
// chooseFile opens a file picker that writes the chosen path into target. A
|
||||||
|
// nil filter offers every file, as job_dialog.go's command browser wants;
|
||||||
|
// chooseJSONFile passed an extension filter here before the two were merged,
|
||||||
|
// since they differed only by that one call.
|
||||||
|
func chooseFile(w fyne.Window, target *widget.Entry, filter fynestorage.FileFilter) {
|
||||||
|
fileDialog := dialog.NewFileOpen(func(uri fyne.URIReadCloser, err error) {
|
||||||
|
if err != nil || uri == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
target.SetText(uri.URI().Path())
|
||||||
|
}, w)
|
||||||
|
if filter != nil {
|
||||||
|
fileDialog.SetFilter(filter)
|
||||||
|
}
|
||||||
|
fileDialog.Resize(fyne.NewSize(900, 640))
|
||||||
|
fileDialog.Show()
|
||||||
|
}
|
||||||
|
|
||||||
|
// chooseJSONFile is chooseFile restricted to .json files, used for the jobs
|
||||||
|
// file so the picker does not list every file in the folder. The entry stays
|
||||||
|
// editable, which is how a path to a file that does not exist yet is entered.
|
||||||
|
func chooseJSONFile(w fyne.Window, target *widget.Entry) {
|
||||||
|
chooseFile(w, target, fynestorage.NewExtensionFileFilter([]string{".json"}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func chooseFolder(w fyne.Window, target *widget.Entry) {
|
||||||
|
folderDialog := dialog.NewFolderOpen(func(uri fyne.ListableURI, err error) {
|
||||||
|
if err != nil || uri == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
target.SetText(uri.Path())
|
||||||
|
}, w)
|
||||||
|
// The default folder picker can be cramped on Windows. A larger size makes
|
||||||
|
// long paths readable and avoids forcing the user to resize it every time.
|
||||||
|
folderDialog.Resize(fyne.NewSize(900, 640))
|
||||||
|
folderDialog.Show()
|
||||||
|
}
|
||||||
|
|
||||||
|
// settingsFolderPath resolves what a directory field currently points at,
|
||||||
|
// applying the same relative-path rule the store uses when it loads the config
|
||||||
|
// so the folder that opens is the one the setting would use. Blank text has no
|
||||||
|
// folder to open and yields an empty path.
|
||||||
|
func settingsFolderPath(appDir string, text string) string {
|
||||||
|
trimmed := strings.TrimSpace(text)
|
||||||
|
if trimmed == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return storage.ResolveConfiguredPath(appDir, trimmed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// openFolder reveals dir in the desktop file manager. A folder that is not set
|
||||||
|
// or cannot be opened (most often: it does not exist yet, because the logs
|
||||||
|
// directory is created on the first run) is reported in a dialog rather than
|
||||||
|
// leaving the button looking dead.
|
||||||
|
func openFolder(w fyne.Window, dir string) {
|
||||||
|
if dir == "" {
|
||||||
|
dialog.ShowError(errors.New("no folder is set"), w)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := filemanager.Open(dir); err != nil {
|
||||||
|
dialog.ShowError(err, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/app"
|
||||||
|
|
||||||
|
"fyne.io/fyne/v2"
|
||||||
|
"fyne.io/fyne/v2/container"
|
||||||
|
"fyne.io/fyne/v2/layout"
|
||||||
|
"fyne.io/fyne/v2/theme"
|
||||||
|
"fyne.io/fyne/v2/widget"
|
||||||
|
)
|
||||||
|
|
||||||
|
// settingsFormFields groups every widget the Settings tab's two-column layout
|
||||||
|
// arranges. It exists so newSettingsLayout takes one argument instead of
|
||||||
|
// twenty, and so a widget added in settingsView is added to exactly one
|
||||||
|
// struct literal rather than threaded through a long parameter list.
|
||||||
|
type settingsFormFields struct {
|
||||||
|
startOnLogin *widget.Check
|
||||||
|
autostartStatus *widget.Label
|
||||||
|
minimizeToTray *widget.Check
|
||||||
|
notifications *widget.Check
|
||||||
|
themeSelect *widget.Select
|
||||||
|
executionModeSelect *widget.Select
|
||||||
|
overlapPolicySelect *widget.Select
|
||||||
|
defaultTimeout *widget.Entry
|
||||||
|
configPath string
|
||||||
|
jobsFile *widget.Entry
|
||||||
|
jobsFileBrowse *widget.Button
|
||||||
|
logsDir *widget.Entry
|
||||||
|
logsDirOpen *widget.Button
|
||||||
|
logsDirBrowse *widget.Button
|
||||||
|
maxLogFiles *widget.Entry
|
||||||
|
maxLogAgeDays *widget.Entry
|
||||||
|
saveSettings *widget.Button
|
||||||
|
cancelSettings *widget.Button
|
||||||
|
restoreDefaults *widget.Button
|
||||||
|
settingsStatus *widget.Label
|
||||||
|
}
|
||||||
|
|
||||||
|
// newSettingsLayout assembles the Settings tab from its fields: a two-column
|
||||||
|
// grid (Application/Queue on the left, Storage/About on the right) with the
|
||||||
|
// Save/Cancel/Defaults row below.
|
||||||
|
func newSettingsLayout(f settingsFormFields) fyne.CanvasObject {
|
||||||
|
// capW is measured once from every caption in the tab so all rows —
|
||||||
|
// Application, Queue, Storage, About — share one value column start,
|
||||||
|
// instead of each settingsRow call re-measuring its own single caption.
|
||||||
|
capW := captionColumnWidth(settingsCaptions...)
|
||||||
|
|
||||||
|
// The form is split into two columns so a wide window uses its horizontal
|
||||||
|
// space instead of stretching into one tall strip. The left column holds the
|
||||||
|
// toggles (Application, Queue); the right holds the editable Storage fields and
|
||||||
|
// the read-only About block. Save spans the full width below both columns.
|
||||||
|
leftColumn := container.NewVBox(
|
||||||
|
settingsSection("Application", rowOverlap(),
|
||||||
|
settingsRow(capW, "Autostart", f.startOnLogin),
|
||||||
|
// Autostart status sits on its own row, aligned under the checkbox via an
|
||||||
|
// empty caption, so the Application section fits in a half-width column.
|
||||||
|
settingsRow(capW, "", f.autostartStatus),
|
||||||
|
settingsRow(capW, "Tray", f.minimizeToTray),
|
||||||
|
settingsRow(capW, "Notifications", f.notifications),
|
||||||
|
// Theme is the one row here whose value is not text: the Select paints
|
||||||
|
// a box out to the row's edge, so the section's overlap would leave it
|
||||||
|
// flush against the Notifications checkbox. Cancelling the overlap for
|
||||||
|
// this row alone restores the gap the checkbox rows have.
|
||||||
|
cancelRowOverlap(settingsRow(capW, "Theme", f.themeSelect)),
|
||||||
|
),
|
||||||
|
widget.NewSeparator(),
|
||||||
|
// Queue used to inline its own container.NewVBox at the theme's default
|
||||||
|
// spacing; settingsSection now takes that spacing explicitly so both
|
||||||
|
// idioms for "a titled block of rows" collapse into one constructor.
|
||||||
|
settingsSection("Queue", theme.Padding(),
|
||||||
|
settingsRow(capW, "Execution mode", f.executionModeSelect),
|
||||||
|
settingsRow(capW, "Default overlap policy", f.overlapPolicySelect),
|
||||||
|
settingsRow(capW, "Default timeout (s)", f.defaultTimeout),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
// Truncating keeps a long config path from forcing the Settings tab's
|
||||||
|
// minimum width to track the path length instead of the layout itself.
|
||||||
|
configPathLabel := widget.NewLabel(f.configPath)
|
||||||
|
configPathLabel.Truncation = fyne.TextTruncateClip
|
||||||
|
rightColumn := container.NewVBox(
|
||||||
|
settingsSection("Storage", theme.Padding(),
|
||||||
|
settingsRow(capW, "Config JSON", configPathLabel),
|
||||||
|
settingsRow(capW, "Jobs file", container.NewBorder(nil, nil, nil, f.jobsFileBrowse, f.jobsFile)),
|
||||||
|
// Browse stays rightmost so it lines up with the Jobs file row
|
||||||
|
// above it; Open sits between it and the path it opens.
|
||||||
|
settingsRow(capW, "Logs directory", container.NewBorder(nil, nil, nil, container.NewHBox(f.logsDirOpen, f.logsDirBrowse), f.logsDir)),
|
||||||
|
settingsRow(capW, "Max log files", f.maxLogFiles),
|
||||||
|
settingsRow(capW, "Max log age days", f.maxLogAgeDays),
|
||||||
|
),
|
||||||
|
widget.NewSeparator(),
|
||||||
|
settingsSection("About", rowOverlap(),
|
||||||
|
settingsRow(capW, "GoSentry", widget.NewLabel(app.Version)),
|
||||||
|
settingsRow(capW, "Go", widget.NewLabel(runtime.Version())),
|
||||||
|
settingsRow(capW, "Fyne", widget.NewLabel(fyneVersion())),
|
||||||
|
settingsRow(capW, "Repository", widget.NewHyperlink(projectRepositoryURL, mustParseURL(projectRepositoryURL))),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
// The two columns sit in a top-aligned grid; Save spans the full width below.
|
||||||
|
// Wrapping the whole thing in a vertical scroll keeps its minimum height small
|
||||||
|
// so it does not dictate the window's minimum height (AppTabs sizes to the
|
||||||
|
// tallest tab) and it scrolls on short 720p screens.
|
||||||
|
// The button row sits right below the separator's hairline, which reads as
|
||||||
|
// tighter than the other vertical gaps in the tab (those separate whole
|
||||||
|
// sections, not a single thin line from a row of buttons). A top pad the
|
||||||
|
// height of the default padding closes that gap up to match, and a left pad
|
||||||
|
// indents the buttons 4px from the edge the layout promises.
|
||||||
|
return container.NewVScroll(container.NewPadded(container.NewVBox(
|
||||||
|
container.NewGridWithColumns(2, leftColumn, rightColumn),
|
||||||
|
widget.NewSeparator(),
|
||||||
|
container.New(
|
||||||
|
layout.NewCustomPaddedLayout(2*theme.Padding(), 0, theme.Padding(), 0),
|
||||||
|
// Save/Cancel/Defaults share one row with the status so an empty status
|
||||||
|
// (the common case) does not leave a blank line above the separator. The
|
||||||
|
// status appears beside the buttons once a save reports a result.
|
||||||
|
container.NewHBox(f.saveSettings, f.cancelSettings, f.restoreDefaults, f.settingsStatus),
|
||||||
|
),
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// settingsSection groups a bold header above its rows, using the given
|
||||||
|
// vertical spacing between them. Application and About pass rowOverlap() so
|
||||||
|
// the block reads as one compact unit; Queue and Storage pass theme.Padding()
|
||||||
|
// (the same spacing container.NewVBox would use) so their entry-heavy rows
|
||||||
|
// keep a visible gap. One constructor for "a titled block of rows" rather
|
||||||
|
// than two spellings of it.
|
||||||
|
func settingsSection(title string, spacing float32, rows ...fyne.CanvasObject) fyne.CanvasObject {
|
||||||
|
children := make([]fyne.CanvasObject, 0, len(rows)+1)
|
||||||
|
children = append(children, widget.NewLabelWithStyle(title, fyne.TextAlignLeading, fyne.TextStyle{Bold: true}))
|
||||||
|
children = append(children, rows...)
|
||||||
|
return container.New(layout.NewCustomPaddedVBoxLayout(spacing), children...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func settingsRow(captionWidth float32, label string, value fyne.CanvasObject) fyne.CanvasObject {
|
||||||
|
caption := widget.NewLabelWithStyle(label, fyne.TextAlignLeading, fyne.TextStyle{Bold: true})
|
||||||
|
caption.Truncation = fyne.TextTruncateClip
|
||||||
|
captionBox := container.New(minWidthLayout{width: captionWidth}, caption)
|
||||||
|
return container.NewBorder(nil, nil, captionBox, nil, value)
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"fyne.io/fyne/v2"
|
||||||
|
fynestorage "fyne.io/fyne/v2/storage"
|
||||||
|
"fyne.io/fyne/v2/test"
|
||||||
|
"fyne.io/fyne/v2/widget"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSettingsFolderPath covers the path the "Open" button beside the logs
|
||||||
|
// directory hands to the file manager: blank means nothing to open, a relative
|
||||||
|
// directory resolves against the application directory (as the store does),
|
||||||
|
// and an absolute directory is used as typed. Both directories come from
|
||||||
|
// t.TempDir so the absolute case is genuinely absolute on Windows too.
|
||||||
|
func TestSettingsFolderPath(t *testing.T) {
|
||||||
|
appDir := t.TempDir()
|
||||||
|
absolute := filepath.Join(t.TempDir(), "logs")
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
text string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "empty", text: "", want: ""},
|
||||||
|
{name: "whitespace only", text: " ", want: ""},
|
||||||
|
{name: "relative", text: "logs", want: filepath.Join(appDir, "logs")},
|
||||||
|
{name: "relative with spaces around it", text: " logs ", want: filepath.Join(appDir, "logs")},
|
||||||
|
{name: "absolute", text: absolute, want: absolute},
|
||||||
|
}
|
||||||
|
for _, testCase := range cases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
if got := settingsFolderPath(appDir, testCase.text); got != testCase.want {
|
||||||
|
t.Errorf("settingsFolderPath(%q, %q) = %q, want %q", appDir, testCase.text, got, testCase.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSettingsRowStretchesItsControl is the property that makes F2's removal
|
||||||
|
// of settingsControlWidth invisible: settingsRow puts the value in a Border
|
||||||
|
// centre slot, which already stretches it to the column width on its own, so
|
||||||
|
// wrapping it in a fixed-width layout was redundant.
|
||||||
|
func TestSettingsRowStretchesItsControl(t *testing.T) {
|
||||||
|
entry := widget.NewEntry()
|
||||||
|
row := settingsRow(captionColumnWidth("Label"), "Label", entry)
|
||||||
|
|
||||||
|
baseWidth := entry.Size().Width
|
||||||
|
wide := fyne.NewSize(row.MinSize().Width+200, row.MinSize().Height)
|
||||||
|
row.Resize(wide)
|
||||||
|
|
||||||
|
// Only the caption column and one inter-column padding come out of the
|
||||||
|
// extra width; the rest must reach the control. Requiring most of the
|
||||||
|
// 200px growth to show up on the entry is what a reinstated fixed-width
|
||||||
|
// wrapper around it would break.
|
||||||
|
if got := entry.Size().Width; got < baseWidth+150 {
|
||||||
|
t.Errorf("control did not stretch to fill the row: entry width = %v, want at least %v", got, baseWidth+150)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestChooseFileAppliesFilter is the coverage for the deduplicated file picker
|
||||||
|
// (chooseFile absorbed chooseJSONFile's SetFilter call behind a nil-means-none
|
||||||
|
// filter argument): both a nil filter (job_dialog.go's command browser) and a
|
||||||
|
// concrete one (chooseJSONFile) must open a dialog without panicking, and the
|
||||||
|
// dialog must actually appear as a canvas overlay either way.
|
||||||
|
func TestChooseFileAppliesFilter(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
w := testApp.NewWindow("test")
|
||||||
|
defer w.Close()
|
||||||
|
|
||||||
|
target := widget.NewEntry()
|
||||||
|
|
||||||
|
chooseFile(w, target, nil)
|
||||||
|
if w.Canvas().Overlays().Top() == nil {
|
||||||
|
t.Fatal("chooseFile(nil filter) did not open a dialog")
|
||||||
|
}
|
||||||
|
w.Canvas().Overlays().Top().Hide()
|
||||||
|
|
||||||
|
chooseJSONFile(w, target)
|
||||||
|
if w.Canvas().Overlays().Top() == nil {
|
||||||
|
t.Fatal("chooseJSONFile did not open a dialog")
|
||||||
|
}
|
||||||
|
w.Canvas().Overlays().Top().Hide()
|
||||||
|
|
||||||
|
// Exercising a concrete filter directly through chooseFile as well, so the
|
||||||
|
// filter parameter itself (not just chooseJSONFile's use of it) is covered.
|
||||||
|
chooseFile(w, target, fynestorage.NewExtensionFileFilter([]string{".json"}))
|
||||||
|
if w.Canvas().Overlays().Top() == nil {
|
||||||
|
t.Fatal("chooseFile(non-nil filter) did not open a dialog")
|
||||||
|
}
|
||||||
|
w.Canvas().Overlays().Top().Hide()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSettingsCaptionsCoverEveryRow is the settings-tab analog of F10's
|
||||||
|
// jobs-details guard: every caption settingsView actually uses in a row must
|
||||||
|
// be present in settingsCaptions and measure no wider than
|
||||||
|
// captionColumnWidth's result for that list, or a caption added to a row
|
||||||
|
// without adding it to settingsCaptions would silently misalign that column.
|
||||||
|
func TestSettingsCaptionsCoverEveryRow(t *testing.T) {
|
||||||
|
testApp := test.NewApp()
|
||||||
|
defer testApp.Quit()
|
||||||
|
|
||||||
|
capW := captionColumnWidth(settingsCaptions...)
|
||||||
|
for _, c := range settingsCaptions {
|
||||||
|
if c == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if w := widget.NewLabelWithStyle(c, fyne.TextAlignLeading, fyne.TextStyle{Bold: true}).MinSize().Width; w > capW {
|
||||||
|
t.Errorf("caption %q measures %v, wider than captionColumnWidth's %v", c, w, capW)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image/color"
|
||||||
|
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
||||||
|
|
||||||
|
"fyne.io/fyne/v2"
|
||||||
|
"fyne.io/fyne/v2/theme"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The GoSentry theme derives its palette from the logo and app icon, which use
|
||||||
|
// exactly two brand colors on white: deep teal (the wordmark and icon tile) and
|
||||||
|
// amber (the "G" gauge and the terminal prompt). Everything below extends those
|
||||||
|
// two into a working UI palette:
|
||||||
|
// - teal is the primary color (buttons, selection, the active tab indicator),
|
||||||
|
// - amber is the focus accent,
|
||||||
|
// - success/warning/error carry the job run states a scheduler needs.
|
||||||
|
//
|
||||||
|
// The dark variant leans into the app icon: deep teal surfaces so the window
|
||||||
|
// reads as the icon "come to life", with a lifted teal primary and a brightened
|
||||||
|
// error red so both stay legible against the dark teal.
|
||||||
|
var (
|
||||||
|
brandTeal = color.NRGBA{R: 0x0A, G: 0x4A, B: 0x58, A: 0xFF} // wordmark + icon tile
|
||||||
|
brandTealMid = color.NRGBA{R: 0x0F, G: 0x6E, B: 0x82, A: 0xFF} // link on light
|
||||||
|
brandTealLight = color.NRGBA{R: 0x3D, G: 0x97, B: 0xA9, A: 0xFF} // primary on dark
|
||||||
|
brandAmber = color.NRGBA{R: 0xF7, G: 0xA8, B: 0x0C, A: 0xFF} // the "G" + prompt
|
||||||
|
)
|
||||||
|
|
||||||
|
// gosentryLight and gosentryDark hold only the colors the brand theme overrides;
|
||||||
|
// every other ColorName falls through to the base theme, which keeps neutral
|
||||||
|
// surfaces and text contrast correct in both variants.
|
||||||
|
//
|
||||||
|
// The light variant is intentionally more than an accent swap: the window canvas
|
||||||
|
// is a soft teal while inputs, menus, and dialogs stay white, so cards and fields
|
||||||
|
// lift off a branded background instead of sitting on plain gray. Text stays dark
|
||||||
|
// (delegated to the base foreground), which keeps high contrast on both the teal
|
||||||
|
// canvas and the white surfaces.
|
||||||
|
var gosentryLight = map[fyne.ThemeColorName]color.Color{
|
||||||
|
theme.ColorNamePrimary: brandTeal,
|
||||||
|
theme.ColorNameFocus: brandAmber,
|
||||||
|
theme.ColorNameHyperlink: brandTealMid,
|
||||||
|
theme.ColorNameSuccess: color.NRGBA{R: 0x2E, G: 0x9E, B: 0x5B, A: 0xFF},
|
||||||
|
theme.ColorNameWarning: brandAmber,
|
||||||
|
theme.ColorNameError: color.NRGBA{R: 0xD6, G: 0x45, B: 0x45, A: 0xFF},
|
||||||
|
theme.ColorNameBackground: color.NRGBA{R: 0xDC, G: 0xEA, B: 0xED, A: 0xFF}, // teal canvas
|
||||||
|
theme.ColorNameButton: color.NRGBA{R: 0xFF, G: 0xFF, B: 0xFF, A: 0xFF},
|
||||||
|
theme.ColorNameInputBackground: color.NRGBA{R: 0xFF, G: 0xFF, B: 0xFF, A: 0xFF},
|
||||||
|
theme.ColorNameMenuBackground: color.NRGBA{R: 0xFF, G: 0xFF, B: 0xFF, A: 0xFF},
|
||||||
|
theme.ColorNameOverlayBackground: color.NRGBA{R: 0xFF, G: 0xFF, B: 0xFF, A: 0xFF},
|
||||||
|
theme.ColorNameHeaderBackground: color.NRGBA{R: 0xC7, G: 0xDE, B: 0xE2, A: 0xFF}, // deeper teal for table headers
|
||||||
|
theme.ColorNameSeparator: color.NRGBA{R: 0xB4, G: 0xD0, B: 0xD6, A: 0xFF},
|
||||||
|
theme.ColorNameInputBorder: color.NRGBA{R: 0xB4, G: 0xD0, B: 0xD6, A: 0xFF},
|
||||||
|
theme.ColorNameSelection: color.NRGBA{R: 0x0A, G: 0x4A, B: 0x58, A: 0x33},
|
||||||
|
theme.ColorNameHover: color.NRGBA{R: 0x0A, G: 0x4A, B: 0x58, A: 0x14},
|
||||||
|
}
|
||||||
|
|
||||||
|
var gosentryDark = map[fyne.ThemeColorName]color.Color{
|
||||||
|
theme.ColorNamePrimary: brandTealLight,
|
||||||
|
theme.ColorNameFocus: brandAmber,
|
||||||
|
theme.ColorNameHyperlink: color.NRGBA{R: 0x6B, G: 0xB8, B: 0xCA, A: 0xFF},
|
||||||
|
theme.ColorNameSuccess: color.NRGBA{R: 0x46, G: 0xB8, B: 0x7A, A: 0xFF},
|
||||||
|
theme.ColorNameWarning: brandAmber,
|
||||||
|
theme.ColorNameError: color.NRGBA{R: 0xF2, G: 0x6D, B: 0x6D, A: 0xFF},
|
||||||
|
theme.ColorNameForeground: color.NRGBA{R: 0xEA, G: 0xF2, B: 0xF4, A: 0xFF},
|
||||||
|
theme.ColorNamePlaceHolder: color.NRGBA{R: 0x9B, G: 0xB4, B: 0xBC, A: 0xFF},
|
||||||
|
theme.ColorNameBackground: color.NRGBA{R: 0x0B, G: 0x20, B: 0x27, A: 0xFF},
|
||||||
|
theme.ColorNameButton: color.NRGBA{R: 0x14, G: 0x3A, B: 0x45, A: 0xFF},
|
||||||
|
theme.ColorNameInputBackground: color.NRGBA{R: 0x0F, G: 0x2E, B: 0x37, A: 0xFF},
|
||||||
|
theme.ColorNameMenuBackground: color.NRGBA{R: 0x0F, G: 0x2E, B: 0x37, A: 0xFF},
|
||||||
|
theme.ColorNameOverlayBackground: color.NRGBA{R: 0x0F, G: 0x2E, B: 0x37, A: 0xFF},
|
||||||
|
theme.ColorNameHeaderBackground: color.NRGBA{R: 0x0B, G: 0x20, B: 0x27, A: 0xFF},
|
||||||
|
theme.ColorNameSeparator: color.NRGBA{R: 0x20, G: 0x50, B: 0x5C, A: 0xFF},
|
||||||
|
theme.ColorNameInputBorder: color.NRGBA{R: 0x20, G: 0x50, B: 0x5C, A: 0xFF},
|
||||||
|
theme.ColorNameSelection: color.NRGBA{R: 0x3D, G: 0x97, B: 0xA9, A: 0x55},
|
||||||
|
theme.ColorNameHover: color.NRGBA{R: 0xFF, G: 0xFF, B: 0xFF, A: 0x14},
|
||||||
|
}
|
||||||
|
|
||||||
|
// gosentryTheme wraps the default theme, overriding only brand colors and
|
||||||
|
// delegating fonts, icons, sizes, and unbranded colors to it. Embedding the base
|
||||||
|
// keeps the theme robust against Fyne adding new ColorNames — anything not in the
|
||||||
|
// override maps still resolves to a sensible default.
|
||||||
|
type gosentryTheme struct {
|
||||||
|
base fyne.Theme
|
||||||
|
}
|
||||||
|
|
||||||
|
func newGoSentryTheme() fyne.Theme {
|
||||||
|
return gosentryTheme{base: theme.DefaultTheme()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t gosentryTheme) Color(name fyne.ThemeColorName, variant fyne.ThemeVariant) color.Color {
|
||||||
|
overrides := gosentryLight
|
||||||
|
if variant == theme.VariantDark {
|
||||||
|
overrides = gosentryDark
|
||||||
|
}
|
||||||
|
if c, ok := overrides[name]; ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
return t.base.Color(name, variant)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t gosentryTheme) Font(style fyne.TextStyle) fyne.Resource { return t.base.Font(style) }
|
||||||
|
func (t gosentryTheme) Icon(name fyne.ThemeIconName) fyne.Resource { return t.base.Icon(name) }
|
||||||
|
func (t gosentryTheme) Size(name fyne.ThemeSizeName) float32 { return t.base.Size(name) }
|
||||||
|
|
||||||
|
// themeFor maps a stored Theme choice to a concrete fyne.Theme. Anything other
|
||||||
|
// than the explicit GoSentry choice (including the empty/legacy value) keeps
|
||||||
|
// Fyne's built-in theme.
|
||||||
|
func themeFor(choice domain.Theme) fyne.Theme {
|
||||||
|
if choice == domain.ThemeGoSentry {
|
||||||
|
return newGoSentryTheme()
|
||||||
|
}
|
||||||
|
return theme.DefaultTheme()
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyTheme installs the theme for the given choice on the running app. Fyne
|
||||||
|
// refreshes every canvas when the theme changes, so this works both at startup
|
||||||
|
// and when the user switches themes from Settings.
|
||||||
|
func applyTheme(a fyne.App, choice domain.Theme) {
|
||||||
|
a.Settings().SetTheme(themeFor(choice))
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image/color"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.mixdep.ru/mix/gosentry/src/domain"
|
||||||
|
|
||||||
|
"fyne.io/fyne/v2"
|
||||||
|
"fyne.io/fyne/v2/theme"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The GoSentry theme must expose the brand colors on the semantically correct
|
||||||
|
// ColorNames in each variant. These are the touchpoints a user actually sees —
|
||||||
|
// the primary color drives buttons and the active tab, focus drives the accent —
|
||||||
|
// so they are worth pinning against accidental edits to the palette maps.
|
||||||
|
func TestGoSentryThemeBrandColors(t *testing.T) {
|
||||||
|
th := newGoSentryTheme()
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
color fyne.ThemeColorName
|
||||||
|
variant int
|
||||||
|
want color.Color
|
||||||
|
}{
|
||||||
|
{"light primary is teal", theme.ColorNamePrimary, 0, brandTeal},
|
||||||
|
{"light focus is amber", theme.ColorNameFocus, 0, brandAmber},
|
||||||
|
{"light canvas is a teal tint", theme.ColorNameBackground, 0, color.NRGBA{R: 0xDC, G: 0xEA, B: 0xED, A: 0xFF}},
|
||||||
|
{"light inputs stay white", theme.ColorNameInputBackground, 0, color.NRGBA{R: 0xFF, G: 0xFF, B: 0xFF, A: 0xFF}},
|
||||||
|
{"dark primary is lifted teal", theme.ColorNamePrimary, 1, brandTealLight},
|
||||||
|
{"dark focus is amber", theme.ColorNameFocus, 1, brandAmber},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
variant := theme.VariantLight
|
||||||
|
if tc.variant == 1 {
|
||||||
|
variant = theme.VariantDark
|
||||||
|
}
|
||||||
|
got := th.Color(tc.color, variant)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("%s: Color(%s) = %v, want %v", tc.name, tc.color, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unbranded color names must fall through to the base theme rather than render as
|
||||||
|
// zero-value (transparent) colors, so the theme only recolors what it intends to.
|
||||||
|
func TestGoSentryThemeDelegatesUnbrandedColors(t *testing.T) {
|
||||||
|
th := newGoSentryTheme()
|
||||||
|
base := theme.DefaultTheme()
|
||||||
|
// ScrollBar is not in either override map, so it must match the base theme.
|
||||||
|
got := th.Color(theme.ColorNameScrollBar, theme.VariantDark)
|
||||||
|
want := base.Color(theme.ColorNameScrollBar, theme.VariantDark)
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("unbranded ColorNameScrollBar = %v, want base %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// themeFor maps the stored choice to the right theme: the GoSentry choice yields
|
||||||
|
// the branded teal primary; every other value (including the empty legacy value)
|
||||||
|
// yields the default theme, whose primary is not the brand teal.
|
||||||
|
func TestThemeForChoice(t *testing.T) {
|
||||||
|
gosentry := themeFor(domain.ThemeGoSentry)
|
||||||
|
if got := gosentry.Color(theme.ColorNamePrimary, theme.VariantLight); got != brandTeal {
|
||||||
|
t.Errorf("themeFor(gosentry) primary = %v, want brand teal %v", got, brandTeal)
|
||||||
|
}
|
||||||
|
for _, choice := range []domain.Theme{domain.ThemeDefault, ""} {
|
||||||
|
def := themeFor(choice)
|
||||||
|
if got := def.Color(theme.ColorNamePrimary, theme.VariantLight); got == brandTeal {
|
||||||
|
t.Errorf("themeFor(%q) should not use the brand teal primary", choice)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The dropdown label helpers must round-trip, and the empty/legacy value must map
|
||||||
|
// to the Default label so the select never shows a blank option.
|
||||||
|
func TestThemeLabelRoundTrip(t *testing.T) {
|
||||||
|
if got := themeFromLabel(themeLabel(domain.ThemeGoSentry)); got != domain.ThemeGoSentry {
|
||||||
|
t.Errorf("round-trip gosentry = %q", got)
|
||||||
|
}
|
||||||
|
if got := themeFromLabel(themeLabel(domain.ThemeDefault)); got != domain.ThemeDefault {
|
||||||
|
t.Errorf("round-trip default = %q", got)
|
||||||
|
}
|
||||||
|
if got := themeLabel(""); got != themeLabelDefault {
|
||||||
|
t.Errorf("empty theme label = %q, want %q", got, themeLabelDefault)
|
||||||
|
}
|
||||||
|
}
|
||||||