...
This commit is contained in:
@@ -183,36 +183,33 @@ Commits staged changes.
|
||||
Pushes committed changes to the remote.
|
||||
|
||||
- **Description**: Performs `git push` to the default remote and branch.
|
||||
- **Returns**: `GitRepo` - The same `GitRepo` object for chaining. Halts on error (e.g., network issues, push rejected).
|
||||
- **Rhai Example** (assuming `app_repo` is a `GitRepo` object with committed changes):
|
||||
```rhai
|
||||
print(`Pushing changes for ${app_repo.path()}...`);
|
||||
app_repo.push(); // Halts on error
|
||||
print("Push successful.");
|
||||
```
|
||||
- **Returns**: `GitRepo`
|
||||
|
||||
```rhai
|
||||
print(`Pushing changes for ${app_repo.path()}...`);
|
||||
app_repo.push(); // Halts on error
|
||||
print("Push successful.");
|
||||
```
|
||||
|
||||
## Chaining Operations
|
||||
|
||||
`GitRepo` methods like `pull`, `reset`, `commit`, and `push` return the `GitRepo` object, allowing for chained operations. If any operation in the chain fails, script execution halts.
|
||||
```rhai
|
||||
let git_tree = git_tree_new("./my_projects");
|
||||
// Assumes "my_writable_app" exists and you have write access.
|
||||
// get() will halt if not found.
|
||||
let app_repo = git_tree.get("my_writable_app");
|
||||
print(`Performing chained operations on ${app_repo.path()}`);
|
||||
|
||||
- **Rhai Example**:
|
||||
```rhai
|
||||
let git_tree = git_tree_new("./my_projects");
|
||||
// Assumes "my_writable_app" exists and you have write access.
|
||||
// get() will halt if not found.
|
||||
let app_repo = git_tree.get("my_writable_app");
|
||||
print(`Performing chained operations on ${app_repo.path()}`);
|
||||
// This example demonstrates a common workflow.
|
||||
// Ensure the repo state is suitable (e.g., changes exist for commit/push).
|
||||
app_repo.pull()
|
||||
.commit("Rhai: Chained operations - automated update") // Commits if pull results in changes or local changes existed and were staged.
|
||||
.push();
|
||||
print("Chained pull, commit, and push reported successful.");
|
||||
|
||||
// This example demonstrates a common workflow.
|
||||
// Ensure the repo state is suitable (e.g., changes exist for commit/push).
|
||||
app_repo.pull()
|
||||
.commit("Rhai: Chained operations - automated update") // Commits if pull results in changes or local changes existed and were staged.
|
||||
.push();
|
||||
print("Chained pull, commit, and push reported successful.");
|
||||
|
||||
// Alternative:
|
||||
// app_repo.pull();
|
||||
// if app_repo.has_changes() {
|
||||
// app_repo.commit("Updates").push();
|
||||
// }
|
||||
```
|
||||
// Alternative:
|
||||
// app_repo.pull();
|
||||
// if app_repo.has_changes() {
|
||||
// app_repo.commit("Updates").push();
|
||||
// }
|
||||
```
|
||||
|
60
docs/os/download.md
Normal file
60
docs/os/download.md
Normal file
@@ -0,0 +1,60 @@
|
||||
# os.download Module
|
||||
|
||||
### `download(url, dest, min_size_kb)`
|
||||
|
||||
Download a file from URL to destination using the curl command.
|
||||
|
||||
- **Description**: Downloads a file from the given `url`. If `dest` is a directory, the filename is derived from the URL. If `dest` is a file path, it is used directly. Requires the `curl` command to be available. Halts script execution on download or file writing errors, or if the downloaded file size is less than `min_size_kb`. Returns the destination path.
|
||||
- **Returns**: `String` - The path where the file was downloaded.
|
||||
- **Arguments**:
|
||||
- `url`: `String` - The URL of the file to download.
|
||||
- `dest`: `String` - The destination path (directory or file).
|
||||
- `min_size_kb`: `Integer` - The minimum expected size of the downloaded file in kilobytes.
|
||||
|
||||
```rhai
|
||||
let download_url = "https://example.com/archive.zip";
|
||||
let download_dest_dir = "/tmp/downloads";
|
||||
print(`Downloading ${download_url} to ${download_dest_dir}...`);
|
||||
let downloaded_file_path = os::download(download_url, download_dest_dir, 50); // Halts on error
|
||||
print(`Downloaded to: ${downloaded_file_path}`);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `download_file(url, dest, min_size_kb)`
|
||||
|
||||
Download a file from URL to a specific file destination using the curl command.
|
||||
|
||||
- **Description**: Downloads a file from the given `url` directly to the specified file `dest`. Requires the `curl` command. Halts script execution on download or file writing errors, or if the downloaded file size is less than `min_size_kb`. Returns the destination path.
|
||||
- **Returns**: `String` - The path where the file was downloaded.
|
||||
- **Arguments**:
|
||||
- `url`: `String` - The URL of the file to download.
|
||||
- `dest`: `String` - The full path where the file should be saved.
|
||||
- `min_size_kb`: `Integer` - The minimum expected size of the downloaded file in kilobytes.
|
||||
|
||||
```rhai
|
||||
let data_url = "https://example.com/dataset.tar.gz";
|
||||
let local_path = "/opt/data/dataset.tar.gz";
|
||||
print(`Downloading ${data_url} to ${local_path}...`);
|
||||
os::download_file(data_url, local_path, 1024); // Halts on error
|
||||
print(`Downloaded dataset to: ${local_path}`);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `download_install(url, min_size_kb)`
|
||||
|
||||
Download a file and install it if it\'s a supported package format.
|
||||
|
||||
- **Description**: Downloads a file from the given `url` to a temporary location and then attempts to install it using the appropriate system package manager if the file format is supported (e.g., `.deb` on Ubuntu, `.pkg` or `.dmg` on MacOS). Requires the `curl` command and the system package manager. Halts script execution on download, installation, or file size errors. Returns a success message.
|
||||
- **Returns**: `String` - A success message upon successful download and installation attempt.
|
||||
- **Arguments**:
|
||||
- `url`: `String` - The URL of the package file to download and install.
|
||||
- `min_size_kb`: `Integer` - The minimum expected size of the downloaded file in kilobytes.
|
||||
|
||||
```rhai
|
||||
let package_url = "https://example.com/mytool.deb";
|
||||
print(`Downloading and installing ${package_url}...`);
|
||||
os::download_install(package_url, 300); // Halts on error
|
||||
print("Installation attempt finished.");
|
||||
```
|
338
docs/os/fs.md
Normal file
338
docs/os/fs.md
Normal file
@@ -0,0 +1,338 @@
|
||||
# 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.");
|
||||
```
|
157
docs/os/package.md
Normal file
157
docs/os/package.md
Normal file
@@ -0,0 +1,157 @@
|
||||
# os.package Module
|
||||
|
||||
### `package_install(package)`
|
||||
|
||||
Install a package using the system package manager.
|
||||
|
||||
- **Description**: Installs the specified `package` using the detected system package manager (e.g., `apt` on Ubuntu, `brew` on MacOS). Halts script execution if the package manager command fails. Returns a success message.
|
||||
- **Returns**: `String` - A message indicating successful installation.
|
||||
- **Arguments**:
|
||||
- `package`: `String` - The name of the package to install (e.g., `"nano"`).
|
||||
|
||||
```rhai
|
||||
print("Installing 'nano' package...");
|
||||
os::package_install("nano"); // Halts on package manager error
|
||||
print("'nano' installed successfully.");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `package_remove(package)`
|
||||
|
||||
Remove a package using the system package manager.
|
||||
|
||||
- **Description**: Removes the specified `package` using the detected system package manager. Halts script execution if the package manager command fails. Returns a success message.
|
||||
- **Returns**: `String` - A message indicating successful removal.
|
||||
- **Arguments**:
|
||||
- `package`: `String` - The name of the package to remove (e.g., `"htop"`).
|
||||
|
||||
```rhai
|
||||
print("Removing 'htop' package...");
|
||||
os::package_remove("htop"); // Halts on package manager error
|
||||
print("'htop' removed successfully.");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `package_update()`
|
||||
|
||||
Update package lists using the system package manager.
|
||||
|
||||
- **Description**: Updates the package lists that the system package manager uses (e.g., `apt update`, `brew update`). Halts script execution if the package manager command fails. Returns a success message.
|
||||
- **Returns**: `String` - A message indicating successful update.
|
||||
- **Arguments**: None.
|
||||
|
||||
```rhai
|
||||
print("Updating package lists...");
|
||||
os::package_update(); // Halts on package manager error
|
||||
print("Package lists updated.");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `package_upgrade()`
|
||||
|
||||
Upgrade installed packages using the system package manager.
|
||||
|
||||
- **Description**: Upgrades installed packages using the detected system package manager (e.g., `apt upgrade`, `brew upgrade`). Halts script execution if the package manager command fails. Returns a success message.
|
||||
- **Returns**: `String` - A message indicating successful upgrade.
|
||||
- **Arguments**: None.
|
||||
|
||||
```rhai
|
||||
print("Upgrading installed packages...");
|
||||
os::package_upgrade(); // Halts on package manager error
|
||||
print("Packages upgraded.");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `package_list()`
|
||||
|
||||
List installed packages using the system package manager.
|
||||
|
||||
- **Description**: Lists the names of packages installed on the system using the detected package manager. Halts script execution if the package manager command fails.
|
||||
- **Returns**: `Array` of `String` - An array containing the names of installed packages.
|
||||
- **Arguments**: None.
|
||||
|
||||
```rhai
|
||||
print("Listing installed packages...");
|
||||
let installed_packages = os::package_list(); // Halts on package manager error
|
||||
for pkg in installed_packages {
|
||||
print(`- ${pkg}`);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `package_search(query)`
|
||||
|
||||
Search for packages using the system package manager.
|
||||
|
||||
- **Description**: Searches for packages matching the given `query` using the detected system package manager. Halts script execution if the package manager command fails.
|
||||
- **Returns**: `Array` of `String` - An array containing the search results (package names and/or descriptions).
|
||||
- **Arguments**:
|
||||
- `query`: `String` - The search term.
|
||||
|
||||
```rhai
|
||||
print("Searching for 'python' packages...");
|
||||
let python_packages = os::package_search("python"); // Halts on package manager error
|
||||
for pkg in python_packages {
|
||||
print(`- ${pkg}`);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `package_is_installed(package)`
|
||||
|
||||
Check if a package is installed using the system package manager.
|
||||
|
||||
- **Description**: Checks if the specified `package` is installed using the detected system package manager. Halts script execution if the package manager command itself fails (e.g., command not found), but does NOT halt if the package is simply not found.
|
||||
- **Returns**: `Boolean` - `true` if the package is installed, `false` otherwise.
|
||||
- **Arguments**:
|
||||
- `package`: `String` - The name of the package to check (e.g., `"wget"`).
|
||||
|
||||
```rhai
|
||||
let package_name = "wget";
|
||||
if os::package_is_installed(package_name) { // Halts on package manager command error
|
||||
print(`${package_name} is installed.`);
|
||||
} else {
|
||||
print(`${package_name} is not installed.`);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `package_set_debug(debug)`
|
||||
|
||||
Set the debug mode for package management operations.
|
||||
|
||||
- **Description**: Enables or disables debug output for subsequent package management operations. This function does NOT halt on error and always returns the boolean value it was set to.
|
||||
- **Returns**: `Boolean` - The boolean value that the debug flag was set to.
|
||||
- **Arguments**:
|
||||
- `debug`: `Boolean` - Set to `true` to enable debug output, `false` to disable.
|
||||
|
||||
```rhai
|
||||
print("Enabling package debug output.");
|
||||
os::package_set_debug(true);
|
||||
// Subsequent package operations will print debug info
|
||||
|
||||
print("Disabling package debug output.");
|
||||
os::package_set_debug(false);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `package_platform()`
|
||||
|
||||
Get the current platform name for package management.
|
||||
|
||||
- **Description**: Returns the name of the operating system platform as detected by the package manager logic. This function does NOT halt on error; it returns `"Unknown"` if the platform cannot be determined.
|
||||
- **Returns**: `String` - The platform name, one of `"Ubuntu"`, `"MacOS"`, or `"Unknown"`.
|
||||
- **Arguments**: None.
|
||||
|
||||
```rhai
|
||||
let platform = os::package_platform(); // Does not halt on error
|
||||
print(`Detected package platform: ${platform}`);
|
||||
```
|
223
docs/process/process.md
Normal file
223
docs/process/process.md
Normal file
@@ -0,0 +1,223 @@
|
||||
# Process Module
|
||||
|
||||
The `process` module provides functions for running external commands and managing system processes using a builder pattern for command execution.
|
||||
|
||||
For running commands, you start with the `run()` function which returns a `CommandBuilder` object. You can then chain configuration methods like `silent()`, `ignore_error()`, and `log()` before finally calling the `do()` method to execute the command.
|
||||
|
||||
By default, command execution using the builder (`.do()`) will halt the script execution if the command itself fails (returns a non-zero exit code) or if there's an operating system error preventing the command from running. You can change this behavior with `ignore_error()`.
|
||||
|
||||
Other process management functions (`which`, `kill`, `process_list`, `process_get`) have specific error handling behaviors described below.
|
||||
|
||||
---
|
||||
|
||||
### `CommandResult`
|
||||
|
||||
An object returned by command execution functions (`.do()`) containing the result of the command.
|
||||
|
||||
- **Properties**:
|
||||
- `stdout`: `String` - The standard output of the command.
|
||||
- `stderr`: `String` - The standard error of the command.
|
||||
- `success`: `Boolean` - `true` if the command exited with code 0, `false` otherwise.
|
||||
- `code`: `Integer` - The exit code of the command.
|
||||
|
||||
```rhai
|
||||
let result = run("echo hi").do();
|
||||
print(`Success: ${result.success}, Output: ${result.stdout}`);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `ProcessInfo`
|
||||
|
||||
An object found by process listing/getting functions (`process_list`, `process_get`) containing information about a running process.
|
||||
|
||||
- **Properties**:
|
||||
- `pid`: `Integer` - The process ID.
|
||||
- `name`: `String` - The name of the process executable.
|
||||
- `memory`: `Integer` - The memory usage of the process (unit depends on the operating system, typically KB or bytes).
|
||||
- `cpu`: `Float` - The CPU usage percentage (value and meaning may vary by operating system).
|
||||
|
||||
```rhai
|
||||
let processes = process_list("my_service");
|
||||
if (processes.len() > 0) {
|
||||
let first_proc = processes[0];
|
||||
print(`Process ${first_proc.name} (PID: ${first_proc.pid}) is running.`);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `run(command)`
|
||||
|
||||
Start building a command execution.
|
||||
|
||||
- **Description**: Initializes a `CommandBuilder` for the given command string. This is the entry point to configure and run a process.
|
||||
- **Returns**: `CommandBuilder` - A builder object for configuring the command.
|
||||
- **Arguments**:
|
||||
- `command`: `String` - The command string to execute. Can include arguments and be a simple multiline script.
|
||||
|
||||
```rhai
|
||||
let cmd_builder = run("ls -l");
|
||||
// Now you can chain methods like .silent(), .ignore_error(), .log()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `CommandBuilder:silent()`
|
||||
|
||||
Configure the command to run silently.
|
||||
|
||||
- **Description**: Suppresses real-time standard output and standard error from being printed to the script's console during command execution. The output is still captured in the resulting `CommandResult`.
|
||||
- **Returns**: `CommandBuilder` - Returns `self` for chaining.
|
||||
- **Arguments**: None.
|
||||
|
||||
```rhai
|
||||
print("Running silent command...");
|
||||
run("echo This won\'t show directly").silent().do();
|
||||
print("Silent command finished.");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `CommandBuilder:ignore_error()`
|
||||
|
||||
Configure the command to ignore non-zero exit codes.
|
||||
|
||||
- **Description**: By default, the `do()` method halts script execution if the command returns a non-zero exit code. Calling `ignore_error()` prevents this. The `CommandResult` will still indicate `success: false` and contain the non-zero `code`, allowing the script to handle the command failure explicitly. OS errors preventing the command from running will still cause a halt.
|
||||
- **Returns**: `CommandBuilder` - Returns `self` for chaining.
|
||||
- **Arguments**: None.
|
||||
|
||||
```rhai
|
||||
print("Running command that will fail but not halt...");
|
||||
let result = run("exit 1").ignore_error().do(); // Will not halt
|
||||
if (!result.success) {
|
||||
print(`Command failed as expected with code: ${result.code}`);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `CommandBuilder:log()`
|
||||
|
||||
Configure the command to log the execution details.
|
||||
|
||||
- **Description**: Enables logging of the command string before execution.
|
||||
- **Returns**: `CommandBuilder` - Returns `self` for chaining.
|
||||
- **Arguments**: None.
|
||||
|
||||
```rhai
|
||||
print("Running command with logging...");
|
||||
run("ls /tmp").log().do(); // Will print the "ls /tmp" command before running
|
||||
print("Command finished.");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `CommandBuilder:do()`
|
||||
|
||||
Execute the configured command.
|
||||
|
||||
- **Description**: Runs the command with the options set by the builder methods. Waits for the command to complete and returns the `CommandResult`. This method is the final step in the command execution builder chain. Halts based on the `ignore_error()` setting and OS errors.
|
||||
- **Returns**: `CommandResult` - An object containing the output and status of the command.
|
||||
- **Arguments**: None.
|
||||
|
||||
```rhai
|
||||
print("Running command using builder...");
|
||||
let command_result = run("pwd")
|
||||
.log() // Log the command
|
||||
.silent() // Don't print output live
|
||||
.do(); // Execute and get result (halts on error by default)
|
||||
|
||||
print(`Command output: ${command_result.stdout}`);
|
||||
|
||||
// Example with multiple options
|
||||
let fail_result = run("command_that_does_not_exist")
|
||||
.ignore_error() // Don't halt on non-zero exit (though OS error might still halt)
|
||||
.silent() // Don't print error live
|
||||
.do();
|
||||
|
||||
if (!fail_result.success) {
|
||||
print(`Failed command exited with code: ${fail_result.code} and stderr: ${fail_result.stderr}`);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `which(cmd)`
|
||||
|
||||
Check if a command exists in the system PATH.
|
||||
|
||||
- **Description**: Searches the system's PATH environment variable for the executable `cmd`. This function does NOT halt if the command is not found; it returns an empty string.
|
||||
- **Returns**: `String` - The full path to the command executable if found, otherwise an empty string (`""`).
|
||||
- **Arguments**:
|
||||
- `cmd`: `String` - The name of the command to search for (e.g., `"node"`).
|
||||
|
||||
```rhai
|
||||
let node_path = which("node"); // Does not halt if node is not found
|
||||
if (node_path != "") {
|
||||
print(`Node executable found at: ${node_path}`);
|
||||
} else {
|
||||
print("Node executable not found in PATH.");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `kill(pattern)`
|
||||
|
||||
Kill processes matching a pattern.
|
||||
|
||||
- **Description**: Terminates running processes whose names match the provided `pattern`. Uses platform-specific commands (like `pkill` or equivalent). Halts script execution on error interacting with the system process list or kill command.
|
||||
- **Returns**: `String` - A success message indicating the kill attempt finished.
|
||||
- **Arguments**:
|
||||
- `pattern`: `String` - A pattern to match against process names (e.g., `"nginx"`).
|
||||
|
||||
```rhai
|
||||
print("Attempting to kill processes matching 'my_service'...");
|
||||
// Use with caution!
|
||||
kill("my_service"); // Halts on OS error during kill attempt
|
||||
print("Kill command sent.");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `process_list(pattern)`
|
||||
|
||||
List processes matching a pattern (or all if pattern is empty).
|
||||
|
||||
- **Description**: Lists information about running processes whose names match the provided `pattern`. If `pattern` is an empty string `""`, lists all processes. Halts script execution on error interacting with the system process list. Returns an empty array if no processes match the pattern.
|
||||
- **Returns**: `Array` of `ProcessInfo` - An array of objects, each containing `pid` (Integer), `name` (String), `memory` (Integer), and `cpu` (Float).
|
||||
- **Arguments**:
|
||||
- `pattern`: `String` - A pattern to match against process names, or `""` for all processes.
|
||||
|
||||
```rhai
|
||||
print("Listing processes matching 'bash'...");
|
||||
let bash_processes = process_list("bash"); // Halts on OS error
|
||||
if (bash_processes.len() > 0) {
|
||||
print("Found bash processes:");
|
||||
for proc in bash_processes {
|
||||
print(`- PID: ${proc.pid}, Name: ${proc.name}, CPU: ${proc.cpu}%, Memory: ${proc.memory}`);
|
||||
}
|
||||
} else {
|
||||
print("No bash processes found.");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `process_get(pattern)`
|
||||
|
||||
Get a single process matching the pattern (error if 0 or more than 1 match).
|
||||
|
||||
- **Description**: Finds exactly one running process whose name matches the provided `pattern`. Halts script execution if zero or more than one process matches the pattern, or on error interacting with the system process list.
|
||||
- **Returns**: `ProcessInfo` - An object containing `pid` (Integer), `name` (String), `memory` (Integer), and `cpu` (Float).
|
||||
- **Arguments**:
|
||||
- `pattern`: `String` - A pattern to match against process names, expected to match exactly one process.
|
||||
|
||||
```rhai
|
||||
let expected_service_name = "my_critical_service";
|
||||
print(`Getting process info for '${expected_service_name}'...`);
|
||||
// This will halt if the service isn't running, or if multiple services have this name
|
||||
let service_proc_info = process_get(expected_service_name);
|
||||
print(`Found process: PID ${service_proc_info.pid}, Name: ${service_proc_info.name}`);
|
||||
```
|
Reference in New Issue
Block a user