Cross-platform OS compatibility utilities for Go.
This package provides abstractions for OS-specific behaviors that differ between Windows and Unix-like systems (Linux, macOS).
go get github.com/grokify/oscompatCross-platform unique identifier generation using crypto/rand.
Why this exists: Time-based ID generation (e.g., time.Now().String()) is unreliable on Windows due to the system clock's coarse resolution (~15.6ms vs nanoseconds on Unix). This causes ID collisions when generating multiple IDs in rapid succession.
import "github.com/grokify/oscompat/id"
// Generate a 16-character hex ID (8 random bytes)
spanID := id.Generate16()
// Generate a 32-character hex ID (16 random bytes)
traceID := id.Generate32()
// Generate custom length (N bytes = 2N hex characters)
customID := id.Generate(4) // 8-character hex stringCross-platform process management utilities.
Why this exists: Unix and Windows handle process signals differently:
- Unix has
SIGTERMfor graceful termination; Windows does not - Unix uses
Setpgidfor process group management; Windows does not - Opening a URL or file in the default application takes a different program on each platform
import "github.com/grokify/oscompat/process"
// Configure a command to run detached from parent
cmd := exec.Command("myapp")
process.SetDetached(cmd)
// Send termination signal (SIGTERM on Unix, Kill on Windows)
err := process.Signal(pid)
// Find and signal a process
err := process.FindAndSignal(pid)
// Is it running? Does it match the process a record was written for?
ok, err := process.Exists(pid)
started, err := process.StartTime(pid) // process.ErrNotFound if it is gone
if err == nil && started.Sub(recorded).Abs() > 2*time.Second {
// the PID was reused by a different process
}
// Hand the terminal to another program: replaces this process on Unix, runs
// it as a child and exits with its status on Windows. Returns only on failure.
err = process.Exec(path, []string{"claude", "--resume", id})
// Open a URL or a file with the user's default application:
// open on macOS, xdg-open on Linux and the BSDs, rundll32 on Windows.
err = process.OpenDefault("http://localhost:9401")Cross-platform configuration and data directory resolution.
Why this exists: Applications need platform-appropriate directories:
- Unix: XDG Base Directory Specification (~/.config, ~/.local/share)
- macOS: ~/Library/Application Support, ~/Library/Caches
- Windows: %APPDATA%, %LOCALAPPDATA%, %ProgramData%
import "github.com/grokify/oscompat/paths"
// Get app-specific config directory (creates if needed)
configDir, err := paths.AppConfig("myapp")
// Unix: ~/.config/myapp
// macOS: ~/Library/Application Support/myapp
// Windows: %APPDATA%\myapp
// Get app-specific data directory
dataDir, err := paths.AppData("myapp")
// Get app-specific cache directory
cacheDir, err := paths.AppCache("myapp")
// Get system-wide config directory
sysConfig, err := paths.SystemConfig()
// Unix: /etc
// Windows: %ProgramData%Cross-platform filesystem utilities.
Why this exists:
- File permissions (0755, 0644) are Unix-centric; Windows ignores them
- Executable detection differs: Unix uses permission bits, Windows uses file extensions
- Path separators differ (/ vs )
- Path traversal validation needs to handle both separators
- File locking is
flockon Unix andLockFileExon Windows, directories can be flushed on Unix and not on Windows, and mode bits are not enforced on Windows
import "github.com/grokify/oscompat/fs"
// Check if a file is executable (cross-platform)
isExec, err := fs.IsExecutable("/path/to/file")
// Unix: checks if any execute bit is set (mode & 0111)
// Windows: checks for .exe/.cmd/.bat/.com/.ps1 or no extension (shell scripts)
// Check with existing FileInfo (more efficient in loops)
info, _ := os.Stat("/path/to/file")
isExec := fs.IsExecutableInfo(info, "/path/to/file")
// Validate path for traversal attacks (handles both / and \)
err := fs.ValidatePath("foo/../../../etc/passwd") // returns ErrPathTraversal
err = fs.ValidatePath(`\\server\share\x`) // ErrAbsolutePath, on every platform
// Validate a forward-slash path, such as one inside a repository
err = fs.ValidateSlashPath(`docs\a.md`) // returns ErrInvalidPath
// Absolute or rooted on any platform, unlike filepath.IsAbs
fs.IsAbsAny("/etc/passwd") // true on Windows too
// Normalize path to forward slashes (for storage)
normalized := fs.NormalizePath(`foo\bar\baz`) // "foo/bar/baz"
// Convert to OS-specific path
osPath := fs.OSPath("foo/bar/baz") // "foo\bar\baz" on Windows
// Safe path joining with traversal protection
fullPath, err := fs.SafeJoin("/base", "relative/path")
// Confine a caller's path to a directory, refusing links that leave it
root, err := fs.RealDir("/srv/uploads")
path, err := fs.ResolveInRoot(root, req.Path) // ErrOutsideRoot if it escapes
// Open a file inside a directory, with the open itself confined by os.Root
f, err := fs.OpenInRoot(root, req.Path) // ErrOutsideRoot if it escapes
// Read it safely: a regular file within a limit, and the read capped too
f, err := fs.OpenRegularInRoot(root, req.Path, maxBytes) // ErrNotRegular, ErrTooLarge
body := fs.CapReader(f, maxBytes) // ErrTooLarge if it grows
// Create directory with default permissions
err := fs.MkdirAll("/path/to/dir", 0) // uses DefaultDirPerm (0755)
// Create private directory (owner-only)
err := fs.MkdirAllPrivate("/path/to/private")
// Replace a file so readers see the old one or the new one, never part of
// either: a temporary file, a flush, the mode where it is enforced, a
// rename and a flush of the directory where the platform allows
err := fs.WriteFileAtomic("/path/to/registry.json", data, 0) // DefaultFilePerm
err = fs.WriteFileAtomicPrivate("/path/to/state.json", data) // 0600
// Write file with default permissions
err := fs.WriteFile("file.txt", data, 0) // uses DefaultFilePerm (0644)
// Write private file (owner-only)
err := fs.WriteFilePrivate("secret.txt", data)
// Exclusive advisory lock between processes; waits until ctx ends
unlock, err := fs.Lock(ctx, "/path/to/state.lock")
if err != nil {
return err // context error, or fs.ErrLockUnsupported on a platform with no locking
}
defer unlock()
// Make a rename durable (a no-op where the platform offers no way to ask)
err = fs.SyncDir("/path/to/dir")
// Are mode bits meaningful here? Is a file owner-only?
if fs.PermissionsEnforced() { /* false on Windows */ }
err = fs.CheckPrivate(info) // nil on Windows; wraps fs.ErrNotPrivate elsewhere
err = fs.ChmodPrivate(f) // 0600 on an open file; a failure is ignored on WindowsCross-platform timestamp utilities for file synchronization.
Why this exists: Filesystem timestamp precision varies:
- Windows NTFS: ~100ns precision, sometimes rounded to 2 seconds
- Linux ext4/XFS: nanosecond precision
- FAT32: 2-second precision
- Network drives: varies widely
import "github.com/grokify/oscompat/tsync"
// Compare timestamps with platform-appropriate tolerance (1 second)
if tsync.Equal(file1.ModTime(), file2.ModTime()) {
// Files have same modification time (within tolerance)
}
// Check if file1 is newer than file2 (beyond tolerance)
if tsync.After(file1.ModTime(), file2.ModTime()) {
// file1 is definitively newer
}
// Compare with custom tolerance
if tsync.EqualWithTolerance(t1, t2, tsync.FAT32Tolerance) {
// Equal within 2-second tolerance
}
// Truncate timestamp for cross-platform storage
normalized := tsync.TruncateToSecond(time.Now())Cross-platform local network communication (IPC).
Why this exists: Unix domain sockets don't exist on Windows (or have limited support).
- Unix: Uses Unix domain sockets in /tmp or $XDG_RUNTIME_DIR
- Windows: Uses TCP on localhost with port discovery via file
import "github.com/grokify/oscompat/localnet"
// Server: Create local listener
listener, err := localnet.Listen("myapp")
if err != nil {
return err
}
defer listener.Close()
for {
conn, err := listener.Accept()
// handle connection...
}
// Client: Connect to local server
conn, err := localnet.Dial("myapp")
if err != nil {
return err
}
defer conn.Close()
// use conn...
// Cleanup stale socket (e.g., after crash)
localnet.Cleanup("myapp")oscompat has no dependencies: it imports the Go standard library and itself,
and nothing else (not even golang.org/x/sys), and a test enforces it. That is
what makes it safe for any module to import, including modules that keep their
own dependency set small on purpose.
In return, other modules should import oscompat instead of keeping platform-specific files of their own. Code that differs by operating system belongs here once, tested on every platform. If a difference is missing, add it here, using only the standard library.
The documentation site has a guide for each package:
- Getting started
- fs: permissions, file locks, durable renames, paths
- process, paths, id, tsync, localnet, testutil
- Writing tests that pass on Windows: wall-clock ties,
path separators, open files, signals and line endings;
testutil.ReadFileLFandtestutil.AssertGoldencompare fixtures whatever their line endings;testutil.RequirePOSIXskips a test that needs shell scripts or execute bits, with the reason.
All packages are tested on:
- Linux (ubuntu-latest)
- macOS (macos-latest)
- Windows (windows-latest)
MIT