os Module
The os module provides a comprehensive way to interact with the operating system, including structured device information through maps, file operations, environment variables, and system utilities.
Functions
Args()
Returns the process arguments excluding the interpreter binary. Index 0 is typically the script path, and subsequent elements are the CLI arguments you passed when invoking Harneet.
Returns: - (array, error): An array of strings with the process arguments (script path first).
Example:
| Args Example | |
|---|---|
Getenv(name)
Gets the value of an environment variable.
Parameters: - name: The name of the environment variable.
Returns: - (string, error): The value of the environment variable, or an empty string if it's not set.
Example:
| Getenv Example | |
|---|---|
Setenv(name, value)
Sets the value of an environment variable.
Parameters: - name: The name of the environment variable. - value: The value to set.
Returns: - (None, error)
Example:
Type()
Returns the operating system type.
Returns: - (string, error): The OS type (e.g., "darwin", "linux", "windows").
Example:
| Type Example | |
|---|---|
Version()
Returns the operating system version.
Returns: - (string, error): The OS version.
Arch()
Returns the system architecture.
Returns: - (string, error): The architecture (e.g., "amd64", "arm64").
Getwd()
Returns the current working directory.
Returns: - (string, error): The current working directory path.
Chdir(path)
Changes the current working directory.
Parameters: - path: The path to the new directory.
Mkdir(path)
Creates a new directory.
Parameters: - path: The path of the directory to create.
Remove(path)
Removes a file or directory.
Parameters: - path: The path of the file or directory to remove.
Exists(path)
Checks if a file or directory exists.
Parameters: - path: The path to check.
Returns: - (boolean, error): true if the path exists, false otherwise.
TempDir()
Returns the default directory to use for temporary files.
Returns: - (string, error): The temporary directory path (e.g., "/tmp" on Unix systems).
Example:
| TempDir Example | |
|---|---|
CreateTemp(dir, pattern)
Creates a new temporary file in the directory dir with a name beginning with pattern and returns the file path. The file is created on disk immediately with a unique name.
Parameters: - dir (string): Directory for temp file (use empty string "" for os.TempDir()) - pattern (string): Name pattern (e.g., "myapp-*.txt" where * is replaced with random string)
Returns: - (string, error): The full path to the created temporary file.
Key Features: - Automatic location: Empty string uses system temp directory (/tmp on Unix, %TEMP% on Windows) - Pattern matching: The * in pattern is replaced with a random string to ensure uniqueness - File created: File is created on disk immediately and returned closed - No collisions: Guaranteed unique filename prevents conflicts
Pattern Examples: - "upload-*.dat" → upload-1234567.dat - "cache-*.json" → cache-9876543.json - "test-*" → test-4567890
Example 1 - Basic Usage:
Example 2 - Upload Processing:
Example 3 - Custom Directory:
| CreateTemp Custom Directory | |
|---|---|
Example 4 - Safe Pattern with Defer (Future):
Chmod(name, mode)
Changes the mode (permissions) of the named file to mode.
Parameters: - name (string): Path to the file - mode (int): Unix file permissions as decimal (e.g., 420 for 0644, 493 for 0755)
Returns: - (None, error): None on success, error on failure.
Common Permission Values: - 420 (0644): rw-r--r-- - Owner read/write, group/others read - 384 (0600): rw------- - Owner read/write only - 493 (0755): rwxr-xr-x - Owner full, group/others read/execute
Example:
| Chmod Example | |
|---|---|
Chtimes(name, atime, mtime)
Changes the access and modification times of the named file.
Parameters: - name (string): Path to the file - atime (int): Access time as Unix timestamp (seconds since epoch) - mtime (int): Modification time as Unix timestamp (seconds since epoch)
Returns: - (None, error): None on success, error on failure.
Example:
Clearenv()
Deletes all environment variables. Use with caution - this clears the entire environment!
Returns: - (None, error): None on success.
Example:
| Clearenv Example | |
|---|---|
Environ()
Returns a copy of strings representing the environment, in the form "KEY=value".
Returns: - (array, error): Array of strings, each in "KEY=value" format.
Example:
| Environ Example | |
|---|---|
Getpid()
Returns the process ID of the caller.
Returns: - (int, error): The process ID.
Example:
| Getpid Example | |
|---|---|
Getppid()
Returns the process ID of the caller's parent.
Returns: - (int, error): The parent process ID.
Example:
| Getppid Example | |
|---|---|
LookupUser(username)
Looks up a user by username and returns a map with user information.
Parameters: - username (string): The username to look up
Returns: - (map, error): Map with keys: uid, gid, username, name, homedir
Example:
| LookupUser Example | |
|---|---|
LookupGroup(groupname)
Looks up a group by name and returns a map with group information.
Parameters: - groupname (string): The group name to look up
Returns: - (map, error): Map with keys: gid, name
Example:
| LookupGroup Example | |
|---|---|
Hostname()
Returns the host name reported by the kernel.
Returns: - (string, error): The hostname.
Example:
| Hostname Example | |
|---|---|
UserHomeDir()
Returns the current user's home directory.
Returns: - (string, error): The home directory path.
Example:
| UserHomeDir Example | |
|---|---|
Exec(cmd, args)
Runs an external command and returns its stdout as a string. On non-zero exit, returns an error containing stderr.
Parameters: - cmd (string): Command to execute - args (array): Array of string arguments
Returns: - (string, error): Command output or error with stderr.
Example:
| Exec Example | |
|---|---|
Device Functions
The following functions provide structured device information through maps, enabling modern programmatic access to system hardware data.
ListDevices()
Returns an array of device information maps for system devices.
Returns: - (array, error): Array of device maps, each containing device information.
Device Map Structure: Each device map contains the following keys: - type: Device type ("USB", "Storage", "Network") - name: Human-readable device name - id: Device identifier - status: Device status ("available", "connected", "mounted") - count: Number of devices (for USB devices)
Example:
Cross-Platform Support: - macOS: USB devices and storage drives - Linux: Individual USB devices with detailed information - Windows: Storage devices and system drives
GetDeviceInfo(deviceId)
Returns detailed information about a specific device as a structured map.
Parameters: - deviceId: Device identifier string (e.g., "system", "cpu")
Returns: - (map, error): Device information map with detailed hardware data.
Device Info Map Structure: The returned map contains the following keys: - id: Device identifier - type: Device type ("macOS Device", "Linux Device", "Windows Device") - name: Device name - status: Device status ("active", "inactive") - details: Nested map with hardware-specific information
Example:
Platform-Specific Details:
macOS (system_profiler): - Chip/Processor information - Memory specifications - Model details and serial numbers - Hardware UUID and identifiers
Linux (lscpu): - CPU architecture and specifications - Core count and threading - Cache information - Processor features
Windows (wmic): - System manufacturer and model - Total physical memory - Computer system information
JSON Integration: Device information maps work seamlessly with JSON serialization:
MkdirAll(path)
Creates a directory and all necessary parents.
Parameters: - path: Directory to create (parents will be created as needed).
Returns: - (None, error)
Example:
RemoveAll(path)
Removes a path and everything it contains.
Parameters: - path: File or directory to remove recursively.
Returns: - (None, error)
Rename(old, new)
Renames (moves) a file or directory.
Parameters: - old: Source path. - new: Destination path.
Returns: - (None, error)
ReadFile(path)
Reads a file and returns its contents as a string.
Parameters: - path: File path to read.
Returns: - (string, error)
Example:
| ReadFile Example | |
|---|---|
WriteFile(path, data)
Writes a string to a file (creates or overwrites) using 0644 permissions.
Parameters: - path: Target file path. - data: String content to write.
Returns: - (None, error)
ReadDir(path)
Reads a directory and returns an array of tuples for each entry: (name string, isDir boolean, size int, modTime string) where modTime is RFC3339 UTC.
Parameters: - path: Directory path.
Returns: - (array, error)
Example:
| ReadDir Example | |
|---|---|
Stat(path)
Returns basic file information: size (bytes), isDir (boolean), modTime (RFC3339 UTC).
Parameters: - path: File or directory path.
Returns: - (int, boolean, string, error)
Example:
| Stat Example | |
|---|---|
Watch(path)
Watches a file or directory by taking snapshots and reporting what changed since the previous call for that same path. This is a polling, snapshot-based API, not a background watcher.
On the first call for a given path, os.Watch stores an internal snapshot and returns an empty array. On subsequent calls, it compares the current state with the last snapshot and returns an array of change maps.
Each change map has the following keys:
path(string): Full path to the changed entryname(string): Base name of the entryisDir(boolean): Whether the entry is a directorysize(int): Size in bytes (for files)modTime(string): Last modification time (RFC3339 UTC)mode(int): File permissions (Unix-style, decimal, e.g. 420 for 0644)ops(array): Array of operation strings, any of:"create"– entry was created since last snapshot"modify"– size ormodTimechanged"chmod"– permissions changed (mode differs)"delete"– entry was removed since last snapshot
Notes:
- For files, both content changes and permission changes are reported.
- For directories, structural changes (created/deleted children) are reflected via child entries getting
create/deleteops. - Snapshots are maintained per path you pass to
os.Watch.
Returns: - (array, error): Array of change maps, or empty array if nothing changed.
Example:
### WatchStart(path, intervalMs), WatchEvents(id), WatchStop(id)
These functions provide a lower-level, event-queue based watcher built on background goroutines. They are useful when you want a dedicated watcher per path and you are comfortable polling for events.
Signatures: - os.WatchStart(path string, intervalMs int) (string, error) - os.WatchEvents(id string) (array, error) - os.WatchStop(id string) (None, error)
Behavior: - WatchStart: - Validates intervalMs > 0. - Starts a background watcher for path that snapshots the filesystem every intervalMs milliseconds and enqueues change events internally. - Returns a watcher id string like "watch-1". - WatchEvents: - Takes a watcher id and returns all pending events for that watcher. - Clears the internal event queue for that id before returning. - WatchStop: - Stops the background watcher for the given id and releases its resources.
Each event returned by WatchEvents is a map with the same shape as os.Watch change maps:
path(string)name(string)isDir(boolean)size(int)modTime(string, RFC3339 UTC)mode(int, Unix permissions as decimal)ops(array of strings like"create","modify","chmod","delete")
Example:
#### Pub-sub style helper (example package)
For many applications, a callback-based style is more convenient: you want changes to be pushed to a handler function instead of polling with WatchEvents. You can build this using Harneet's concurrency primitives (do, sleep, newCancelToken, cancel, sleepUntil).
The repository includes an example helper package at examples/watch/watch.ha with a small API:
| watch helper API (example) | |
|---|---|
A simplified usage pattern (adapt for your own project layout):
This pattern keeps all callback invocation inside Harneet's scheduler while the low-level os module handles the actual filesystem polling.
Exit(code)
Terminates the current process with the given status code.
Parameters: - code: Exit status code (int).
Returns: - (None, error)
Note: This will terminate the program immediately.
ExpandEnv(s)
Expands ${VAR} or $VAR in a string using the current environment.
Parameters: - s: Input string containing env references.
Returns: - (string, error)
Example:
| ExpandEnv Example | |
|---|---|
Device Information Maps
The os module provides structured device information through maps, making system data easy to access and process programmatically.
Map-Based Device Data
Unlike traditional string-based system information, Harneet's OS module returns structured maps that can be easily accessed, filtered, and serialized.
Benefits: - Structured Access: Use map indexing to access specific properties - Type Safety: Consistent data types for device properties - JSON Ready: Seamless integration with JSON serialization - Programmatic Processing: Easy filtering and data manipulation
Device List Structure
| Device List Structure | |
|---|---|
Device Info Structure
| Device Info Structure | |
|---|---|
Common Use Cases
System Monitoring:
| System Monitoring | |
|---|---|
Hardware Inventory:
| Hardware Inventory | |
|---|---|
API Integration:
Configuration Management:
| Configuration Management | |
|---|---|
Cross-Platform Compatibility
The device information maps provide consistent structure across platforms while including platform-specific details:
| Platform | Device Types | Hardware Details | Special Features |
|---|---|---|---|
| macOS | USB, Storage | Full system profiler data | Hardware UUID, Model numbers |
| Linux | USB (individual) | CPU specifications | Detailed USB device info |
| Windows | Storage | System manufacturer info | Drive information |
Error Handling
Device functions return structured error information:
| Error Handling | |
|---|---|