sal/docs/os/fs.md
2025-05-08 09:54:20 +03:00

339 lines
12 KiB
Markdown

# os.fs Module
The `os` module provides functions for interacting with the operating system, including file system operations, command execution checks, downloads, and package management.
All functions that interact with the file system or external commands will halt the script execution if an error occurs, unless explicitly noted otherwise.
---
### `copy(src, dest)`
Recursively copy a file or directory from source to destination.
- **Description**: Performs a recursive copy operation. Halts script execution on failure.
- **Returns**: `String` - The destination path.
- **Arguments**:
- `src`: `String` - The path to the source file or directory.
- `dest`: `String` - The path to the destination file or directory.
```rhai
print("Copying directory...");
let source_dir = "/tmp/source_data";
let dest_dir = "/backup/source_data";
let copied_path = os::copy(source_dir, dest_dir); // Halts on error
print(`Copied ${source_dir} to ${copied_path}`);
```
---
### `exist(path)`
Check if a file or directory exists.
- **Description**: Checks for the presence of a file or directory at the given path. This function does NOT halt on error if the path is invalid or permissions prevent checking.
- **Returns**: `Boolean` - `true` if the path exists, `false` otherwise.
- **Arguments**:
- `path`: `String` - The path to check.
```rhai
if os::exist("config.json") {
print(`${file_path} exists.`);
} else {
print(`${file_path} does not exist.`);
}
```
---
### `find_file(dir, filename)`
Find a file in a directory (with support for wildcards).
- **Description**: Searches for a file matching `filename` within the specified `dir`. Supports simple wildcards like `*` and `?`. Halts script execution if the directory cannot be read or if no file is found.
- **Returns**: `String` - The path to the first file found that matches the pattern.
- **Arguments**:
- `dir`: `String` - The directory to search within.
- `filename`: `String` - The filename pattern to search for (e.g., `"*.log"`).
```rhai
let log_file = os::find_file("/var/log", "syslog*.log"); // Halts if not found or directory error
print(`Found log file: ${log_file}`);
```
---
### `find_files(dir, filename)`
Find multiple files in a directory (recursive, with support for wildcards).
- **Description**: Recursively searches for all files matching `filename` within the specified `dir` and its subdirectories. Supports simple wildcards. Halts script execution if the directory cannot be read.
- **Returns**: `Array` of `String` - An array containing paths to all matching files.
- **Arguments**:
- `dir`: `String` - The directory to start the recursive search from.
- `filename`: `String` - The filename pattern to search for (e.g., `"*.tmp"`).
```rhai
let temp_files = os::find_files("/tmp", "*.swp"); // Halts on directory error
print("Found temporary files:");
for file in temp_files {
print(`- ${file}`);
}
```
---
### `find_dir(dir, dirname)`
Find a directory in a parent directory (with support for wildcards).
- **Description**: Searches for a directory matching `dirname` within the specified `dir`. Supports simple wildcards. Halts script execution if the directory cannot be read or if no directory is found.
- **Returns**: `String` - The path to the first directory found that matches the pattern.
- **Arguments**:
- `dir`: `String` - The directory to search within.
- `dirname`: `String` - The directory name pattern to search for (e.g., `"backup_*"`).
```rhai
let latest_backup_dir = os::find_dir("/mnt/backups", "backup_20*"); // Halts if not found or directory error
print(`Found backup directory: ${latest_backup_dir}`);
```
---
### `find_dirs(dir, dirname)`
Find multiple directories in a parent directory (recursive, with support for wildcards).
- **Description**: Recursively searches for all directories matching `dirname` within the specified `dir` and its subdirectories. Supports simple wildcards. Halts script execution if the directory cannot be read.
- **Returns**: `Array` of `String` - An array containing paths to all matching directories.
- **Arguments**:
- `dir`: `String` - The directory to start the recursive search from.
- `dirname`: `String` - The directory name pattern to search for (e.g., `"project_*_v?"`).
```rhai
let project_versions = os::find_dirs("/home/user/dev", "project_*_v?"); // Halts on directory error
print("Found project version directories:");
for dir in project_versions {
print(`- ${dir}`);
}
```
---
### `delete(path)`
Delete a file or directory (defensive - doesn't error if file doesn't exist).
- **Description**: Deletes the file or directory at the given path. If the path does not exist, the function does nothing and does not halt. Halts script execution on other errors (e.g., permission denied, directory not empty). Returns the path that was attempted to be deleted.
- **Returns**: `String` - The path that was given as input.
- **Arguments**:
- `path`: `String` - The path to the file or directory to delete.
```rhai
let temp_path = "/tmp/temporary_item";
print(`Attempting to delete: ${temp_path}`);
os::delete(temp_path); // Halts on permissions or non-empty directory error
print("Deletion attempt finished.");
```
---
### `mkdir(path)`
Create a directory and all parent directories (defensive - doesn't error if directory exists).
- **Description**: Creates the directory at the given path, including any necessary parent directories. If the directory already exists, the function does nothing and does not halt. Halts script execution on other errors (e.g., permission denied). Returns the path that was created (or already existed).
- **Returns**: `String` - The path that was created or checked.
- **Arguments**:
- `path`: `String` - The path to the directory to create.
```rhai
let new_dir = "/data/processed/reports";
print(`Ensuring directory exists: ${new_dir}`);
os::mkdir(new_dir); // Halts on permission error
print("Directory check/creation finished.");
```
---
### `file_size(path)`
Get the size of a file in bytes.
- **Description**: Returns the size of the file at the given path. Halts script execution if the file does not exist or cannot be accessed.
- **Returns**: `Integer` - The size of the file in bytes (as i64).
- **Arguments**:
- `path`: `String` - The path to the file.
```rhai
let file_path = "important_document.pdf";
let size = os::file_size(file_path); // Halts if file not found or cannot read
print(`File size: ${size} bytes`);
```
---
### `rsync(src, dest)`
Sync directories using rsync (or platform equivalent).
- **Description**: Synchronizes the contents of the source directory (`src`) to the destination directory (`dest`) using the system's available rsync-like command. Halts script execution on any error during the sync process. Returns a success message string.
- **Returns**: `String` - A success message indicating the operation completed.
- **Arguments**:
- `src`: `String` - The source directory.
- `dest`: `String` - The destination directory.
```rhai
let source = "/local/project_files";
let destination = "/remote/backup/project_files";
print(`Syncing from ${source} to ${destination}...`);
let result_message = os::rsync(source, destination); // Halts on error
print(`Sync successful: ${result_message}`);
```
---
### `chdir(path)`
Change the current working directory.
- **Description**: Changes the current working directory of the script process. Halts script execution if the directory does not exist or cannot be accessed. Returns the new current working directory path.
- **Returns**: `String` - The absolute path of the directory the process changed into.
- **Arguments**:
- `path`: `String` - The path to change the working directory to.
```rhai
print(`Current directory: ${os::chdir(".")}`); // Use "." to get current path
let new_cwd = "/tmp";
os::chdir(new_cwd); // Halts if directory not found or access denied
print(`Changed directory to: ${os::chdir(".")}`);
```
---
### `file_read(path)`
Read the contents of a file.
- **Description**: Reads the entire content of the file at the given path into a string. Halts script execution if the file does not exist or cannot be read.
- **Returns**: `String` - The content of the file.
- **Arguments**:
- `path`: `String` - The path to the file.
```rhai
let config_content = os::file_read("settings.conf"); // Halts if file not found or cannot read
print("Config content:");
print(config_content);
```
---
### `file_write(path, content)`
Write content to a file (creates the file if it doesn\'t exist, overwrites if it does).
- **Description**: Writes the specified `content` to the file at the given `path`. If the file exists, its content is replaced. If it doesn't exist, it is created. Halts script execution on error (e.g., permission denied, invalid path). Returns the path written to.
- **Returns**: `String` - The path of the file written to.
- **Arguments**:
- `path`: `String` - The path to the file.
- `content`: `String` - The content to write to the file.
```rhai
let output_path = "/tmp/hello.txt";
let text_to_write = "Hello from Rhai!";
os::file_write(output_path, text_to_write); // Halts on error
print(`Wrote to ${output_path}`);
```
---
### `file_write_append(path, content)`
Append content to a file (creates the file if it doesn\'t exist).
- **Description**: Appends the specified `content` to the end of the file at the given `path`. If the file does not exist, it is created. Halts script execution on error (e.g., permission denied, invalid path). Returns the path written to.
- **Returns**: `String` - The path of the file written to.
- **Arguments**:
- `path`: `String` - The path to the file.
- `content`: `String` - The content to append to the file.
```rhai
let log_path = "application.log";
let log_entry = "User login failed.\n";
os::file_write_append(log_path, log_entry); // Halts on error
print(`Appended to ${log_path}`);
```
---
### `mv(src, dest)`
Move a file or directory from source to destination.
- **Description**: Moves the file or directory from `src` to `dest`. Halts script execution on error (e.g., permission denied, source not found, destination exists and cannot be overwritten). Returns the destination path.
- **Returns**: `String` - The path of the destination.
- **Arguments**:
- `src`: `String` - The path to the source file or directory.
- `dest`: `String` - The path to the destination.
```rhai
let old_path = "/tmp/report.csv";
let new_path = "/archive/reports/report_final.csv";
os::mv(old_path, new_path); // Halts on error
print(`Moved ${old_path} to ${new_path}`);
```
---
### `which(command)`
Check if a command exists in the system PATH.
- **Description**: Searches the system's PATH environment variable for the executable `command`. This function does NOT halt on error; it returns an empty string if the command is not found.
- **Returns**: `String` - The full path to the command executable if found, otherwise an empty string (`""`).
- **Arguments**:
- `command`: `String` - The name of the command to search for (e.g., `"git"`).
```rhai
let git_path = os::which("git");
if git_path != "" {
print(`Git executable found at: ${git_path}`);
} else {
print("Git executable not found in PATH.");
}
```
---
### `cmd_ensure_exists(commands)`
Ensure that one or more commands exist in the system PATH.
- **Description**: Checks if all command names specified in the `commands` string (space or comma separated) exist in the system's PATH. Halts script execution if any of the commands are not found. Returns a success message if all commands are found.
- **Returns**: `String` - A success message.
- **Arguments**:
- `commands`: `String` - A string containing one or more command names, separated by spaces or commas (e.g., `"curl,tar,unzip"`).
```rhai
print("Ensuring required commands are available...");
os::cmd_ensure_exists("git curl docker"); // Halts if any command is missing
print("All required commands found.");
```
---
### `chmod_exec(path)`
Make a file executable (equivalent to chmod +x).
- **Description**: Sets the executable permission for the file at the given `path` for the owner, group, and others. Halts script execution on error (e.g., file not found, permission denied). Returns the path modified.
- **Returns**: `String` - The path of the file whose permissions were modified.
- **Arguments**:
- `path`: `String` - The path to the file.
```rhai
let script_path = "/usr/local/bin/myscript";
print(`Making ${script_path} executable...`);
os::chmod_exec(script_path); // Halts on error
print("Permissions updated.");
```