feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MyGo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
# @mygo-plugins/watch
|
||||
|
||||
Changes to files for [MyGo](https://github.com/egoist/mygo) apps' pages, in
|
||||
the directories and files the app lets them watch, such as a project open
|
||||
in an editor.
|
||||
|
||||
Use the plugin in Go with the directories pages may watch, each under a
|
||||
name:
|
||||
|
||||
```go
|
||||
import "github.com/egoist/mygo/plugins/watch"
|
||||
|
||||
mygo.Use(watch.New(watch.Options{
|
||||
Roots: map[string]watch.Root{
|
||||
"project": {Path: projectDir, Recursive: true},
|
||||
},
|
||||
}))
|
||||
```
|
||||
|
||||
and watch one by its name in the frontend:
|
||||
|
||||
```ts
|
||||
import { watch } from "@mygo-plugins/watch";
|
||||
|
||||
const watcher = await watch("project", { recursive: true });
|
||||
for await (const events of watcher) {
|
||||
for (const event of events) console.log(event.op, event.path); // "write", "src/main.ts"
|
||||
}
|
||||
```
|
||||
|
||||
Each batch has the events of `create`, `write`, `remove` and `rename` (with
|
||||
`oldPath`) found once changes stopped for 50 ms (`debounceMs`), with paths
|
||||
relative to what is watched, `path` in the root or the root itself. They say
|
||||
what is different, not every step: treat them as hints to read the files
|
||||
again. `watcher.close()`, breaking out of the loop, an
|
||||
`AbortSignal` (`signal`) or the page navigating stop the watch.
|
||||
|
||||
[The documentation](https://github.com/egoist/mygo/blob/main/docs/plugins/watch.md)
|
||||
covers the options of the Go side, errors and how each platform watches.
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "@mygo-plugins/watch",
|
||||
"version": "0.10.0",
|
||||
"description": "Watches for changes to files in the directories a MyGo desktop app lets its pages watch",
|
||||
"keywords": [
|
||||
"mygo",
|
||||
"desktop",
|
||||
"webview",
|
||||
"go",
|
||||
"watch",
|
||||
"filesystem"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/egoist/mygo.git",
|
||||
"directory": "plugins/watch"
|
||||
},
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "bun run ../build.ts",
|
||||
"test": "bun test"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"mygo-runtime": "^0.10.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"mygo-runtime": "^0.10.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { fakeGo } from "../../fake-go";
|
||||
import { type FileEvent, watch, WatchError } from "./index";
|
||||
|
||||
let cleanup = () => {};
|
||||
afterEach(() => cleanup());
|
||||
|
||||
test("streams the batches, and close waits for Go", async () => {
|
||||
let cleaned = false;
|
||||
const go = fakeGo({
|
||||
"plugin:watch.Watch": async ({ send, signal, args }) => {
|
||||
expect(args[0]).toEqual({ root: "project", path: ".", recursive: false, debounceMs: 0 });
|
||||
send(1, { type: "ready" });
|
||||
send(1, {
|
||||
type: "events",
|
||||
events: [
|
||||
{ op: "create", path: "a", isDir: false },
|
||||
{ op: "write", path: "b", isDir: false },
|
||||
],
|
||||
});
|
||||
send(1, { type: "events", events: [{ op: "remove", path: "a", isDir: false }] });
|
||||
await new Promise<void>((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
|
||||
cleaned = true;
|
||||
},
|
||||
});
|
||||
cleanup = go.uninstall;
|
||||
const w = await watch("project");
|
||||
const iterator = w[Symbol.asyncIterator]();
|
||||
expect((await iterator.next()).value?.map((e: FileEvent) => e.op)).toEqual(["create", "write"]);
|
||||
expect((await iterator.next()).value?.map((e: FileEvent) => e.op)).toEqual(["remove"]);
|
||||
await w.close();
|
||||
await w.close();
|
||||
expect(cleaned).toBe(true);
|
||||
});
|
||||
|
||||
test("a watch that ends ends the iteration", async () => {
|
||||
const go = fakeGo({
|
||||
"plugin:watch.Watch": ({ send, args }) => {
|
||||
expect(args[0]).toEqual({ root: "project", path: "config.json", recursive: false, debounceMs: -1 });
|
||||
send(1, { type: "ready" });
|
||||
send(1, { type: "events", events: [{ op: "remove", path: ".", isDir: false }] });
|
||||
},
|
||||
});
|
||||
cleanup = go.uninstall;
|
||||
const w = await watch("project", { path: "config.json", debounceMs: -1 });
|
||||
const batches = [];
|
||||
for await (const batch of w) batches.push(batch);
|
||||
expect(batches).toEqual([[{ op: "remove", path: ".", isDir: false }]]);
|
||||
await expect(w.closed).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test("errors are WatchErrors with their code", async () => {
|
||||
const go = fakeGo({
|
||||
"plugin:watch.Watch": ({ send, args }) => {
|
||||
if ((args[0] as { root: string }).root === "denied") {
|
||||
return { code: "denied", message: "filesystem watch denied" };
|
||||
}
|
||||
send(1, { type: "ready" });
|
||||
send(1, { type: "events", events: [{ op: "create", path: "a", isDir: false }] });
|
||||
return { code: "limit", message: "filesystem watch limit" };
|
||||
},
|
||||
});
|
||||
cleanup = go.uninstall;
|
||||
const denied = await watch("denied").catch((err) => err);
|
||||
expect(denied).toBeInstanceOf(WatchError);
|
||||
expect(denied.code).toBe("denied");
|
||||
const w = await watch("project");
|
||||
const seen: unknown[] = [];
|
||||
const iterate = (async () => {
|
||||
for await (const batch of w) seen.push(batch);
|
||||
})();
|
||||
await expect(iterate).rejects.toBeInstanceOf(WatchError);
|
||||
await expect(w.closed).rejects.toMatchObject({ code: "limit" });
|
||||
expect(seen).toHaveLength(1);
|
||||
await expect(w.close()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test("invalid options and an aborted signal never call Go", async () => {
|
||||
const go = fakeGo({});
|
||||
cleanup = go.uninstall;
|
||||
await expect(watch("project", { debounceMs: NaN })).rejects.toBeInstanceOf(TypeError);
|
||||
await expect(watch("project", { debounceMs: 60001 })).rejects.toBeInstanceOf(TypeError);
|
||||
const signal = AbortSignal.abort("stop");
|
||||
await expect(watch("project", { signal })).rejects.toBe("stop");
|
||||
expect(go.calls).toHaveLength(0);
|
||||
});
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* The watch plugin of MyGo: changes to the files and directories the app
|
||||
* lets pages watch, by the names it gives them. The Go side must use the
|
||||
* plugin with those directories:
|
||||
*
|
||||
* ```go
|
||||
* mygo.Use(watch.New(watch.Options{ // github.com/egoist/mygo/plugins/watch
|
||||
* Roots: map[string]watch.Root{"project": {Path: dir, Recursive: true}},
|
||||
* }))
|
||||
* ```
|
||||
*
|
||||
* ```ts
|
||||
* import { watch } from "@mygo-plugins/watch";
|
||||
*
|
||||
* const watcher = await watch("project", { recursive: true });
|
||||
* for await (const events of watcher) {
|
||||
* for (const event of events) console.log(event.op, event.path);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { Channel, call } from "mygo-runtime";
|
||||
|
||||
/** The kind of a {@link FileEvent}. */
|
||||
export type FileOp = "create" | "write" | "remove" | "rename";
|
||||
|
||||
/**
|
||||
* A change in a watched directory or file. Events say what is different
|
||||
* once changes stop, not every step that made it so: treat them as hints
|
||||
* to read the files again.
|
||||
*/
|
||||
export interface FileEvent {
|
||||
op: FileOp;
|
||||
/** The path relative to what is watched, separated by slashes; "." is what is watched itself. */
|
||||
path: string;
|
||||
/** Where a rename moved from. */
|
||||
oldPath?: string;
|
||||
isDir: boolean;
|
||||
}
|
||||
|
||||
/** Options of {@link watch}. */
|
||||
export interface WatchOptions {
|
||||
/** What to watch in the root, a directory or a file, relative to it and separated by slashes: the root itself by default. */
|
||||
path?: string;
|
||||
/** Watch the directories in the directory too, if the app allows it. */
|
||||
recursive?: boolean;
|
||||
/** How long changes must stop before they are reported: 50 ms when 0 or omitted, right away when negative. */
|
||||
debounceMs?: number;
|
||||
/** Stops the watch when aborted. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/** Why a watch failed or stopped; see {@link WatchError}. */
|
||||
export type WatchErrorCode = "denied" | "limit" | "not-found" | "unsupported" | "path-encoding" | "io";
|
||||
|
||||
/** A watch that failed to start or stopped, with the reason as its code. */
|
||||
export class WatchError extends Error {
|
||||
constructor(
|
||||
readonly code: WatchErrorCode,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "WatchError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A running watch: iterate it for the changes, a batch of events each time
|
||||
* they stop. Go doesn't look again until the page has taken a batch, so
|
||||
* nothing is lost while the page is busy.
|
||||
*/
|
||||
export interface Watcher extends AsyncIterable<FileEvent[]> {
|
||||
/** Settles once Go has stopped the watch, rejecting with the error that stopped it. */
|
||||
readonly closed: Promise<void>;
|
||||
/** Stops the watch; it resolves once Go has. */
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** What Go streams. */
|
||||
interface Part {
|
||||
type: "ready" | "events";
|
||||
events?: FileEvent[];
|
||||
}
|
||||
|
||||
/** How the watch ended, the result of Go's call: the code of what failed, if anything. */
|
||||
interface Outcome {
|
||||
code?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
const codes: readonly string[] = ["denied", "limit", "not-found", "unsupported", "path-encoding", "io"];
|
||||
|
||||
/**
|
||||
* Watches the directory or file the app named `root`, or `path` in it, and
|
||||
* resolves once everything is watched. What is already there is not
|
||||
* reported. When it is removed, renamed or replaced, the last batch has a
|
||||
* "remove" of ".", and the iteration ends.
|
||||
*/
|
||||
export async function watch(root: string, options: WatchOptions = {}): Promise<Watcher> {
|
||||
const debounceMs = options.debounceMs ?? 0;
|
||||
if (!Number.isInteger(debounceMs) || debounceMs > 60000) {
|
||||
throw new TypeError("debounceMs must be an integer up to 60000");
|
||||
}
|
||||
const path = options.path ?? ".";
|
||||
if (typeof path !== "string") throw new TypeError("path must be a string");
|
||||
if (options.signal?.aborted) throw options.signal.reason;
|
||||
const parts = new Channel<Part>();
|
||||
const stream = parts[Symbol.asyncIterator]();
|
||||
// The first error wins: the signal's reason, or the call's.
|
||||
let terminal: { error: unknown } | undefined;
|
||||
let closing = false;
|
||||
let finished = false;
|
||||
let iterating = false;
|
||||
const record = (error: unknown) => {
|
||||
terminal ??= { error };
|
||||
};
|
||||
const abort = () => {
|
||||
if (finished || closing) return;
|
||||
record(options.signal!.reason);
|
||||
closing = true;
|
||||
parts.close();
|
||||
};
|
||||
options.signal?.addEventListener("abort", abort, { once: true });
|
||||
const closed = call<Outcome | null>("plugin:watch.Watch", { root, path, recursive: options.recursive ?? false, debounceMs }, parts)
|
||||
.then(
|
||||
(outcome) => {
|
||||
if (outcome?.code) {
|
||||
record(
|
||||
codes.includes(outcome.code)
|
||||
? new WatchError(outcome.code as WatchErrorCode, outcome.message ?? "filesystem watch failed")
|
||||
: new Error("Invalid watch outcome"),
|
||||
);
|
||||
}
|
||||
if (terminal) throw terminal.error;
|
||||
},
|
||||
(err: unknown) => {
|
||||
record(err);
|
||||
throw terminal!.error;
|
||||
},
|
||||
)
|
||||
.finally(() => {
|
||||
finished = true;
|
||||
options.signal?.removeEventListener("abort", abort);
|
||||
});
|
||||
void closed.catch(() => {});
|
||||
const close = async () => {
|
||||
if (!closing && !finished) {
|
||||
closing = true;
|
||||
parts.close();
|
||||
}
|
||||
await closed.catch(() => {});
|
||||
};
|
||||
try {
|
||||
const first = await stream.next();
|
||||
if (first.done) {
|
||||
await closed;
|
||||
throw new Error("Watch ended before ready");
|
||||
}
|
||||
if (first.value.type !== "ready") {
|
||||
parts.close();
|
||||
await closed;
|
||||
throw new Error("Invalid watch ready response");
|
||||
}
|
||||
if (terminal) {
|
||||
await closed;
|
||||
throw terminal.error;
|
||||
}
|
||||
} catch (err) {
|
||||
parts.close();
|
||||
options.signal?.removeEventListener("abort", abort);
|
||||
throw err;
|
||||
}
|
||||
return {
|
||||
closed,
|
||||
close,
|
||||
[Symbol.asyncIterator]() {
|
||||
if (iterating) throw new Error("A watch supports one iterator");
|
||||
iterating = true;
|
||||
return (async function* () {
|
||||
try {
|
||||
while (!closing) {
|
||||
const next = await stream.next();
|
||||
if (next.done) break;
|
||||
if (next.value.events?.length && !closing) yield next.value.events;
|
||||
}
|
||||
await closed;
|
||||
} finally {
|
||||
await close();
|
||||
iterating = false;
|
||||
}
|
||||
})();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "../tsconfig.base.json",
|
||||
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
// Package watch is the watch plugin of MyGo: it lets pages watch for
|
||||
// changes to the files and directories the app names (see
|
||||
// @mygo-plugins/watch). Go code and native UI call mygo.WatchFiles
|
||||
// directly.
|
||||
package watch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
)
|
||||
|
||||
// Root is a directory, or a file, pages may watch.
|
||||
type Root struct {
|
||||
// Path is the absolute path of the directory or file.
|
||||
Path string
|
||||
// Recursive lets pages watch the directories in it too, and what is
|
||||
// in them.
|
||||
Recursive bool
|
||||
// Ignore, when set, is asked about every file and directory a watch
|
||||
// of the root finds, by its path relative to the root, separated by
|
||||
// slashes, as mygo.FileWatchOptions.Ignore is.
|
||||
Ignore func(path string, isDir bool) bool
|
||||
}
|
||||
|
||||
// Request is a watch a page asks for.
|
||||
type Request struct {
|
||||
// Root is the name of the root.
|
||||
Root string
|
||||
// Path is what to watch in the root, relative to it and separated by
|
||||
// slashes: "." for the root itself.
|
||||
Path string
|
||||
// Recursive asks to watch the directories in it too.
|
||||
Recursive bool
|
||||
}
|
||||
|
||||
// Options configures the plugin.
|
||||
type Options struct {
|
||||
// Roots are the directories and files pages may watch, by the names
|
||||
// they use: lowercase letters, digits and dashes, starting with a
|
||||
// letter.
|
||||
Roots map[string]Root
|
||||
// Resolve, when set, is asked for the root of a name that is not in
|
||||
// Roots, with the call's context, so that the app can grant roots
|
||||
// while it runs, such as a folder the user chose in a dialog. It
|
||||
// returns false for names it doesn't know.
|
||||
Resolve func(ctx context.Context, name string) (Root, bool)
|
||||
// Allow, when set, is asked before each watch with the call's context
|
||||
// and the request, and can refuse it.
|
||||
Allow func(ctx context.Context, r Request) bool
|
||||
// MaxWatchesPerPage is how many watches a page may have at a time: 8
|
||||
// when zero.
|
||||
MaxWatchesPerPage int
|
||||
// MaxWatches is how many watches all pages may have at a time: 128
|
||||
// when zero.
|
||||
MaxWatches int
|
||||
}
|
||||
|
||||
// Plugin is the plugin without roots, which lets pages watch nothing.
|
||||
var Plugin = New(Options{})
|
||||
|
||||
type watcher interface {
|
||||
Next(context.Context) ([]mygo.FileEvent, error)
|
||||
Close() error
|
||||
Root() string
|
||||
}
|
||||
|
||||
// active is a running watch, which counts against its page's quota while
|
||||
// its call's context is not done: the page context ends with navigation,
|
||||
// before the watch has stopped.
|
||||
type active struct {
|
||||
page any
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
type service struct {
|
||||
opts Options
|
||||
identities map[string]os.FileInfo
|
||||
factory func(context.Context, string, mygo.FileWatchOptions) (watcher, error)
|
||||
mu sync.Mutex
|
||||
active map[*active]bool
|
||||
}
|
||||
|
||||
// New returns the plugin with opts. mygo.Use panics when a root is not an
|
||||
// absolute path to a directory or a file, after resolving its symlinks.
|
||||
func New(opts Options) mygo.Plugin {
|
||||
roots := make(map[string]Root, len(opts.Roots))
|
||||
for k, v := range opts.Roots {
|
||||
roots[k] = v
|
||||
}
|
||||
opts.Roots = roots
|
||||
if opts.MaxWatchesPerPage == 0 {
|
||||
opts.MaxWatchesPerPage = 8
|
||||
}
|
||||
if opts.MaxWatches == 0 {
|
||||
opts.MaxWatches = 128
|
||||
}
|
||||
s := &service{opts: opts, identities: make(map[string]os.FileInfo), active: make(map[*active]bool), factory: func(ctx context.Context, path string, o mygo.FileWatchOptions) (watcher, error) {
|
||||
return mygo.WatchFiles(ctx, path, o)
|
||||
}}
|
||||
return mygo.Plugin{Name: "watch", Service: s, Setup: s.setup}
|
||||
}
|
||||
|
||||
var alias = regexp.MustCompile(`^[a-z][a-z0-9-]{0,63}$`)
|
||||
|
||||
func (s *service) setup() error {
|
||||
if s.opts.MaxWatchesPerPage < 0 || s.opts.MaxWatches < 0 {
|
||||
return errors.New("watch: negative quota")
|
||||
}
|
||||
for name, root := range s.opts.Roots {
|
||||
if !alias.MatchString(name) {
|
||||
return fmt.Errorf("watch: invalid root alias %q", name)
|
||||
}
|
||||
root, info, err := canonical(root)
|
||||
if err != nil {
|
||||
return fmt.Errorf("watch: root %q: %w", name, err)
|
||||
}
|
||||
s.opts.Roots[name] = root
|
||||
s.identities[name] = info
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// canonical resolves the symlinks of root's path, and returns what it is.
|
||||
func canonical(root Root) (Root, os.FileInfo, error) {
|
||||
if !filepath.IsAbs(root.Path) {
|
||||
return root, nil, errors.New("root must be absolute")
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(root.Path)
|
||||
if err != nil {
|
||||
return root, nil, err
|
||||
}
|
||||
root.Path = resolved
|
||||
info, err := validateRoot(root.Path)
|
||||
return root, info, err
|
||||
}
|
||||
|
||||
// validateRoot checks that path is a file or a directory in ordinary
|
||||
// directories, none a symlink or a Windows junction, and returns it.
|
||||
func validateRoot(path string) (os.FileInfo, error) {
|
||||
if !filepath.IsAbs(path) {
|
||||
return nil, errors.New("root must be absolute")
|
||||
}
|
||||
path = filepath.Clean(path)
|
||||
for p := path; ; p = filepath.Dir(p) {
|
||||
info, err := os.Lstat(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Lstat doesn't take symlinks and junctions for directories.
|
||||
if !info.IsDir() && (p != path || !info.Mode().IsRegular()) {
|
||||
return nil, errors.New("root components must be ordinary directories")
|
||||
}
|
||||
if filepath.Dir(p) == p {
|
||||
break
|
||||
}
|
||||
}
|
||||
info, err := os.Lstat(path)
|
||||
return mygo.StatIdentity(info), err
|
||||
}
|
||||
|
||||
// validPath reports whether p is a path relative to a root, separated by
|
||||
// slashes, that stays in it.
|
||||
func validPath(p string) bool {
|
||||
if p == "." {
|
||||
return true
|
||||
}
|
||||
if !fs.ValidPath(p) || strings.Contains(p, `\`) || runtime.GOOS == "windows" && strings.Contains(p, ":") {
|
||||
return false
|
||||
}
|
||||
return filepath.IsLocal(filepath.FromSlash(p))
|
||||
}
|
||||
|
||||
// resolve checks what p names in root, through its directories without
|
||||
// following symlinks, and returns its path and whether it is a directory.
|
||||
func resolve(root Root, p string) (string, bool, error) {
|
||||
if p == "." {
|
||||
info, err := os.Lstat(root.Path)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return root.Path, info.IsDir(), nil
|
||||
}
|
||||
r, err := os.OpenRoot(root.Path)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
defer r.Close()
|
||||
parts := strings.Split(p, "/")
|
||||
for i := range parts {
|
||||
info, err := r.Lstat(filepath.FromSlash(strings.Join(parts[:i+1], "/")))
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if !info.IsDir() && (i < len(parts)-1 || !info.Mode().IsRegular()) {
|
||||
return "", false, errDenied
|
||||
}
|
||||
if i == len(parts)-1 {
|
||||
return filepath.Join(root.Path, filepath.FromSlash(p)), info.IsDir(), nil
|
||||
}
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
// samePath reports whether a and b are the same path, which on Windows
|
||||
// EvalSymlinks gives the case of the names on disk.
|
||||
func samePath(a, b string) bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
return strings.EqualFold(a, b)
|
||||
}
|
||||
return a == b
|
||||
}
|
||||
|
||||
// request is what the page sends.
|
||||
type request struct {
|
||||
Root string `json:"root"`
|
||||
Path string `json:"path"`
|
||||
Recursive bool `json:"recursive"`
|
||||
DebounceMS int `json:"debounceMs"`
|
||||
}
|
||||
|
||||
// part is what Go streams: "ready" once everything is watched, then
|
||||
// "events", a part per batch.
|
||||
type part struct {
|
||||
Type string `json:"type"`
|
||||
Events []mygo.FileEvent `json:"events,omitzero"`
|
||||
}
|
||||
|
||||
// outcome is how a watch ended, the result of Watch: the code of what
|
||||
// failed or stopped it, or none.
|
||||
type outcome struct {
|
||||
Code string `json:"code,omitzero"`
|
||||
Message string `json:"message,omitzero"`
|
||||
}
|
||||
|
||||
// failure is the code of a failure, as pages see it: never a path.
|
||||
type failure string
|
||||
|
||||
func (f failure) Error() string { return "filesystem watch " + strings.ReplaceAll(string(f), "-", " ") }
|
||||
|
||||
const (
|
||||
errDenied failure = "denied"
|
||||
errLimit failure = "limit"
|
||||
errNotFound failure = "not-found"
|
||||
errUnsupported failure = "unsupported"
|
||||
errEncoding failure = "path-encoding"
|
||||
errIO failure = "io"
|
||||
)
|
||||
|
||||
func codeFor(err error) failure {
|
||||
if f, ok := errors.AsType[failure](err); ok {
|
||||
return f
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, mygo.ErrWatchLimit):
|
||||
return errLimit
|
||||
case errors.Is(err, errors.ErrUnsupported):
|
||||
return errUnsupported
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
return errNotFound
|
||||
default:
|
||||
return errIO
|
||||
}
|
||||
}
|
||||
|
||||
// Watch watches what the request names for the calling page, streaming
|
||||
// "ready" once everything is watched, then the batches of events, until
|
||||
// the page closes parts or goes away, or the watch ends. It returns what
|
||||
// failed, if anything.
|
||||
func (s *service) Watch(ctx context.Context, req request, parts *mygo.Channel[part]) outcome {
|
||||
page := mygo.CallerPage(ctx)
|
||||
if page == nil {
|
||||
return outcome{Code: string(errDenied), Message: errDenied.Error()}
|
||||
}
|
||||
return s.run(ctx, page, req, parts.Send, parts.Close)
|
||||
}
|
||||
|
||||
func (s *service) run(ctx context.Context, page any, req request, send func(part) error, unblock func()) outcome {
|
||||
err := s.watch(ctx, page, req, send, unblock)
|
||||
if err == nil || ctx.Err() != nil {
|
||||
return outcome{}
|
||||
}
|
||||
f := codeFor(err)
|
||||
return outcome{Code: string(f), Message: f.Error()}
|
||||
}
|
||||
|
||||
// root returns the root named name, which it checks is still what it was.
|
||||
func (s *service) root(ctx context.Context, name string) (Root, error) {
|
||||
if !alias.MatchString(name) {
|
||||
return Root{}, errDenied
|
||||
}
|
||||
if root, ok := s.opts.Roots[name]; ok {
|
||||
info, err := validateRoot(root.Path)
|
||||
if err != nil {
|
||||
return Root{}, err
|
||||
}
|
||||
// A directory replaced since setup is another one; a file is
|
||||
// replaced whenever an editor saves it, but must remain a file.
|
||||
if known := s.identities[name]; info.IsDir() != known.IsDir() || known.IsDir() && !os.SameFile(info, known) {
|
||||
return Root{}, errIO
|
||||
}
|
||||
return root, nil
|
||||
}
|
||||
if s.opts.Resolve == nil {
|
||||
return Root{}, errDenied
|
||||
}
|
||||
root, ok := s.opts.Resolve(ctx, name)
|
||||
if !ok {
|
||||
return Root{}, errDenied
|
||||
}
|
||||
root, _, err := canonical(root)
|
||||
return root, err
|
||||
}
|
||||
|
||||
func (s *service) watch(ctx context.Context, page any, req request, send func(part) error, unblock func()) error {
|
||||
if req.Path == "" {
|
||||
req.Path = "."
|
||||
}
|
||||
if !validPath(req.Path) || !alias.MatchString(req.Root) {
|
||||
return errDenied
|
||||
}
|
||||
if req.DebounceMS > 60000 {
|
||||
return errLimit
|
||||
}
|
||||
root, err := s.root(ctx, req.Root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target, isDir, err := resolve(root, req.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// A root that isn't Recursive lets pages watch itself and the files
|
||||
// in it, not the directories.
|
||||
if req.Recursive && !root.Recursive || !root.Recursive && req.Path != "." && (isDir || strings.Contains(req.Path, "/")) {
|
||||
return errDenied
|
||||
}
|
||||
if s.opts.Allow != nil && !s.opts.Allow(ctx, Request{Root: req.Root, Path: req.Path, Recursive: req.Recursive}) {
|
||||
return errDenied
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
entry := &active{page: page, ctx: ctx}
|
||||
s.mu.Lock()
|
||||
count := 0
|
||||
for a := range s.active {
|
||||
if a.page == page && a.ctx.Err() == nil {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if len(s.active) >= s.opts.MaxWatches || count >= s.opts.MaxWatchesPerPage {
|
||||
s.mu.Unlock()
|
||||
return errLimit
|
||||
}
|
||||
s.active[entry] = true
|
||||
s.mu.Unlock()
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
delete(s.active, entry)
|
||||
s.mu.Unlock()
|
||||
}()
|
||||
opts := mygo.FileWatchOptions{Recursive: req.Recursive, Debounce: time.Duration(req.DebounceMS) * time.Millisecond}
|
||||
if ignore := root.Ignore; ignore != nil {
|
||||
opts.Ignore = func(p string, isDir bool) bool { return ignore(path.Join(req.Path, p), isDir) }
|
||||
}
|
||||
life, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
w, err := s.factory(life, target, opts)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
defer w.Close()
|
||||
if !samePath(w.Root(), target) {
|
||||
return errDenied // a symlink appeared since
|
||||
}
|
||||
// The page going away unblocks a send waiting for it.
|
||||
stop := context.AfterFunc(ctx, func() { w.Close(); unblock() })
|
||||
defer stop()
|
||||
if send(part{Type: "ready"}) != nil {
|
||||
return nil
|
||||
}
|
||||
for {
|
||||
batch, err := w.Next(life)
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) || ctx.Err() != nil {
|
||||
return nil // closed, or the root went away
|
||||
}
|
||||
return err
|
||||
}
|
||||
for _, e := range batch {
|
||||
if !utf8.ValidString(e.Path) || !utf8.ValidString(e.OldPath) {
|
||||
return errEncoding
|
||||
}
|
||||
}
|
||||
if send(part{Type: "events", Events: batch}) != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
package watch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
)
|
||||
|
||||
type fakeWatcher struct {
|
||||
root string
|
||||
once sync.Once
|
||||
closed chan struct{}
|
||||
batches [][]mygo.FileEvent
|
||||
err error
|
||||
}
|
||||
|
||||
func (w *fakeWatcher) Next(context.Context) ([]mygo.FileEvent, error) {
|
||||
if len(w.batches) > 0 {
|
||||
b := w.batches[0]
|
||||
w.batches = w.batches[1:]
|
||||
return b, nil
|
||||
}
|
||||
if w.err != nil {
|
||||
return nil, w.err
|
||||
}
|
||||
return nil, io.EOF
|
||||
}
|
||||
func (w *fakeWatcher) Close() error { w.once.Do(func() { close(w.closed) }); return nil }
|
||||
func (w *fakeWatcher) Root() string { return w.root }
|
||||
func (w *fakeWatcher) isClosed() bool {
|
||||
select {
|
||||
case <-w.closed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// pluginFixture returns the plugin's service with the root "project", and
|
||||
// a page.
|
||||
func pluginFixture(t *testing.T, opts Options) (*service, string, any) {
|
||||
t.Helper()
|
||||
dir, err := filepath.EvalSymlinks(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if opts.Roots == nil {
|
||||
opts.Roots = map[string]Root{"project": {Path: dir}}
|
||||
}
|
||||
p := New(opts)
|
||||
if err = p.Setup(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p.Service.(*service), dir, new(int)
|
||||
}
|
||||
|
||||
// collect runs req for page and returns the parts sent, and as the last
|
||||
// one the outcome, as an "error" part.
|
||||
func collect(s *service, ctx context.Context, page any, req request) []result {
|
||||
var parts []result
|
||||
o := s.run(ctx, page, req, func(p part) error { parts = append(parts, result{Type: p.Type, Events: p.Events}); return nil }, func() {})
|
||||
if o.Code != "" {
|
||||
parts = append(parts, result{Type: "error", Code: o.Code, Message: o.Message})
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
type result struct {
|
||||
Type string
|
||||
Events []mygo.FileEvent
|
||||
Code, Message string
|
||||
}
|
||||
|
||||
func TestStreamReadyAndCleanup(t *testing.T) {
|
||||
s, dir, page := pluginFixture(t, Options{})
|
||||
w := &fakeWatcher{root: dir, closed: make(chan struct{}), batches: [][]mygo.FileEvent{{{Op: mygo.FileCreate, Path: "a"}, {Op: mygo.FileWrite, Path: "b"}}}}
|
||||
s.factory = func(_ context.Context, path string, o mygo.FileWatchOptions) (watcher, error) {
|
||||
if path != dir || o.Debounce != -time.Millisecond {
|
||||
t.Fatalf("watch %s %+v", path, o)
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
parts := collect(s, context.Background(), page, request{Root: "project", DebounceMS: -1})
|
||||
if len(parts) != 2 || parts[0].Type != "ready" || len(parts[1].Events) != 2 {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
if !w.isClosed() {
|
||||
t.Fatal("not closed")
|
||||
}
|
||||
if len(s.active) != 0 {
|
||||
t.Fatal("quota leaked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamSanitizesFailures(t *testing.T) {
|
||||
s, _, page := pluginFixture(t, Options{})
|
||||
s.factory = func(context.Context, string, mygo.FileWatchOptions) (watcher, error) {
|
||||
return nil, &os.PathError{Op: "watch", Path: "/secret/private", Err: errors.New("secret")}
|
||||
}
|
||||
parts := collect(s, context.Background(), page, request{Root: "project"})
|
||||
if len(parts) != 1 || parts[0].Type != "error" || parts[0].Code != "io" || strings.Contains(parts[0].Message, "secret") {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
s.factory = func(context.Context, string, mygo.FileWatchOptions) (watcher, error) {
|
||||
return nil, mygo.ErrWatchLimit
|
||||
}
|
||||
if parts := collect(s, context.Background(), page, request{Root: "project"}); parts[0].Code != "limit" {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermissionsAndQuota(t *testing.T) {
|
||||
s, dir, page := pluginFixture(t, Options{MaxWatchesPerPage: 1})
|
||||
if err := os.Mkdir(filepath.Join(dir, "sub"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "file"), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.factory = func(context.Context, string, mygo.FileWatchOptions) (watcher, error) {
|
||||
t.Fatal("unauthorized factory call")
|
||||
return nil, nil
|
||||
}
|
||||
// A root without Recursive lets pages watch it and its files, not its
|
||||
// directories.
|
||||
for _, req := range []request{{Root: "project", Recursive: true}, {Root: "project", Path: "sub"}} {
|
||||
if parts := collect(s, context.Background(), page, req); parts[0].Code != "denied" {
|
||||
t.Fatalf("%+v: %+v", req, parts)
|
||||
}
|
||||
}
|
||||
block := make(chan struct{})
|
||||
s.factory = func(_ context.Context, path string, _ mygo.FileWatchOptions) (watcher, error) {
|
||||
return &fakeWatcher{root: path, closed: make(chan struct{}), err: errors.New("blocked")}, nil
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
s.run(ctx, page, request{Root: "project", Path: "file"}, func(p part) error {
|
||||
if p.Type == "ready" {
|
||||
<-block
|
||||
}
|
||||
return nil
|
||||
}, func() {})
|
||||
}()
|
||||
for {
|
||||
s.mu.Lock()
|
||||
n := len(s.active)
|
||||
s.mu.Unlock()
|
||||
if n == 1 {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if parts := collect(s, context.Background(), page, request{Root: "project"}); parts[0].Code != "limit" {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
// Another page has its own quota, and a page's watches whose context
|
||||
// is done no longer count, before they have stopped.
|
||||
if parts := collect(s, context.Background(), new(int), request{Root: "project"}); parts[0].Type != "ready" {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
cancel()
|
||||
if parts := collect(s, context.Background(), page, request{Root: "project"}); parts[0].Type != "ready" {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
close(block)
|
||||
<-done
|
||||
}
|
||||
|
||||
func TestPaths(t *testing.T) {
|
||||
s, dir, page := pluginFixture(t, Options{})
|
||||
s.opts.Roots["project"] = Root{Path: dir, Recursive: true}
|
||||
for _, p := range []string{"a/b", "a/b/c"} {
|
||||
if err := os.MkdirAll(filepath.Join(dir, filepath.FromSlash(p)), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(dir, "a"), filepath.Join(dir, "link")); err != nil {
|
||||
t.Skipf("symlinks unavailable: %v", err)
|
||||
}
|
||||
var watched []string
|
||||
s.factory = func(_ context.Context, path string, _ mygo.FileWatchOptions) (watcher, error) {
|
||||
watched = append(watched, path)
|
||||
return &fakeWatcher{root: path, closed: make(chan struct{})}, nil
|
||||
}
|
||||
for _, p := range []string{"", ".", "a", "a/b/c"} {
|
||||
if parts := collect(s, context.Background(), page, request{Root: "project", Path: p, Recursive: true}); parts[0].Type != "ready" {
|
||||
t.Fatalf("%q: %+v", p, parts)
|
||||
}
|
||||
}
|
||||
want := []string{dir, dir, filepath.Join(dir, "a"), filepath.Join(dir, "a", "b", "c")}
|
||||
if strings.Join(watched, "\n") != strings.Join(want, "\n") {
|
||||
t.Fatalf("watched %v", watched)
|
||||
}
|
||||
for _, p := range []string{"..", "../x", "/etc", "a/../..", "a//b", "./a", `a\b`, "link", "link/b", "missing"} {
|
||||
parts := collect(s, context.Background(), page, request{Root: "project", Path: p})
|
||||
if parts[0].Type != "error" || p == "missing" && parts[0].Code != "not-found" {
|
||||
t.Fatalf("%q: %+v", p, parts)
|
||||
}
|
||||
}
|
||||
// What Ignore is asked is relative to the root.
|
||||
var asked string
|
||||
s.opts.Roots["project"] = Root{Path: dir, Recursive: true, Ignore: func(p string, isDir bool) bool { asked = p; return false }}
|
||||
s.factory = func(_ context.Context, path string, o mygo.FileWatchOptions) (watcher, error) {
|
||||
o.Ignore("c", true)
|
||||
return &fakeWatcher{root: path, closed: make(chan struct{})}, nil
|
||||
}
|
||||
collect(s, context.Background(), page, request{Root: "project", Path: "a/b"})
|
||||
if asked != "a/b/c" {
|
||||
t.Fatalf("asked %q", asked)
|
||||
}
|
||||
}
|
||||
|
||||
// Allow gets the request, and Resolve grants roots at run time.
|
||||
func TestAllowAndResolve(t *testing.T) {
|
||||
picked, err := filepath.EvalSymlinks(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var requests []Request
|
||||
s, _, page := pluginFixture(t, Options{
|
||||
Resolve: func(ctx context.Context, name string) (Root, bool) {
|
||||
return Root{Path: picked, Recursive: true}, name == "picked"
|
||||
},
|
||||
Allow: func(ctx context.Context, r Request) bool {
|
||||
requests = append(requests, r)
|
||||
return r.Path != "secret"
|
||||
},
|
||||
})
|
||||
if err := os.Mkdir(filepath.Join(picked, "secret"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.factory = func(_ context.Context, path string, _ mygo.FileWatchOptions) (watcher, error) {
|
||||
return &fakeWatcher{root: path, closed: make(chan struct{})}, nil
|
||||
}
|
||||
if parts := collect(s, context.Background(), page, request{Root: "picked", Recursive: true}); parts[0].Type != "ready" {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
if parts := collect(s, context.Background(), page, request{Root: "picked", Path: "secret"}); parts[0].Code != "denied" {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
if parts := collect(s, context.Background(), page, request{Root: "other"}); parts[0].Code != "denied" {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
if len(requests) != 2 || requests[0] != (Request{Root: "picked", Path: ".", Recursive: true}) || requests[1].Path != "secret" {
|
||||
t.Fatalf("requests %+v", requests)
|
||||
}
|
||||
}
|
||||
|
||||
// A root replaced since setup is not watched.
|
||||
func TestReplacedRoot(t *testing.T) {
|
||||
s, dir, page := pluginFixture(t, Options{})
|
||||
if err := os.Rename(dir, dir+"-old"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parts := collect(s, context.Background(), page, request{Root: "project"}); parts[0].Code != "io" {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDenyUnknownRoot(t *testing.T) {
|
||||
p := New(Options{})
|
||||
if err := p.Setup(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, root := range []string{"project", "../", "/tmp", `C:\secret`, "a:b"} {
|
||||
parts := collect(p.Service.(*service), context.Background(), new(int), request{Root: root})
|
||||
if len(parts) != 1 || parts[0].Code != "denied" {
|
||||
t.Fatalf("%q: %+v", root, parts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanonicalRoot(t *testing.T) {
|
||||
parent := t.TempDir()
|
||||
dir := filepath.Join(parent, "real")
|
||||
if err := os.Mkdir(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := filepath.Join(parent, "alias")
|
||||
if err := os.Symlink(dir, link); err != nil {
|
||||
t.Skipf("symlinks unavailable: %v", err)
|
||||
}
|
||||
p := New(Options{Roots: map[string]Root{"project": {Path: link}}})
|
||||
if err := p.Setup(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := filepath.EvalSymlinks(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := p.Service.(*service)
|
||||
if got := s.opts.Roots["project"].Path; got != want {
|
||||
t.Fatalf("root = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguration(t *testing.T) {
|
||||
dir, err := filepath.EvalSymlinks(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := filepath.Join(dir, "config.json")
|
||||
if err := os.WriteFile(file, nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
roots := map[string]Root{"project": {Path: dir}, "config": {Path: file}}
|
||||
p := New(Options{Roots: roots})
|
||||
roots["project"] = Root{Path: "relative"}
|
||||
if err := p.Setup(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, opts := range []Options{{Roots: map[string]Root{"../": {Path: dir}}}, {Roots: map[string]Root{"project": {Path: "relative"}}}, {MaxWatchesPerPage: -1}, {MaxWatches: -1}} {
|
||||
if err := New(opts).Setup(); err == nil {
|
||||
t.Fatalf("accepted %+v", opts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A file root replaced, as editors save, is still watched.
|
||||
func TestFileRoot(t *testing.T) {
|
||||
dir, err := filepath.EvalSymlinks(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := filepath.Join(dir, "settings.json")
|
||||
if err := os.WriteFile(file, nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, _, page := pluginFixture(t, Options{Roots: map[string]Root{"settings": {Path: file}}})
|
||||
s.factory = func(_ context.Context, path string, _ mygo.FileWatchOptions) (watcher, error) {
|
||||
return &fakeWatcher{root: path, closed: make(chan struct{})}, nil
|
||||
}
|
||||
if err := os.WriteFile(file+".tmp", []byte("{}"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Rename(file+".tmp", file); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parts := collect(s, context.Background(), page, request{Root: "settings"}); parts[0].Type != "ready" {
|
||||
t.Fatalf("parts %+v", parts)
|
||||
}
|
||||
for _, req := range []request{{Root: "settings", Path: "x"}, {Root: "settings", Recursive: true}} {
|
||||
if parts := collect(s, context.Background(), page, req); parts[0].Code == "" {
|
||||
t.Fatalf("%+v: %+v", req, parts)
|
||||
}
|
||||
}
|
||||
|
||||
// A file grant must not expand to a directory and its children.
|
||||
if err := os.Remove(file); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(file, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(file, "child"), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.factory = func(context.Context, string, mygo.FileWatchOptions) (watcher, error) {
|
||||
t.Fatal("a file root replaced by a directory reached the watcher")
|
||||
return nil, nil
|
||||
}
|
||||
for _, path := range []string{".", "child"} {
|
||||
parts := collect(s, context.Background(), page, request{Root: "settings", Path: path})
|
||||
if len(parts) != 1 || parts[0].Code != "io" {
|
||||
t.Fatalf("%q: %+v", path, parts)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user