Compare commits

...
20 Commits
Author SHA1 Message Date
lukaszraczyloandGitHub 2d9c28657b Update go.mod and go.sum (#3) 2025-12-12 03:28:24 +00:00
lukaszraczyloandGitHub a8acb2d480 Update go.mod and go.sum (#2) 2025-12-09 03:25:21 +00:00
lukaszraczyloandGitHub 29263dc8a2 gosec govulncheck runs (#1)
* gosec govulncheck runs

* Fix flaky TestRateLimiter_Matrix test

The test was failing due to two issues:
1. Test name generation used invalid character conversion (string(rune('0'+limit)))
   which produced non-printable characters for limits >= 10
2. Using 10ms windows with 100 requests caused race conditions - early requests
   would expire before all 100 were made, allowing the 101st request

Changed to use struct-based test cases with proper fmt.Sprintf naming and
a consistent 1-second window that won't expire during rapid test execution.
2025-12-09 01:07:16 +00:00
lukaszraczylo 27d5011ab1 fix: remove unnecessary verified parameter from homebrew cask
The verified parameter is only needed when the URL domain differs
from the homepage domain. Since both point to github.com, Homebrew
audit flags this as unnecessary.
2025-12-08 02:08:00 +00:00
lukaszraczylo 51119b3694 Use shared PR workflow 2025-12-08 01:31:55 +00:00
lukaszraczylo 1b66f4c6f9 Trigger autoupdater 2025-12-08 01:11:32 +00:00
lukaszraczylo 8c022fa0d2 fixup! fixup! Move to casks. 2025-12-07 15:53:46 +00:00
lukaszraczylo 5d8c72d75f fixup! Move to casks. 2025-12-07 14:58:25 +00:00
lukaszraczylo 2a6f0ee244 Move to casks. 2025-12-07 14:49:14 +00:00
lukaszraczylo 99f215cb7c Move build and release to shared workflow 2025-12-07 13:33:46 +00:00
lukaszraczylo 6eb634bfd0 Move to shared workflows. 2025-12-07 13:25:56 +00:00
lukaszraczylo 4bf0dd2cdf Update the autoupdate workflow 2025-12-07 12:36:24 +00:00
lukaszraczylo 70ac227613 Update autoupdate workflow. LOL. 2025-12-03 00:47:35 +00:00
lukaszraczylo 90e0375a83 Remove unused functions. 2025-12-02 18:19:01 +00:00
lukaszraczyloandgithub-actions[bot] 8445e50dc8 Update go.mod and go.sum 2025-12-02 03:26:03 +00:00
lukaszraczylo e1b9c15a2a fixup! fixup! Fix autoupdate workflow 2025-12-01 14:39:46 +00:00
lukaszraczyloandgithub-actions[bot] c442eade9e Update go.mod and go.sum 2025-12-01 14:32:58 +00:00
lukaszraczylo acc80882e2 fixup! Fix autoupdate workflow 2025-12-01 14:31:00 +00:00
lukaszraczylo 5e24b13595 Fix autoupdate workflow 2025-12-01 14:24:59 +00:00
lukaszraczylo 76e364ca3e bugfix: Deleted hosts were lingering in the TUI list. 2025-11-29 02:38:12 +00:00
26 changed files with 297 additions and 370 deletions
+12 -40
View File
@@ -1,47 +1,19 @@
name: AutoUpdate name: Autoupdate go.mod and go.sum
on: on:
workflow_dispatch:
schedule: schedule:
- cron: "0 3 * * *" - cron: "0 3 * * *"
workflow_dispatch:
permissions:
contents: write
actions: write
pull-requests: write
jobs: jobs:
prepare: autoupdate:
runs-on: ubuntu-latest uses: lukaszraczylo/shared-actions/.github/workflows/go-autoupdate.yaml@main
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v5
with: with:
go-version: "1.24" go-version: ">=1.24"
cache: true release-workflow: "release.yml"
secrets: inherit
- name: Install dependencies
run: go get ./...
test:
needs: prepare
runs-on: ubuntu-latest
container: golang:1
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install dependencies
run: apt-get update && apt-get install -y ca-certificates make
- name: Tidy and update modules
run: |
go mod tidy
go get -u -v ./...
- name: Run tests
run: CI_RUN=${CI} go test -v ./...
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "Update go.mod and go.sum"
file_pattern: "go.mod go.sum"
+22
View File
@@ -0,0 +1,22 @@
name: Pull Request
on:
pull_request:
branches:
- main
push:
branches:
- "**"
- "!main"
permissions:
contents: write
actions: write
pull-requests: write
security-events: write
jobs:
pr-checks:
uses: lukaszraczylo/shared-actions/.github/workflows/go-pr.yaml@main
with:
go-version: ">=1.24"
+6 -76
View File
@@ -10,82 +10,12 @@ on:
- "go.sum" - "go.sum"
workflow_dispatch: workflow_dispatch:
jobs: permissions:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: "1.24"
- name: Run tests
run: go test -race -v ./...
version:
needs: test
runs-on: ubuntu-latest
outputs:
version: ${{ steps.version_formatted.outputs.version }}
version_tag: ${{ steps.version_formatted.outputs.version_tag }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Calculate version
id: semver
uses: lukaszraczylo/semver-generator@v1
with:
config_file: semver.yaml
repository_local: true
- name: Format version
id: version_formatted
run: |
VERSION="${{ steps.semver.outputs.semantic_version }}"
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "version_tag=v${VERSION}" >> $GITHUB_OUTPUT
- name: Print version
run: |
echo "Version: ${{ steps.version_formatted.outputs.version }}"
echo "Version tag: ${{ steps.version_formatted.outputs.version_tag }}"
release:
needs: version
if: needs.version.outputs.version_tag != ''
runs-on: ubuntu-latest
permissions:
contents: write contents: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Go jobs:
uses: actions/setup-go@v5 release:
uses: lukaszraczylo/shared-actions/.github/workflows/go-release.yaml@main
with: with:
go-version: "1.24" go-version: ">=1.24"
secrets: inherit
- name: Create and push tag
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -a ${{ needs.version.outputs.version_tag }} -m "Release ${{ needs.version.outputs.version }}"
git push origin ${{ needs.version.outputs.version_tag }}
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: "~> v2"
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
+11 -6
View File
@@ -22,7 +22,7 @@ builds:
archives: archives:
- id: lolcathost - id: lolcathost
format: tar.gz formats: [tar.gz]
name_template: "lolcathost-{{ .Version }}-{{ .Os }}-{{ .Arch }}" name_template: "lolcathost-{{ .Version }}-{{ .Os }}-{{ .Arch }}"
files: files:
- LICENSE - LICENSE
@@ -49,14 +49,19 @@ release:
draft: false draft: false
prerelease: auto prerelease: auto
brews: homebrew_casks:
- repository: - repository:
owner: lukaszraczylo owner: lukaszraczylo
name: homebrew-taps name: homebrew-taps
token: "{{ .Env.HOMEBREW_TAP_TOKEN }}" token: "{{ .Env.HOMEBREW_TAP_TOKEN }}"
directory: Formula directory: Casks
homepage: https://github.com/lukaszraczylo/lolcathost homepage: https://github.com/lukaszraczylo/lolcathost
description: "Dynamic host management tool for macOS and Linux with TUI" description: "Dynamic host management tool with TUI"
license: MIT license: MIT
test: | hooks:
system "#{bin}/lolcathost", "--version" post:
install: |
if OS.mac?
system_command "/usr/bin/xattr",
args: ["-dr", "com.apple.quarantine", "#{staged_path}/lolcathost"]
end
+7 -2
View File
@@ -50,12 +50,17 @@ lolcathost manages your `/etc/hosts` file with an interactive terminal interface
## Installation ## Installation
### Homebrew (macOS/Linux) ### Homebrew (macOS)
```bash ```bash
brew install lukaszraczylo/taps/lolcathost brew install --cask lukaszraczylo/taps/lolcathost
``` ```
> **Note**: If you previously installed via `brew install lukaszraczylo/taps/lolcathost` (formula), uninstall first:
> ```bash
> brew uninstall lolcathost
> ```
After Homebrew installation, run: After Homebrew installation, run:
```bash ```bash
+1 -1
View File
@@ -204,7 +204,7 @@ func runList() {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", status, e.Domain, e.IP, e.Alias, e.Group) fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", status, e.Domain, e.IP, e.Alias, e.Group)
} }
w.Flush() _ = w.Flush()
} }
func runOn(alias string) { func runOn(alias string) {
+2 -2
View File
@@ -276,9 +276,9 @@
<div class="glass p-6 rounded-xl"> <div class="glass p-6 rounded-xl">
<h3 class="font-semibold text-gray-900 dark:text-gray-100 mb-3 flex items-center"> <h3 class="font-semibold text-gray-900 dark:text-gray-100 mb-3 flex items-center">
<i class="fas fa-beer mr-2 text-amber-500"></i> <i class="fas fa-beer mr-2 text-amber-500"></i>
Homebrew (macOS/Linux) Homebrew (macOS)
</h3> </h3>
<pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto"><code>brew install lukaszraczylo/taps/lolcathost <pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto"><code>brew install --cask lukaszraczylo/taps/lolcathost
sudo lolcathost --install</code></pre> sudo lolcathost --install</code></pre>
</div> </div>
<div class="glass p-6 rounded-xl"> <div class="glass p-6 rounded-xl">
+5 -5
View File
@@ -8,18 +8,18 @@ require (
github.com/charmbracelet/lipgloss v1.1.0 github.com/charmbracelet/lipgloss v1.1.0
github.com/fsnotify/fsnotify v1.9.0 github.com/fsnotify/fsnotify v1.9.0
github.com/stretchr/testify v1.11.1 github.com/stretchr/testify v1.11.1
golang.org/x/sys v0.38.0 golang.org/x/sys v0.39.0
gopkg.in/yaml.v3 v3.0.1 gopkg.in/yaml.v3 v3.0.1
) )
require ( require (
github.com/atotto/clipboard v0.1.4 // indirect github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/charmbracelet/colorprofile v0.3.3 // indirect github.com/charmbracelet/colorprofile v0.4.1 // indirect
github.com/charmbracelet/x/ansi v0.11.2 // indirect github.com/charmbracelet/x/ansi v0.11.3 // indirect
github.com/charmbracelet/x/cellbuf v0.0.14 // indirect github.com/charmbracelet/x/cellbuf v0.0.14 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.6.0 // indirect github.com/clipperhouse/displaywidth v0.6.1 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect
@@ -34,5 +34,5 @@ require (
github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect github.com/rivo/uniseg v0.4.7 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/text v0.31.0 // indirect golang.org/x/text v0.32.0 // indirect
) )
+10 -10
View File
@@ -8,20 +8,20 @@ github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg= github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
github.com/charmbracelet/colorprofile v0.3.3 h1:DjJzJtLP6/NZ8p7Cgjno0CKGr7wwRJGxWUwh2IyhfAI= github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk=
github.com/charmbracelet/colorprofile v0.3.3/go.mod h1:nB1FugsAbzq284eJcjfah2nhdSLppN2NqvfotkfRYP4= github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
github.com/charmbracelet/x/ansi v0.11.2 h1:XAG3FSjiVtFvgEgGrNBkCNNYrsucAt8c6bfxHyROLLs= github.com/charmbracelet/x/ansi v0.11.3 h1:6DcVaqWI82BBVM/atTyq6yBoRLZFBsnoDoX9GCu2YOI=
github.com/charmbracelet/x/ansi v0.11.2/go.mod h1:9tY2bzX5SiJCU0iWyskjBeI2BRQfvPqI+J760Mjf+Rg= github.com/charmbracelet/x/ansi v0.11.3/go.mod h1:yI7Zslym9tCJcedxz5+WBq+eUGMJT0bM06Fqy1/Y4dI=
github.com/charmbracelet/x/cellbuf v0.0.14 h1:iUEMryGyFTelKW3THW4+FfPgi4fkmKnnaLOXuc+/Kj4= github.com/charmbracelet/x/cellbuf v0.0.14 h1:iUEMryGyFTelKW3THW4+FfPgi4fkmKnnaLOXuc+/Kj4=
github.com/charmbracelet/x/cellbuf v0.0.14/go.mod h1:P447lJl49ywBbil/KjCk2HexGh4tEY9LH0/1QrZZ9rA= github.com/charmbracelet/x/cellbuf v0.0.14/go.mod h1:P447lJl49ywBbil/KjCk2HexGh4tEY9LH0/1QrZZ9rA=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ= github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/clipperhouse/displaywidth v0.6.0 h1:k32vueaksef9WIKCNcoqRNyKbyvkvkysNYnAWz2fN4s= github.com/clipperhouse/displaywidth v0.6.1 h1:/zMlAezfDzT2xy6acHBzwIfyu2ic0hgkT83UX5EY2gY=
github.com/clipperhouse/displaywidth v0.6.0/go.mod h1:R+kHuzaYWFkTm7xoMmK1lFydbci4X2CicfbGstSGg0o= github.com/clipperhouse/displaywidth v0.6.1/go.mod h1:R+kHuzaYWFkTm7xoMmK1lFydbci4X2CicfbGstSGg0o=
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs= github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA= github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4= github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
@@ -58,10 +58,10 @@ golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+2 -2
View File
@@ -44,7 +44,7 @@ func (c *Client) Connect() error {
// Close existing connection if any // Close existing connection if any
if c.conn != nil { if c.conn != nil {
c.conn.Close() _ = c.conn.Close()
c.conn = nil c.conn = nil
c.reader = nil c.reader = nil
} }
@@ -83,7 +83,7 @@ func (c *Client) send(req *protocol.Request) (*protocol.Response, error) {
} }
// Set deadline // Set deadline
c.conn.SetDeadline(time.Now().Add(c.timeout)) _ = c.conn.SetDeadline(time.Now().Add(c.timeout))
// Send request // Send request
data, err := json.Marshal(req) data, err := json.Marshal(req)
+4 -71
View File
@@ -167,7 +167,7 @@ func (m *Manager) watchLoop() {
func (m *Manager) Stop() { func (m *Manager) Stop() {
close(m.stopCh) close(m.stopCh)
if m.watcher != nil { if m.watcher != nil {
m.watcher.Close() _ = m.watcher.Close()
} }
} }
@@ -338,76 +338,6 @@ func (c *Config) DeleteHost(alias string) bool {
return false return false
} }
// UpdateHost updates an existing host by alias.
func (c *Config) UpdateHost(oldAlias, domain, ip, newAlias, groupName string) error {
// Find the host
var foundGroup int = -1
var foundHost int = -1
for i := range c.Groups {
for j := range c.Groups[i].Hosts {
if c.Groups[i].Hosts[j].Alias == oldAlias {
foundGroup = i
foundHost = j
break
}
}
if foundHost >= 0 {
break
}
}
if foundHost < 0 {
return fmt.Errorf("alias not found: %s", oldAlias)
}
// Check for duplicate alias if alias is changing
if oldAlias != newAlias {
if existing, _ := c.FindHostByAlias(newAlias); existing != nil {
return fmt.Errorf("alias already exists: %s", newAlias)
}
}
// Get current enabled state
enabled := c.Groups[foundGroup].Hosts[foundHost].Enabled
// If group is changing, move to new group
if c.Groups[foundGroup].Name != groupName {
// Remove from old group
c.Groups[foundGroup].Hosts = append(c.Groups[foundGroup].Hosts[:foundHost], c.Groups[foundGroup].Hosts[foundHost+1:]...)
// Add to new group
host := Host{
Domain: domain,
IP: ip,
Alias: newAlias,
Enabled: enabled,
}
// Find or create target group
found := false
for i := range c.Groups {
if c.Groups[i].Name == groupName {
c.Groups[i].Hosts = append(c.Groups[i].Hosts, host)
found = true
break
}
}
if !found {
c.Groups = append(c.Groups, Group{
Name: groupName,
Hosts: []Host{host},
})
}
} else {
// Update in place
c.Groups[foundGroup].Hosts[foundHost].Domain = domain
c.Groups[foundGroup].Hosts[foundHost].IP = ip
c.Groups[foundGroup].Hosts[foundHost].Alias = newAlias
}
return nil
}
// ApplyPreset applies a preset to the configuration. // ApplyPreset applies a preset to the configuration.
func (c *Config) ApplyPreset(name string) error { func (c *Config) ApplyPreset(name string) error {
preset := c.FindPreset(name) preset := c.FindPreset(name)
@@ -482,6 +412,7 @@ func (m *Manager) Save() error {
return fmt.Errorf("failed to marshal config: %w", err) return fmt.Errorf("failed to marshal config: %w", err)
} }
// #nosec G306 -- config file should be world-readable
if err := os.WriteFile(m.path, data, 0644); err != nil { if err := os.WriteFile(m.path, data, 0644); err != nil {
return fmt.Errorf("failed to write config: %w", err) return fmt.Errorf("failed to write config: %w", err)
} }
@@ -492,6 +423,7 @@ func (m *Manager) Save() error {
// CreateDefault creates a default configuration file. // CreateDefault creates a default configuration file.
func CreateDefault(path string) error { func CreateDefault(path string) error {
dir := filepath.Dir(path) dir := filepath.Dir(path)
// #nosec G301 -- config directory should be world-readable
if err := os.MkdirAll(dir, 0755); err != nil { if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create config directory: %w", err) return fmt.Errorf("failed to create config directory: %w", err)
} }
@@ -533,6 +465,7 @@ func CreateDefault(path string) error {
return fmt.Errorf("failed to marshal default config: %w", err) return fmt.Errorf("failed to marshal default config: %w", err)
} }
// #nosec G306 -- config file should be world-readable
if err := os.WriteFile(path, data, 0644); err != nil { if err := os.WriteFile(path, data, 0644); err != nil {
return fmt.Errorf("failed to write default config: %w", err) return fmt.Errorf("failed to write default config: %w", err)
} }
-71
View File
@@ -432,77 +432,6 @@ func TestConfig_DeleteHost(t *testing.T) {
}) })
} }
func TestConfig_UpdateHost(t *testing.T) {
t.Run("update in same group", func(t *testing.T) {
cfg := &Config{
Groups: []Group{
{Name: "dev", Hosts: []Host{{Domain: "old.com", IP: "127.0.0.1", Alias: "test"}}},
},
}
err := cfg.UpdateHost("test", "new.com", "192.168.1.1", "test", "dev")
require.NoError(t, err)
assert.Equal(t, "new.com", cfg.Groups[0].Hosts[0].Domain)
assert.Equal(t, "192.168.1.1", cfg.Groups[0].Hosts[0].IP)
})
t.Run("move to different group", func(t *testing.T) {
cfg := &Config{
Groups: []Group{
{Name: "source", Hosts: []Host{{Domain: "a.com", IP: "127.0.0.1", Alias: "test"}}},
{Name: "target", Hosts: []Host{}},
},
}
err := cfg.UpdateHost("test", "a.com", "127.0.0.1", "test", "target")
require.NoError(t, err)
assert.Len(t, cfg.Groups[0].Hosts, 0)
assert.Len(t, cfg.Groups[1].Hosts, 1)
})
t.Run("move to new group", func(t *testing.T) {
cfg := &Config{
Groups: []Group{
{Name: "source", Hosts: []Host{{Domain: "a.com", IP: "127.0.0.1", Alias: "test"}}},
},
}
err := cfg.UpdateHost("test", "a.com", "127.0.0.1", "test", "newgroup")
require.NoError(t, err)
assert.Len(t, cfg.Groups, 2)
assert.Equal(t, "newgroup", cfg.Groups[1].Name)
})
t.Run("change alias", func(t *testing.T) {
cfg := &Config{
Groups: []Group{
{Name: "dev", Hosts: []Host{{Domain: "a.com", IP: "127.0.0.1", Alias: "old"}}},
},
}
err := cfg.UpdateHost("old", "a.com", "127.0.0.1", "new", "dev")
require.NoError(t, err)
assert.Equal(t, "new", cfg.Groups[0].Hosts[0].Alias)
})
t.Run("alias conflict error", func(t *testing.T) {
cfg := &Config{
Groups: []Group{
{Name: "dev", Hosts: []Host{
{Domain: "a.com", Alias: "a"},
{Domain: "b.com", Alias: "b"},
}},
},
}
err := cfg.UpdateHost("a", "a.com", "127.0.0.1", "b", "dev")
assert.Error(t, err)
assert.Contains(t, err.Error(), "alias already exists")
})
t.Run("host not found error", func(t *testing.T) {
cfg := &Config{Groups: []Group{}}
err := cfg.UpdateHost("nonexistent", "a.com", "127.0.0.1", "new", "dev")
assert.Error(t, err)
assert.Contains(t, err.Error(), "alias not found")
})
}
func TestConfig_AddPreset(t *testing.T) { func TestConfig_AddPreset(t *testing.T) {
t.Run("add new preset", func(t *testing.T) { t.Run("add new preset", func(t *testing.T) {
cfg := &Config{Presets: []Preset{}} cfg := &Config{Presets: []Preset{}}
+1 -1
View File
@@ -44,7 +44,7 @@ func New(configPath string) (*Daemon, error) {
cfg.EnsureDefaultGroup() cfg.EnsureDefaultGroup()
// Save if we added a default group // Save if we added a default group
if len(cfg.Groups) == 1 && cfg.Groups[0].Name == "default" && len(cfg.Groups[0].Hosts) == 0 { if len(cfg.Groups) == 1 && cfg.Groups[0].Name == "default" && len(cfg.Groups[0].Hosts) == 0 {
cfgManager.Save() _ = cfgManager.Save()
} }
} }
+7 -2
View File
@@ -178,13 +178,14 @@ func (m *HostsManager) buildManagedSection(entries []HostEntry) string {
func (m *HostsManager) writeAtomic(content string) error { func (m *HostsManager) writeAtomic(content string) error {
// Write to temp file first // Write to temp file first
tmpFile := m.hostsPath + ".tmp" tmpFile := m.hostsPath + ".tmp"
// #nosec G306 -- hosts file must be world-readable
if err := os.WriteFile(tmpFile, []byte(content), 0644); err != nil { if err := os.WriteFile(tmpFile, []byte(content), 0644); err != nil {
return err return err
} }
// Rename atomically // Rename atomically
if err := os.Rename(tmpFile, m.hostsPath); err != nil { if err := os.Rename(tmpFile, m.hostsPath); err != nil {
os.Remove(tmpFile) _ = os.Remove(tmpFile)
return err return err
} }
@@ -193,6 +194,7 @@ func (m *HostsManager) writeAtomic(content string) error {
// CreateBackup creates a backup of the current hosts file. // CreateBackup creates a backup of the current hosts file.
func (m *HostsManager) CreateBackup() error { func (m *HostsManager) CreateBackup() error {
// #nosec G301 -- backup directory should be world-readable for recovery
if err := os.MkdirAll(m.backupDir, 0755); err != nil { if err := os.MkdirAll(m.backupDir, 0755); err != nil {
return fmt.Errorf("failed to create backup directory: %w", err) return fmt.Errorf("failed to create backup directory: %w", err)
} }
@@ -205,6 +207,7 @@ func (m *HostsManager) CreateBackup() error {
timestamp := time.Now().Format("20060102-150405") timestamp := time.Now().Format("20060102-150405")
backupPath := filepath.Join(m.backupDir, fmt.Sprintf("hosts.%s.bak", timestamp)) backupPath := filepath.Join(m.backupDir, fmt.Sprintf("hosts.%s.bak", timestamp))
// #nosec G306 -- backup files should be world-readable for recovery
if err := os.WriteFile(backupPath, content, 0644); err != nil { if err := os.WriteFile(backupPath, content, 0644); err != nil {
return fmt.Errorf("failed to write backup: %w", err) return fmt.Errorf("failed to write backup: %w", err)
} }
@@ -243,7 +246,7 @@ func (m *HostsManager) cleanupBackups() error {
// Remove oldest backups // Remove oldest backups
for i := MaxBackups; i < len(backups); i++ { for i := MaxBackups; i < len(backups); i++ {
path := filepath.Join(m.backupDir, backups[i].Name()) path := filepath.Join(m.backupDir, backups[i].Name())
os.Remove(path) _ = os.Remove(path)
} }
return nil return nil
@@ -301,6 +304,7 @@ func (m *HostsManager) GetBackupContent(name string) (string, error) {
return "", fmt.Errorf("invalid backup name") return "", fmt.Errorf("invalid backup name")
} }
// #nosec G304 -- backupPath is validated above: filepath.Base(name) == name and prefix/suffix checks
content, err := os.ReadFile(backupPath) content, err := os.ReadFile(backupPath)
if err != nil { if err != nil {
return "", fmt.Errorf("failed to read backup: %w", err) return "", fmt.Errorf("failed to read backup: %w", err)
@@ -318,6 +322,7 @@ func (m *HostsManager) RestoreBackup(name string) error {
return fmt.Errorf("invalid backup name") return fmt.Errorf("invalid backup name")
} }
// #nosec G304 -- backupPath is validated above: filepath.Base(name) == name and prefix/suffix checks
content, err := os.ReadFile(backupPath) content, err := os.ReadFile(backupPath)
if err != nil { if err != nil {
return fmt.Errorf("failed to read backup: %w", err) return fmt.Errorf("failed to read backup: %w", err)
+2 -1
View File
@@ -24,7 +24,7 @@ func (s *Server) getPeerCredentials(conn net.Conn) *PeerCredentials {
} }
var creds *PeerCredentials var creds *PeerCredentials
rawConn.Control(func(fd uintptr) { _ = rawConn.Control(func(fd uintptr) {
xucred, err := unix.GetsockoptXucred(int(fd), unix.SOL_LOCAL, unix.LOCAL_PEERCRED) xucred, err := unix.GetsockoptXucred(int(fd), unix.SOL_LOCAL, unix.LOCAL_PEERCRED)
if err != nil { if err != nil {
return return
@@ -33,6 +33,7 @@ func (s *Server) getPeerCredentials(conn net.Conn) *PeerCredentials {
// Get PID separately using LOCAL_PEERPID // Get PID separately using LOCAL_PEERPID
var pid int32 var pid int32
pidLen := uint32(unsafe.Sizeof(pid)) pidLen := uint32(unsafe.Sizeof(pid))
// #nosec G103 -- unsafe required for low-level syscall to get peer PID
_, _, errno := syscall.Syscall6( _, _, errno := syscall.Syscall6(
syscall.SYS_GETSOCKOPT, syscall.SYS_GETSOCKOPT,
fd, fd,
+2
View File
@@ -114,10 +114,12 @@ type AuditEntry struct {
func NewAuditLogger(path string) (*AuditLogger, error) { func NewAuditLogger(path string) (*AuditLogger, error) {
// Ensure directory exists // Ensure directory exists
dir := path[:len(path)-len("/audit.log")] dir := path[:len(path)-len("/audit.log")]
// #nosec G301 -- log directory should be world-readable
if err := os.MkdirAll(dir, 0755); err != nil { if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("failed to create log directory: %w", err) return nil, fmt.Errorf("failed to create log directory: %w", err)
} }
// #nosec G304,G302 -- path is from constant AuditLogPath; audit log should be world-readable
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open audit log: %w", err) return nil, fmt.Errorf("failed to open audit log: %w", err)
+16 -10
View File
@@ -1,6 +1,7 @@
package daemon package daemon
import ( import (
"fmt"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -145,27 +146,32 @@ func TestPeerCredentials(t *testing.T) {
// Matrix test for rate limiting // Matrix test for rate limiting
func TestRateLimiter_Matrix(t *testing.T) { func TestRateLimiter_Matrix(t *testing.T) {
limits := []int{1, 5, 10, 100} testCases := []struct {
windows := []time.Duration{10 * time.Millisecond, 100 * time.Millisecond, time.Second} limit int
window time.Duration
}{
{1, time.Second},
{5, time.Second},
{10, time.Second},
{100, time.Second},
}
for _, limit := range limits { for _, tc := range testCases {
for _, window := range windows {
t.Run( t.Run(
"limit="+string(rune('0'+limit))+"_window="+window.String(), fmt.Sprintf("limit=%d_window=%s", tc.limit, tc.window),
func(t *testing.T) { func(t *testing.T) {
rl := NewRateLimiter(limit, window) rl := NewRateLimiter(tc.limit, tc.window)
// Should allow exactly 'limit' requests // Should allow exactly 'limit' requests
for i := 0; i < limit; i++ { for i := 0; i < tc.limit; i++ {
assert.True(t, rl.Allow(1)) assert.True(t, rl.Allow(1), "request %d should be allowed", i)
} }
// Next should be blocked // Next should be blocked
assert.False(t, rl.Allow(1)) assert.False(t, rl.Allow(1), "request after limit should be blocked")
}, },
) )
} }
}
} }
func BenchmarkRateLimiter_Allow(b *testing.B) { func BenchmarkRateLimiter_Allow(b *testing.B) {
+9 -8
View File
@@ -48,7 +48,7 @@ func NewServer(socketPath string, cfgManager *config.Manager) *Server {
// Start starts the server. // Start starts the server.
func (s *Server) Start() error { func (s *Server) Start() error {
// Remove existing socket // Remove existing socket
os.Remove(s.socketPath) _ = os.Remove(s.socketPath)
listener, err := net.Listen("unix", s.socketPath) listener, err := net.Listen("unix", s.socketPath)
if err != nil { if err != nil {
@@ -56,14 +56,15 @@ func (s *Server) Start() error {
} }
// Set socket permissions: 0660 root:lolcathost // Set socket permissions: 0660 root:lolcathost
// #nosec G302 -- socket must be group-accessible for lolcathost group members
if err := os.Chmod(s.socketPath, 0660); err != nil { if err := os.Chmod(s.socketPath, 0660); err != nil {
listener.Close() _ = listener.Close()
return fmt.Errorf("failed to set socket permissions: %w", err) return fmt.Errorf("failed to set socket permissions: %w", err)
} }
// Set socket group to lolcathost (GID 850) // Set socket group to lolcathost (GID 850)
if err := os.Chown(s.socketPath, 0, 850); err != nil { if err := os.Chown(s.socketPath, 0, 850); err != nil {
listener.Close() _ = listener.Close()
return fmt.Errorf("failed to set socket ownership: %w", err) return fmt.Errorf("failed to set socket ownership: %w", err)
} }
@@ -94,13 +95,13 @@ func (s *Server) Stop() error {
close(s.stopCh) close(s.stopCh)
if s.listener != nil { if s.listener != nil {
s.listener.Close() _ = s.listener.Close()
} }
os.Remove(s.socketPath) _ = os.Remove(s.socketPath)
if s.auditLogger != nil { if s.auditLogger != nil {
s.auditLogger.Close() _ = s.auditLogger.Close()
} }
return nil return nil
@@ -200,7 +201,7 @@ func (s *Server) isAuthorized(creds *PeerCredentials) bool {
func (s *Server) writeResponse(conn net.Conn, resp *protocol.Response) { func (s *Server) writeResponse(conn net.Conn, resp *protocol.Response) {
data, _ := json.Marshal(resp) data, _ := json.Marshal(resp)
data = append(data, '\n') data = append(data, '\n')
conn.Write(data) _, _ = conn.Write(data)
} }
func (s *Server) handleRequest(req *protocol.Request, creds *PeerCredentials) *protocol.Response { func (s *Server) handleRequest(req *protocol.Request, creds *PeerCredentials) *protocol.Response {
@@ -492,7 +493,7 @@ func (s *Server) handleRollback(req *protocol.Request) *protocol.Response {
} }
// Flush DNS after restore // Flush DNS after restore
s.flusher.Flush() _ = s.flusher.Flush()
resp, _ := protocol.NewOKResponse(map[string]string{"restored": payload.BackupName}) resp, _ := protocol.NewOKResponse(map[string]string{"restored": payload.BackupName})
return resp return resp
+15
View File
@@ -219,6 +219,21 @@ func TestServer_HandleDelete(t *testing.T) {
assert.Equal(t, "ok", resp.Status) assert.Equal(t, "ok", resp.Status)
}) })
t.Run("verify deleted entry not in list", func(t *testing.T) {
// After delete, list should not contain the deleted entry
resp := server.handleList()
assert.Equal(t, "ok", resp.Status)
var data protocol.ListData
err := resp.ParseData(&data)
require.NoError(t, err)
// Check that the deleted entry is not in the list
for _, entry := range data.Entries {
assert.NotEqual(t, "todelete", entry.Alias, "deleted entry should not appear in list")
}
})
t.Run("delete nonexistent", func(t *testing.T) { t.Run("delete nonexistent", func(t *testing.T) {
req, _ := protocol.NewRequest(protocol.RequestDelete, protocol.DeletePayload{ req, _ := protocol.NewRequest(protocol.RequestDelete, protocol.DeletePayload{
Alias: "nonexistent", Alias: "nonexistent",
+14 -8
View File
@@ -168,7 +168,7 @@ func (i *Installer) Uninstall() error {
} }
// Remove socket // Remove socket
os.Remove(SocketPath) _ = os.Remove(SocketPath)
// Note: We don't remove the group, logs, or backups // Note: We don't remove the group, logs, or backups
// The user may want to keep these // The user may want to keep these
@@ -225,6 +225,7 @@ func (i *Installer) createGroupDarwin() error {
} }
for _, args := range cmds { for _, args := range cmds {
// #nosec G204 -- args are hardcoded dscl commands with the constant GroupName
if err := exec.Command(args[0], args[1:]...).Run(); err != nil { if err := exec.Command(args[0], args[1:]...).Run(); err != nil {
return fmt.Errorf("command %v failed: %w", args, err) return fmt.Errorf("command %v failed: %w", args, err)
} }
@@ -315,6 +316,7 @@ func (i *Installer) createDirectories() error {
for _, dir := range dirs { for _, dir := range dirs {
i.log(" Creating directory '%s'...", dir) i.log(" Creating directory '%s'...", dir)
// #nosec G301 -- system directories should be world-readable
if err := os.MkdirAll(dir, 0755); err != nil { if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create %s: %w", dir, err) return fmt.Errorf("failed to create %s: %w", dir, err)
} }
@@ -340,21 +342,23 @@ func (i *Installer) installLaunchDaemon() error {
// Unload if already loaded (do this before writing plist) // Unload if already loaded (do this before writing plist)
i.log(" Stopping existing daemon if running...") i.log(" Stopping existing daemon if running...")
exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run() _ = exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run()
// Give launchd time to fully unload the service // Give launchd time to fully unload the service
time.Sleep(500 * time.Millisecond) time.Sleep(500 * time.Millisecond)
// Remove old plist to ensure clean state // Remove old plist to ensure clean state
os.Remove(plistPath) _ = os.Remove(plistPath)
i.log(" Writing LaunchDaemon plist...") i.log(" Writing LaunchDaemon plist...")
// #nosec G306 -- plist files are world-readable by convention
if err := os.WriteFile(plistPath, []byte(plistContent), 0644); err != nil { if err := os.WriteFile(plistPath, []byte(plistContent), 0644); err != nil {
return fmt.Errorf("failed to write plist: %w", err) return fmt.Errorf("failed to write plist: %w", err)
} }
// Bootstrap the daemon // Bootstrap the daemon
i.log(" Starting daemon...") i.log(" Starting daemon...")
// #nosec G204 -- plistPath is constructed from constant LaunchDaemonDir
cmd := exec.Command("launchctl", "bootstrap", "system", plistPath) cmd := exec.Command("launchctl", "bootstrap", "system", plistPath)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
@@ -376,10 +380,10 @@ func (i *Installer) uninstallLaunchDaemon() {
plistPath := filepath.Join(LaunchDaemonDir, "com.lolcathost.daemon.plist") plistPath := filepath.Join(LaunchDaemonDir, "com.lolcathost.daemon.plist")
i.log(" Stopping daemon...") i.log(" Stopping daemon...")
exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run() _ = exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run()
i.log(" Removing LaunchDaemon plist...") i.log(" Removing LaunchDaemon plist...")
os.Remove(plistPath) _ = os.Remove(plistPath)
} }
func (i *Installer) installSystemdService() error { func (i *Installer) installSystemdService() error {
@@ -387,6 +391,7 @@ func (i *Installer) installSystemdService() error {
unitContent := fmt.Sprintf(SystemdUnit, i.binaryPath) unitContent := fmt.Sprintf(SystemdUnit, i.binaryPath)
i.log(" Writing systemd unit...") i.log(" Writing systemd unit...")
// #nosec G306 -- systemd unit files are world-readable by convention
if err := os.WriteFile(unitPath, []byte(unitContent), 0644); err != nil { if err := os.WriteFile(unitPath, []byte(unitContent), 0644); err != nil {
return fmt.Errorf("failed to write unit file: %w", err) return fmt.Errorf("failed to write unit file: %w", err)
} }
@@ -408,12 +413,12 @@ func (i *Installer) installSystemdService() error {
func (i *Installer) uninstallSystemdService() { func (i *Installer) uninstallSystemdService() {
i.log(" Stopping and disabling service...") i.log(" Stopping and disabling service...")
exec.Command("systemctl", "disable", "--now", "lolcathost.service").Run() _ = exec.Command("systemctl", "disable", "--now", "lolcathost.service").Run()
i.log(" Removing systemd unit...") i.log(" Removing systemd unit...")
os.Remove(filepath.Join(SystemdDir, "lolcathost.service")) _ = os.Remove(filepath.Join(SystemdDir, "lolcathost.service"))
exec.Command("systemctl", "daemon-reload").Run() _ = exec.Command("systemctl", "daemon-reload").Run()
} }
func (i *Installer) createDefaultConfig() error { func (i *Installer) createDefaultConfig() error {
@@ -430,6 +435,7 @@ func (i *Installer) createDefaultConfig() error {
// Create config directory // Create config directory
configDir := filepath.Dir(configPath) configDir := filepath.Dir(configPath)
// #nosec G301 -- config directory should be world-readable
if err := os.MkdirAll(configDir, 0755); err != nil { if err := os.MkdirAll(configDir, 0755); err != nil {
return fmt.Errorf("failed to create config directory: %w", err) return fmt.Errorf("failed to create config directory: %w", err)
} }
+62 -8
View File
@@ -9,6 +9,7 @@ import (
"github.com/charmbracelet/bubbles/textinput" "github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea" tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/lukaszraczylo/lolcathost/internal/client" "github.com/lukaszraczylo/lolcathost/internal/client"
"github.com/lukaszraczylo/lolcathost/internal/config" "github.com/lukaszraczylo/lolcathost/internal/config"
@@ -27,6 +28,7 @@ const (
ViewBackups ViewBackups
ViewHelp ViewHelp
ViewSearch ViewSearch
ViewConfirmDelete
) )
// Model is the main Bubble Tea model. // Model is the main Bubble Tea model.
@@ -52,6 +54,7 @@ type Model struct {
messageTime time.Time messageTime time.Time
searchTerm string searchTerm string
allGroups []string // All groups including empty ones allGroups []string // All groups including empty ones
pendingDeleteAlias string // Alias of host pending delete confirmation
// Update notification // Update notification
updateAvailable bool updateAvailable bool
@@ -351,8 +354,9 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.setError(fmt.Sprintf("Refresh failed: %v", msg.err)) m.setError(fmt.Sprintf("Refresh failed: %v", msg.err))
// Mark as disconnected to trigger reconnect // Mark as disconnected to trigger reconnect
m.connected = false m.connected = false
m.client.Close() _ = m.client.Close()
} else if msg.entries != nil { } else {
// Always update the list, even if entries is nil/empty
m.list.SetItems(msg.entries) m.list.SetItems(msg.entries)
} }
@@ -385,7 +389,10 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.mode = ViewList m.mode = ViewList
case deleteMsg: case deleteMsg:
// Clear pending state regardless of success/failure
m.list.SetPending(msg.alias, false)
if msg.err != nil { if msg.err != nil {
m.list.SetError(msg.alias, true)
m.setError(fmt.Sprintf("Delete failed: %v", msg.err)) m.setError(fmt.Sprintf("Delete failed: %v", msg.err))
} else { } else {
cmds = append(cmds, m.refresh()) cmds = append(cmds, m.refresh())
@@ -521,6 +528,8 @@ func (m *Model) handleKey(msg tea.KeyMsg) tea.Cmd {
return m.handleHelpKey(msg) return m.handleHelpKey(msg)
case ViewSearch: case ViewSearch:
return m.handleSearchKey(msg) return m.handleSearchKey(msg)
case ViewConfirmDelete:
return m.handleConfirmDeleteKey(msg)
} }
return nil return nil
@@ -554,7 +563,8 @@ func (m *Model) handleListKey(msg tea.KeyMsg) tea.Cmd {
} }
case "d": case "d":
if item := m.list.Selected(); item != nil { if item := m.list.Selected(); item != nil {
return m.deleteHost(item.Entry.Alias) m.pendingDeleteAlias = item.Entry.Alias
m.mode = ViewConfirmDelete
} }
case "p": case "p":
m.mode = ViewPresets m.mode = ViewPresets
@@ -593,7 +603,7 @@ func (m *Model) handleFormKey(msg tea.KeyMsg) tea.Cmd {
oldAlias := m.form.EditAlias() oldAlias := m.form.EditAlias()
return tea.Sequence( return tea.Sequence(
func() tea.Msg { func() tea.Msg {
m.client.Delete(oldAlias) _ = m.client.Delete(oldAlias)
return nil return nil
}, },
m.addHost(domain, ip, "", group), // Empty alias = auto-generate m.addHost(domain, ip, "", group), // Empty alias = auto-generate
@@ -668,7 +678,7 @@ func (m *Model) handlePresetFormKey(msg tea.KeyMsg) tea.Cmd {
oldName := m.presetPicker.EditName() oldName := m.presetPicker.EditName()
return tea.Sequence( return tea.Sequence(
func() tea.Msg { func() tea.Msg {
m.client.DeletePreset(oldName) _ = m.client.DeletePreset(oldName)
return nil return nil
}, },
m.addPreset(name, enable, disable), m.addPreset(name, enable, disable),
@@ -850,6 +860,23 @@ func (m *Model) handleSearchKey(msg tea.KeyMsg) tea.Cmd {
return cmd return cmd
} }
func (m *Model) handleConfirmDeleteKey(msg tea.KeyMsg) tea.Cmd {
switch msg.String() {
case "y", "Y":
alias := m.pendingDeleteAlias
m.pendingDeleteAlias = ""
m.mode = ViewList
// Set pending state for visual feedback
m.list.SetPending(alias, true)
return m.deleteHost(alias)
case "n", "N", "esc":
m.pendingDeleteAlias = ""
m.mode = ViewList
return nil
}
return nil
}
func (m *Model) toggleSelected() tea.Cmd { func (m *Model) toggleSelected() tea.Cmd {
item := m.list.Selected() item := m.list.Selected()
if item == nil { if item == nil {
@@ -904,6 +931,8 @@ func (m *Model) View() string {
sb.WriteString(m.helpView()) sb.WriteString(m.helpView())
case ViewSearch: case ViewSearch:
sb.WriteString(m.searchView()) sb.WriteString(m.searchView())
case ViewConfirmDelete:
sb.WriteString(m.confirmDeleteView())
} }
// Message // Message
@@ -1077,9 +1106,34 @@ func (m *Model) searchView() string {
return dialogStyle.Render(sb.String()) return dialogStyle.Render(sb.String())
} }
// Run starts the TUI application. func (m *Model) confirmDeleteView() string {
func Run(socketPath string) error { var sb strings.Builder
return RunWithVersion(socketPath, "dev", "", "")
sb.WriteString(titleStyle.Render("Confirm Delete"))
sb.WriteString("\n\n")
// Find the entry details for the pending delete
var domain, ip string
for _, item := range m.list.items {
if item.Entry.Alias == m.pendingDeleteAlias {
domain = item.Entry.Domain
ip = item.Entry.IP
break
}
}
warningStyle := lipgloss.NewStyle().Foreground(colorWarning).Bold(true)
sb.WriteString(warningStyle.Render("Are you sure you want to delete this host?"))
sb.WriteString("\n\n")
sb.WriteString(fmt.Sprintf(" Alias: %s\n", helpKeyStyle.Render(m.pendingDeleteAlias)))
sb.WriteString(fmt.Sprintf(" Domain: %s\n", helpDescStyle.Render(domain)))
sb.WriteString(fmt.Sprintf(" IP: %s\n", helpDescStyle.Render(ip)))
sb.WriteString("\n")
sb.WriteString(helpDescStyle.Render("y confirm • n/Esc cancel"))
return dialogStyle.Render(sb.String())
} }
// RunWithVersion starts the TUI application with version info for update checking. // RunWithVersion starts the TUI application with version info for update checking.
-5
View File
@@ -295,11 +295,6 @@ func (l *ListView) ViewFiltered(searchTerm string) string {
return sb.String() return sb.String()
} }
// GroupCount returns the number of groups.
func (l *ListView) GroupCount() int {
return len(l.groupOrder)
}
// GetGroups returns all group names. // GetGroups returns all group names.
func (l *ListView) GetGroups() []string { func (l *ListView) GetGroups() []string {
return l.groupOrder return l.groupOrder
+69
View File
@@ -407,3 +407,72 @@ func BenchmarkListView_View(b *testing.B) {
_ = lv.View() _ = lv.View()
} }
} }
func TestListView_DeleteSimulation(t *testing.T) {
lv := NewListView()
// Initial entries
entries := []protocol.HostEntry{
{Domain: "a.com", IP: "127.0.0.1", Alias: "a", Enabled: true, Group: "dev"},
{Domain: "b.com", IP: "127.0.0.1", Alias: "b", Enabled: false, Group: "dev"},
{Domain: "c.com", IP: "192.168.1.1", Alias: "c", Enabled: true, Group: "staging"},
}
lv.SetItems(entries)
require.Equal(t, 3, lv.Len())
// Select the second item
lv.MoveDown()
selected := lv.Selected()
require.NotNil(t, selected)
require.Equal(t, "b", selected.Entry.Alias)
// Simulate delete: set new items without the deleted entry
entriesAfterDelete := []protocol.HostEntry{
{Domain: "a.com", IP: "127.0.0.1", Alias: "a", Enabled: true, Group: "dev"},
{Domain: "c.com", IP: "192.168.1.1", Alias: "c", Enabled: true, Group: "staging"},
}
lv.SetItems(entriesAfterDelete)
// Verify list has only 2 items now
assert.Equal(t, 2, lv.Len())
// Verify "b" is no longer in the list
for i := 0; i < lv.Len(); i++ {
assert.NotEqual(t, "b", lv.items[i].Entry.Alias, "deleted entry should not be in list")
}
// Cursor should be adjusted if needed
assert.LessOrEqual(t, lv.cursor, lv.Len()-1)
}
func TestListView_SetItemsWithNil(t *testing.T) {
lv := NewListView()
// Initial entries
entries := []protocol.HostEntry{
{Domain: "a.com", IP: "127.0.0.1", Alias: "a", Enabled: true, Group: "dev"},
}
lv.SetItems(entries)
require.Equal(t, 1, lv.Len())
// Set nil entries (simulating empty list from server)
lv.SetItems(nil)
assert.Equal(t, 0, lv.Len())
assert.Equal(t, 0, lv.cursor)
}
func TestListView_SetItemsWithEmptySlice(t *testing.T) {
lv := NewListView()
// Initial entries
entries := []protocol.HostEntry{
{Domain: "a.com", IP: "127.0.0.1", Alias: "a", Enabled: true, Group: "dev"},
}
lv.SetItems(entries)
require.Equal(t, 1, lv.Len())
// Set empty slice
lv.SetItems([]protocol.HostEntry{})
assert.Equal(t, 0, lv.Len())
assert.Equal(t, 0, lv.cursor)
}
-5
View File
@@ -146,11 +146,6 @@ func StatusText(enabled bool, pending bool, hasError bool) string {
return disabledStyle.Render("○ Disabled") return disabledStyle.Render("○ Disabled")
} }
// HelpItem formats a help item.
func HelpItem(key, desc string) string {
return helpKeyStyle.Render(key) + " " + helpDescStyle.Render(desc)
}
// WrapHelpText wraps help text to fit within maxWidth, splitting on bullet separators. // WrapHelpText wraps help text to fit within maxWidth, splitting on bullet separators.
// If maxWidth is 0 or negative, returns the original text. // If maxWidth is 0 or negative, returns the original text.
func WrapHelpText(text string, maxWidth int) string { func WrapHelpText(text string, maxWidth int) string {
+2 -7
View File
@@ -76,6 +76,7 @@ func (c *Checker) CheckForUpdate(ctx context.Context) *UpdateInfo {
// fetchLatestRelease fetches the latest release info from GitHub API // fetchLatestRelease fetches the latest release info from GitHub API
func (c *Checker) fetchLatestRelease(ctx context.Context) (*ReleaseInfo, error) { func (c *Checker) fetchLatestRelease(ctx context.Context) (*ReleaseInfo, error) {
// #nosec G107 -- URL is constructed from hardcoded constant and validated owner/repo
url := fmt.Sprintf(githubReleasesURL, c.owner, c.repo) url := fmt.Sprintf(githubReleasesURL, c.owner, c.repo)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
@@ -145,15 +146,9 @@ func parseVersion(v string) []int {
for _, p := range parts { for _, p := range parts {
var num int var num int
fmt.Sscanf(p, "%d", &num) _, _ = fmt.Sscanf(p, "%d", &num)
result = append(result, num) result = append(result, num)
} }
return result return result
} }
// FormatUpdateMessage formats a user-friendly update notification
func (u *UpdateInfo) FormatUpdateMessage() string {
return fmt.Sprintf("New version available: %s (current: %s) - %s",
u.LatestVersion, u.CurrentVersion, u.ReleaseURL)
}
-13
View File
@@ -76,19 +76,6 @@ func TestIsNewerVersion(t *testing.T) {
} }
} }
func TestUpdateInfo_FormatUpdateMessage(t *testing.T) {
info := &UpdateInfo{
CurrentVersion: "1.0.0",
LatestVersion: "1.1.0",
ReleaseURL: "https://github.com/lukaszraczylo/lolcathost/releases/tag/v1.1.0",
}
msg := info.FormatUpdateMessage()
assert.Contains(t, msg, "1.0.0")
assert.Contains(t, msg, "1.1.0")
assert.Contains(t, msg, "https://github.com")
}
func TestNewChecker(t *testing.T) { func TestNewChecker(t *testing.T) {
checker := NewChecker("lukaszraczylo", "lolcathost", "v1.0.0") checker := NewChecker("lukaszraczylo", "lolcathost", "v1.0.0")