UPdate.
This commit is contained in:
@@ -0,0 +1,300 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "argparse" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "argparse"}] %}
|
||||
{% set prev_page = {"url": "api/html.html", "title": "html"} %}
|
||||
{% set next_page = {"url": "api/wdantic.html", "title": "wdantic"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>argparse</h1>
|
||||
|
||||
<p>The <code>argparse</code> module provides command-line argument parsing with support for positional arguments, optional flags, type conversion, and help generation.</p>
|
||||
|
||||
<pre><code>import "argparse" for ArgumentParser</code></pre>
|
||||
|
||||
<h2>ArgumentParser Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>ArgumentParser</h3>
|
||||
<p>Command-line argument parser</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructors</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ArgumentParser.new</span>() → <span class="type">ArgumentParser</span>
|
||||
</div>
|
||||
<p>Creates a new argument parser with no description.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ArgumentParser.new</span>(<span class="param">description</span>) → <span class="type">ArgumentParser</span>
|
||||
</div>
|
||||
<p>Creates a new argument parser with a description shown in help.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">description</span> <span class="param-type">(String)</span> - Description of the program</li>
|
||||
</ul>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">prog</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Gets or sets the program name shown in help output.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">description</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Gets or sets the program description.</p>
|
||||
|
||||
<h3>Instance Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">addArgument</span>(<span class="param">name</span>) → <span class="type">ArgumentParser</span>
|
||||
</div>
|
||||
<p>Adds an argument with default options. Returns the parser for chaining.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">name</span> <span class="param-type">(String)</span> - Argument name (positional) or flag (starts with <code>-</code>)</li>
|
||||
</ul>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">addArgument</span>(<span class="param">name</span>, <span class="param">options</span>) → <span class="type">ArgumentParser</span>
|
||||
</div>
|
||||
<p>Adds an argument with specified options.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">name</span> <span class="param-type">(String)</span> - Argument name or flag</li>
|
||||
<li><span class="param-name">options</span> <span class="param-type">(Map)</span> - Configuration options</li>
|
||||
</ul>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">parseArgs</span>() → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Parses arguments from <code>Process.arguments</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">parseArgs</span>(<span class="param">args</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Parses the provided argument list.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">args</span> <span class="param-type">(List)</span> - List of argument strings</li>
|
||||
<li><span class="returns">Returns:</span> Map of argument names to values</li>
|
||||
</ul>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">printHelp</span>()
|
||||
</div>
|
||||
<p>Prints formatted help information to stdout.</p>
|
||||
|
||||
<h2>Argument Options</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Option</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>long</code></td>
|
||||
<td>String</td>
|
||||
<td>Long form of the flag (e.g., <code>--verbose</code>)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>type</code></td>
|
||||
<td>String</td>
|
||||
<td><code>"string"</code>, <code>"int"</code>, <code>"float"</code>, or <code>"bool"</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>default</code></td>
|
||||
<td>any</td>
|
||||
<td>Default value if not provided</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>required</code></td>
|
||||
<td>Bool</td>
|
||||
<td>Whether the argument is required</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>help</code></td>
|
||||
<td>String</td>
|
||||
<td>Help text description</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>choices</code></td>
|
||||
<td>List</td>
|
||||
<td>List of valid values</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>action</code></td>
|
||||
<td>String</td>
|
||||
<td>How to handle the argument</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>nargs</code></td>
|
||||
<td>String/Num</td>
|
||||
<td>Number of values to consume</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>dest</code></td>
|
||||
<td>String</td>
|
||||
<td>Name for the result map key</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Actions</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Action</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>store</code></td>
|
||||
<td>Store the value (default)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>storeTrue</code></td>
|
||||
<td>Store <code>true</code> when flag is present</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>storeFalse</code></td>
|
||||
<td>Store <code>false</code> when flag is present</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>count</code></td>
|
||||
<td>Count occurrences of the flag</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>append</code></td>
|
||||
<td>Append values to a list</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Nargs Values</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Value</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>*</code></td>
|
||||
<td>Zero or more values (returns list)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>+</code></td>
|
||||
<td>One or more values (returns list)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>N</code> (number)</td>
|
||||
<td>Exactly N values (returns list)</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Basic Usage</h3>
|
||||
<pre><code>import "argparse" for ArgumentParser
|
||||
|
||||
var parser = ArgumentParser.new("File processing utility")
|
||||
parser.prog = "myapp"
|
||||
|
||||
parser.addArgument("filename", {"help": "Input file to process"})
|
||||
parser.addArgument("-o", {
|
||||
"long": "--output",
|
||||
"help": "Output file path",
|
||||
"default": "output.txt"
|
||||
})
|
||||
|
||||
var args = parser.parseArgs()
|
||||
System.print("Input: %(args["filename"])")
|
||||
System.print("Output: %(args["output"])")</code></pre>
|
||||
|
||||
<h3>Boolean Flags</h3>
|
||||
<pre><code>import "argparse" for ArgumentParser
|
||||
|
||||
var parser = ArgumentParser.new()
|
||||
parser.addArgument("-v", {
|
||||
"long": "--verbose",
|
||||
"action": "storeTrue",
|
||||
"help": "Enable verbose output"
|
||||
})
|
||||
parser.addArgument("-q", {
|
||||
"long": "--quiet",
|
||||
"action": "storeFalse",
|
||||
"dest": "verbose",
|
||||
"help": "Disable verbose output"
|
||||
})
|
||||
|
||||
var args = parser.parseArgs(["-v"])
|
||||
System.print(args["verbose"]) // true</code></pre>
|
||||
|
||||
<h3>Type Conversion</h3>
|
||||
<pre><code>import "argparse" for ArgumentParser
|
||||
|
||||
var parser = ArgumentParser.new()
|
||||
parser.addArgument("-n", {
|
||||
"long": "--count",
|
||||
"type": "int",
|
||||
"default": 1,
|
||||
"help": "Number of iterations"
|
||||
})
|
||||
parser.addArgument("-t", {
|
||||
"long": "--threshold",
|
||||
"type": "float",
|
||||
"default": 0.5,
|
||||
"help": "Detection threshold"
|
||||
})
|
||||
|
||||
var args = parser.parseArgs(["-n", "10", "-t", "0.75"])
|
||||
System.print(args["count"]) // 10 (Num)
|
||||
System.print(args["threshold"]) // 0.75 (Num)</code></pre>
|
||||
|
||||
<h3>Multiple Values</h3>
|
||||
<pre><code>import "argparse" for ArgumentParser
|
||||
|
||||
var parser = ArgumentParser.new()
|
||||
parser.addArgument("files", {
|
||||
"nargs": "+",
|
||||
"help": "Files to process"
|
||||
})
|
||||
parser.addArgument("-e", {
|
||||
"long": "--exclude",
|
||||
"action": "append",
|
||||
"help": "Patterns to exclude"
|
||||
})
|
||||
|
||||
var args = parser.parseArgs(["file1.txt", "file2.txt", "-e", "*.tmp", "-e", "*.bak"])
|
||||
System.print(args["files"]) // ["file1.txt", "file2.txt"]
|
||||
System.print(args["exclude"]) // ["*.tmp", "*.bak"]</code></pre>
|
||||
|
||||
<h3>Choices</h3>
|
||||
<pre><code>import "argparse" for ArgumentParser
|
||||
|
||||
var parser = ArgumentParser.new()
|
||||
parser.addArgument("-f", {
|
||||
"long": "--format",
|
||||
"choices": ["json", "xml", "csv"],
|
||||
"default": "json",
|
||||
"help": "Output format"
|
||||
})
|
||||
|
||||
var args = parser.parseArgs(["-f", "csv"])
|
||||
System.print(args["format"]) // csv</code></pre>
|
||||
|
||||
<h3>Verbosity Counter</h3>
|
||||
<pre><code>import "argparse" for ArgumentParser
|
||||
|
||||
var parser = ArgumentParser.new()
|
||||
parser.addArgument("-v", {
|
||||
"action": "count",
|
||||
"help": "Increase verbosity"
|
||||
})
|
||||
|
||||
var args = parser.parseArgs(["-v", "-v", "-v"])
|
||||
System.print(args["v"]) // 3</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Argument names starting with <code>-</code> are treated as optional flags. Names without a leading dash are positional arguments. Hyphens in argument names are converted to underscores in the result map.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,178 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "base64" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "base64"}] %}
|
||||
{% set prev_page = {"url": "api/json.html", "title": "json"} %}
|
||||
{% set next_page = {"url": "api/regex.html", "title": "regex"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>base64</h1>
|
||||
|
||||
<p>The <code>base64</code> module provides Base64 encoding and decoding functionality, including URL-safe variants.</p>
|
||||
|
||||
<pre><code>import "base64" for Base64</code></pre>
|
||||
|
||||
<h2>Base64 Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Base64</h3>
|
||||
<p>Base64 encoding and decoding utilities</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Base64.encode</span>(<span class="param">data</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Encodes data to standard Base64.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(String)</span> - Data to encode</li>
|
||||
<li><span class="returns">Returns:</span> Base64-encoded string</li>
|
||||
</ul>
|
||||
<pre><code>var encoded = Base64.encode("Hello, World!")
|
||||
System.print(encoded) // SGVsbG8sIFdvcmxkIQ==</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Base64.decode</span>(<span class="param">data</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Decodes a Base64-encoded string.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(String)</span> - Base64 string to decode</li>
|
||||
<li><span class="returns">Returns:</span> Decoded data as a string</li>
|
||||
</ul>
|
||||
<pre><code>var decoded = Base64.decode("SGVsbG8sIFdvcmxkIQ==")
|
||||
System.print(decoded) // Hello, World!</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Base64.encodeUrl</span>(<span class="param">data</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Encodes data to URL-safe Base64. Replaces <code>+</code> with <code>-</code>, <code>/</code> with <code>_</code>, and removes padding.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(String)</span> - Data to encode</li>
|
||||
<li><span class="returns">Returns:</span> URL-safe Base64 string (no padding)</li>
|
||||
</ul>
|
||||
<pre><code>var encoded = Base64.encodeUrl("Hello, World!")
|
||||
System.print(encoded) // SGVsbG8sIFdvcmxkIQ</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Base64.decodeUrl</span>(<span class="param">data</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Decodes a URL-safe Base64 string. Handles strings with or without padding.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(String)</span> - URL-safe Base64 string to decode</li>
|
||||
<li><span class="returns">Returns:</span> Decoded data as a string</li>
|
||||
</ul>
|
||||
<pre><code>var decoded = Base64.decodeUrl("SGVsbG8sIFdvcmxkIQ")
|
||||
System.print(decoded) // Hello, World!</code></pre>
|
||||
|
||||
<h2>Encoding Comparison</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Method</th>
|
||||
<th>Alphabet</th>
|
||||
<th>Padding</th>
|
||||
<th>Use Case</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>encode</code></td>
|
||||
<td>A-Z, a-z, 0-9, +, /</td>
|
||||
<td>Yes (=)</td>
|
||||
<td>General purpose, email, file storage</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>encodeUrl</code></td>
|
||||
<td>A-Z, a-z, 0-9, -, _</td>
|
||||
<td>No</td>
|
||||
<td>URLs, filenames, JWT tokens</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Basic Encoding and Decoding</h3>
|
||||
<pre><code>import "base64" for Base64
|
||||
|
||||
var original = "The quick brown fox jumps over the lazy dog"
|
||||
|
||||
var encoded = Base64.encode(original)
|
||||
System.print("Encoded: %(encoded)")
|
||||
|
||||
var decoded = Base64.decode(encoded)
|
||||
System.print("Decoded: %(decoded)")
|
||||
System.print("Match: %(original == decoded)")</code></pre>
|
||||
|
||||
<h3>Binary Data Encoding</h3>
|
||||
<pre><code>import "base64" for Base64
|
||||
|
||||
var binaryData = String.fromCodePoint(0) +
|
||||
String.fromCodePoint(1) +
|
||||
String.fromCodePoint(255)
|
||||
|
||||
var encoded = Base64.encode(binaryData)
|
||||
System.print("Encoded binary: %(encoded)")
|
||||
|
||||
var decoded = Base64.decode(encoded)
|
||||
System.print("Byte 0: %(decoded.bytes[0])")
|
||||
System.print("Byte 1: %(decoded.bytes[1])")
|
||||
System.print("Byte 2: %(decoded.bytes[2])")</code></pre>
|
||||
|
||||
<h3>URL-Safe Encoding for Tokens</h3>
|
||||
<pre><code>import "base64" for Base64
|
||||
import "crypto" for Crypto, Hash
|
||||
|
||||
var data = "user:12345"
|
||||
var token = Base64.encodeUrl(data)
|
||||
System.print("Token: %(token)")
|
||||
|
||||
var decodedToken = Base64.decodeUrl(token)
|
||||
System.print("Decoded: %(decodedToken)")</code></pre>
|
||||
|
||||
<h3>HTTP Basic Authentication</h3>
|
||||
<pre><code>import "base64" for Base64
|
||||
import "http" for Http
|
||||
|
||||
var username = "alice"
|
||||
var password = "secret123"
|
||||
var credentials = Base64.encode("%(username):%(password)")
|
||||
|
||||
var headers = {
|
||||
"Authorization": "Basic %(credentials)"
|
||||
}
|
||||
|
||||
var response = Http.get("https://api.example.com/protected", headers)
|
||||
System.print(response.body)</code></pre>
|
||||
|
||||
<h3>Data URI Encoding</h3>
|
||||
<pre><code>import "base64" for Base64
|
||||
import "io" for File
|
||||
|
||||
var imageData = File.read("image.png")
|
||||
var encoded = Base64.encode(imageData)
|
||||
var dataUri = "data:image/png;base64,%(encoded)"
|
||||
System.print(dataUri)</code></pre>
|
||||
|
||||
<h3>JWT-Style Token Parts</h3>
|
||||
<pre><code>import "base64" for Base64
|
||||
import "json" for Json
|
||||
|
||||
var header = {"alg": "HS256", "typ": "JWT"}
|
||||
var payload = {"sub": "1234567890", "name": "John Doe"}
|
||||
|
||||
var headerB64 = Base64.encodeUrl(Json.stringify(header))
|
||||
var payloadB64 = Base64.encodeUrl(Json.stringify(payload))
|
||||
|
||||
System.print("Header: %(headerB64)")
|
||||
System.print("Payload: %(payloadB64)")</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Base64 encoding increases data size by approximately 33%. A 3-byte input becomes 4 Base64 characters.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Use <code>encodeUrl</code> and <code>decodeUrl</code> when the encoded string will be used in URLs, query parameters, or filenames where <code>+</code>, <code>/</code>, and <code>=</code> characters may cause issues.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,226 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "crypto" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "crypto"}] %}
|
||||
{% set prev_page = {"url": "api/jinja.html", "title": "jinja"} %}
|
||||
{% set next_page = {"url": "api/os.html", "title": "os"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>crypto</h1>
|
||||
|
||||
<p>The <code>crypto</code> module provides cryptographic functions including secure random number generation and hash algorithms.</p>
|
||||
|
||||
<pre><code>import "crypto" for Crypto, Hash</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#crypto-class">Crypto Class</a></li>
|
||||
<li><a href="#hash-class">Hash Class</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="crypto-class">Crypto Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Crypto</h3>
|
||||
<p>Cryptographic random number generation</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Crypto.randomBytes</span>(<span class="param">length</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Generates cryptographically secure random bytes.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">length</span> <span class="param-type">(Num)</span> - Number of bytes to generate (must be non-negative)</li>
|
||||
<li><span class="returns">Returns:</span> List of random byte values (0-255)</li>
|
||||
</ul>
|
||||
<pre><code>var bytes = Crypto.randomBytes(16)
|
||||
System.print(bytes) // [142, 55, 201, 89, ...]</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Crypto.randomInt</span>(<span class="param">min</span>, <span class="param">max</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Generates a cryptographically secure random integer in the specified range.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">min</span> <span class="param-type">(Num)</span> - Minimum value (inclusive)</li>
|
||||
<li><span class="param-name">max</span> <span class="param-type">(Num)</span> - Maximum value (exclusive)</li>
|
||||
<li><span class="returns">Returns:</span> Random integer in range [min, max)</li>
|
||||
</ul>
|
||||
<pre><code>var roll = Crypto.randomInt(1, 7) // Dice roll: 1-6
|
||||
System.print(roll)</code></pre>
|
||||
|
||||
<h2 id="hash-class">Hash Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Hash</h3>
|
||||
<p>Cryptographic hash functions</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Hash.md5</span>(<span class="param">data</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Computes the MD5 hash of the input data.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(String|List)</span> - Data to hash (string or list of bytes)</li>
|
||||
<li><span class="returns">Returns:</span> 16-byte hash as a list of bytes</li>
|
||||
</ul>
|
||||
<pre><code>var hash = Hash.md5("Hello, World!")
|
||||
System.print(Hash.toHex(hash)) // 65a8e27d8879283831b664bd8b7f0ad4</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Hash.sha1</span>(<span class="param">data</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Computes the SHA-1 hash of the input data.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(String|List)</span> - Data to hash</li>
|
||||
<li><span class="returns">Returns:</span> 20-byte hash as a list of bytes</li>
|
||||
</ul>
|
||||
<pre><code>var hash = Hash.sha1("Hello, World!")
|
||||
System.print(Hash.toHex(hash)) // 0a0a9f2a6772942557ab5355d76af442f8f65e01</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Hash.sha256</span>(<span class="param">data</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Computes the SHA-256 hash of the input data.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(String|List)</span> - Data to hash</li>
|
||||
<li><span class="returns">Returns:</span> 32-byte hash as a list of bytes</li>
|
||||
</ul>
|
||||
<pre><code>var hash = Hash.sha256("Hello, World!")
|
||||
System.print(Hash.toHex(hash)) // dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Hash.toHex</span>(<span class="param">bytes</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts a list of bytes to a hexadecimal string.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">bytes</span> <span class="param-type">(List)</span> - List of byte values</li>
|
||||
<li><span class="returns">Returns:</span> Lowercase hexadecimal string</li>
|
||||
</ul>
|
||||
<pre><code>var hex = Hash.toHex([0xDE, 0xAD, 0xBE, 0xEF])
|
||||
System.print(hex) // deadbeef</code></pre>
|
||||
|
||||
<h2>Hash Algorithm Comparison</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Algorithm</th>
|
||||
<th>Output Size</th>
|
||||
<th>Security</th>
|
||||
<th>Use Case</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>MD5</td>
|
||||
<td>128 bits (16 bytes)</td>
|
||||
<td>Broken</td>
|
||||
<td>Checksums only (not for security)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>SHA-1</td>
|
||||
<td>160 bits (20 bytes)</td>
|
||||
<td>Weak</td>
|
||||
<td>Legacy compatibility only</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>SHA-256</td>
|
||||
<td>256 bits (32 bytes)</td>
|
||||
<td>Strong</td>
|
||||
<td>Recommended for new applications</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Generating a Random Token</h3>
|
||||
<pre><code>import "crypto" for Crypto, Hash
|
||||
|
||||
var bytes = Crypto.randomBytes(32)
|
||||
var token = Hash.toHex(bytes)
|
||||
System.print("Random token: %(token)")</code></pre>
|
||||
|
||||
<h3>Password Hashing</h3>
|
||||
<pre><code>import "crypto" for Crypto, Hash
|
||||
|
||||
var password = "mysecretpassword"
|
||||
var salt = Crypto.randomBytes(16)
|
||||
var saltHex = Hash.toHex(salt)
|
||||
|
||||
var saltedPassword = saltHex + password
|
||||
var hash = Hash.sha256(saltedPassword)
|
||||
var hashHex = Hash.toHex(hash)
|
||||
|
||||
System.print("Salt: %(saltHex)")
|
||||
System.print("Hash: %(hashHex)")</code></pre>
|
||||
|
||||
<h3>File Checksum</h3>
|
||||
<pre><code>import "crypto" for Hash
|
||||
import "io" for File
|
||||
|
||||
var content = File.read("document.txt")
|
||||
var hash = Hash.sha256(content)
|
||||
System.print("SHA-256: %(Hash.toHex(hash))")</code></pre>
|
||||
|
||||
<h3>Random Selection</h3>
|
||||
<pre><code>import "crypto" for Crypto
|
||||
|
||||
var items = ["apple", "banana", "cherry", "date", "elderberry"]
|
||||
var index = Crypto.randomInt(0, items.count)
|
||||
System.print("Selected: %(items[index])")</code></pre>
|
||||
|
||||
<h3>Generating Random IDs</h3>
|
||||
<pre><code>import "crypto" for Crypto, Hash
|
||||
import "base64" for Base64
|
||||
|
||||
var bytes = Crypto.randomBytes(12)
|
||||
var id = ""
|
||||
for (b in bytes) {
|
||||
id = id + String.fromCodePoint(b)
|
||||
}
|
||||
var encoded = Base64.encodeUrl(id)
|
||||
System.print("Random ID: %(encoded)")</code></pre>
|
||||
|
||||
<h3>Secure Dice Roll</h3>
|
||||
<pre><code>import "crypto" for Crypto
|
||||
|
||||
var numDice = 5
|
||||
var results = []
|
||||
|
||||
for (i in 0...numDice) {
|
||||
results.add(Crypto.randomInt(1, 7))
|
||||
}
|
||||
|
||||
System.print("Dice rolls: %(results)")</code></pre>
|
||||
|
||||
<h3>Comparing Hashes</h3>
|
||||
<pre><code>import "crypto" for Hash
|
||||
|
||||
var original = "Hello, World!"
|
||||
var hash1 = Hash.sha256(original)
|
||||
var hash2 = Hash.sha256(original)
|
||||
var hash3 = Hash.sha256("Different text")
|
||||
|
||||
System.print("Same input, same hash: %(Hash.toHex(hash1) == Hash.toHex(hash2))")
|
||||
System.print("Different input, different hash: %(Hash.toHex(hash1) != Hash.toHex(hash3))")</code></pre>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>MD5 and SHA-1 are cryptographically broken and should not be used for security-sensitive applications. Use SHA-256 for new applications requiring secure hashing.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Hash functions accept both strings and lists of bytes. When a string is provided, it is automatically converted to its byte representation before hashing.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>For password storage, always use a salt (random bytes prepended to the password) before hashing. Store the salt alongside the hash for verification.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,293 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "dataset" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "dataset"}] %}
|
||||
{% set prev_page = {"url": "api/wdantic.html", "title": "wdantic"} %}
|
||||
{% set next_page = {"url": "api/markdown.html", "title": "markdown"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>dataset</h1>
|
||||
|
||||
<p>The <code>dataset</code> module provides a simple ORM-like interface for SQLite databases with automatic schema management. Tables and columns are created automatically as you insert data.</p>
|
||||
|
||||
<pre><code>import "dataset" for Dataset, Table</code></pre>
|
||||
|
||||
<h2>Dataset Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Dataset</h3>
|
||||
<p>Database connection and table access</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructors</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Dataset.open</span>(<span class="param">path</span>) → <span class="type">Dataset</span>
|
||||
</div>
|
||||
<p>Opens or creates a SQLite database file.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">path</span> <span class="param-type">(String)</span> - Path to the database file</li>
|
||||
</ul>
|
||||
<pre><code>var db = Dataset.open("data.db")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Dataset.memory</span>() → <span class="type">Dataset</span>
|
||||
</div>
|
||||
<p>Creates an in-memory database (data is lost when closed).</p>
|
||||
<pre><code>var db = Dataset.memory()</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">db</span> → <span class="type">Database</span>
|
||||
</div>
|
||||
<p>Access to the underlying SQLite database for raw queries.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">tables</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>List of table names in the database.</p>
|
||||
|
||||
<h3>Subscript Access</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">[tableName]</span> → <span class="type">Table</span>
|
||||
</div>
|
||||
<p>Gets a table by name. Creates the table if it does not exist on first insert.</p>
|
||||
<pre><code>var users = db["users"]</code></pre>
|
||||
|
||||
<h3>Instance Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>()
|
||||
</div>
|
||||
<p>Closes the database connection.</p>
|
||||
|
||||
<h2>Table Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Table</h3>
|
||||
<p>CRUD operations on a database table</p>
|
||||
</div>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">name</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The table name.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">columns</span> → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Map of column names to SQL types.</p>
|
||||
|
||||
<h3>Instance Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">insert</span>(<span class="param">record</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Inserts a record and returns it with generated <code>uid</code> and <code>created_at</code>.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">record</span> <span class="param-type">(Map)</span> - Data to insert</li>
|
||||
<li><span class="returns">Returns:</span> Inserted record with uid and created_at</li>
|
||||
</ul>
|
||||
<pre><code>var user = db["users"].insert({
|
||||
"name": "Alice",
|
||||
"email": "alice@example.com"
|
||||
})
|
||||
System.print(user["uid"]) // auto-generated UUID</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">update</span>(<span class="param">record</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Updates a record by uid. Returns number of rows affected.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">record</span> <span class="param-type">(Map)</span> - Must contain <code>uid</code> and fields to update</li>
|
||||
</ul>
|
||||
<pre><code>db["users"].update({
|
||||
"uid": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"name": "Alice Smith"
|
||||
})</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">delete</span>(<span class="param">uid</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Soft deletes a record (sets <code>deleted_at</code> timestamp). Returns true if record was deleted.</p>
|
||||
<pre><code>db["users"].delete("550e8400-e29b-41d4-a716-446655440000")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">hardDelete</span>(<span class="param">uid</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Permanently deletes a record from the database.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">find</span>(<span class="param">conditions</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Finds records matching conditions. Returns list of records (excludes soft-deleted).</p>
|
||||
<pre><code>var admins = db["users"].find({"role": "admin"})</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">findOne</span>(<span class="param">conditions</span>) → <span class="type">Map|null</span>
|
||||
</div>
|
||||
<p>Finds first record matching conditions or null.</p>
|
||||
<pre><code>var user = db["users"].findOne({"email": "alice@example.com"})</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">all</span>() → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns all non-deleted records.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">count</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns count of non-deleted records.</p>
|
||||
|
||||
<h2>Query Operators</h2>
|
||||
|
||||
<p>Use suffixes in condition keys for comparison operators:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Suffix</th>
|
||||
<th>SQL Operator</th>
|
||||
<th>Example</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>__gt</code></td>
|
||||
<td>></td>
|
||||
<td><code>{"age__gt": 18}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>__lt</code></td>
|
||||
<td><</td>
|
||||
<td><code>{"price__lt": 100}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>__gte</code></td>
|
||||
<td>>=</td>
|
||||
<td><code>{"score__gte": 90}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>__lte</code></td>
|
||||
<td><=</td>
|
||||
<td><code>{"score__lte": 100}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>__ne</code></td>
|
||||
<td>!=</td>
|
||||
<td><code>{"status__ne": "deleted"}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>__like</code></td>
|
||||
<td>LIKE</td>
|
||||
<td><code>{"name__like": "A\%"}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>__in</code></td>
|
||||
<td>IN</td>
|
||||
<td><code>{"status__in": ["active", "pending"]}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>__null</code></td>
|
||||
<td>IS NULL / IS NOT NULL</td>
|
||||
<td><code>{"deleted_at__null": true}</code></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Automatic Features</h2>
|
||||
|
||||
<h3>Auto-Generated Fields</h3>
|
||||
<ul>
|
||||
<li><code>uid</code> - UUID v4 primary key (auto-generated if not provided)</li>
|
||||
<li><code>created_at</code> - ISO timestamp (auto-generated on insert)</li>
|
||||
<li><code>deleted_at</code> - ISO timestamp (set by soft delete)</li>
|
||||
</ul>
|
||||
|
||||
<h3>Auto Schema</h3>
|
||||
<ul>
|
||||
<li>Tables are created automatically on first insert</li>
|
||||
<li>Columns are added automatically when new fields appear</li>
|
||||
<li>Type inference: Num → INTEGER/REAL, Bool → INTEGER, Map/List → TEXT (JSON)</li>
|
||||
</ul>
|
||||
|
||||
<h3>JSON Serialization</h3>
|
||||
<p>Maps and Lists are automatically serialized to JSON when stored and deserialized when retrieved.</p>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Basic CRUD</h3>
|
||||
<pre><code>import "dataset" for Dataset
|
||||
|
||||
var db = Dataset.open("app.db")
|
||||
var users = db["users"]
|
||||
|
||||
var user = users.insert({
|
||||
"name": "Alice",
|
||||
"email": "alice@example.com",
|
||||
"settings": {"theme": "dark", "notifications": true}
|
||||
})
|
||||
|
||||
System.print("Created user: %(user["uid"])")
|
||||
|
||||
users.update({
|
||||
"uid": user["uid"],
|
||||
"name": "Alice Smith"
|
||||
})
|
||||
|
||||
var found = users.findOne({"email": "alice@example.com"})
|
||||
System.print("Found: %(found["name"])")
|
||||
|
||||
users.delete(user["uid"])
|
||||
|
||||
db.close()</code></pre>
|
||||
|
||||
<h3>Querying with Operators</h3>
|
||||
<pre><code>import "dataset" for Dataset
|
||||
|
||||
var db = Dataset.open("products.db")
|
||||
var products = db["products"]
|
||||
|
||||
var expensive = products.find({"price__gt": 100})
|
||||
|
||||
var cheap = products.find({"price__lte": 10})
|
||||
|
||||
var search = products.find({"name__like": "\%phone\%"})
|
||||
|
||||
var featured = products.find({
|
||||
"category__in": ["electronics", "gadgets"],
|
||||
"stock__gt": 0
|
||||
})
|
||||
|
||||
db.close()</code></pre>
|
||||
|
||||
<h3>Working with JSON Data</h3>
|
||||
<pre><code>import "dataset" for Dataset
|
||||
|
||||
var db = Dataset.memory()
|
||||
|
||||
db["posts"].insert({
|
||||
"title": "First Post",
|
||||
"tags": ["wren", "programming", "tutorial"],
|
||||
"metadata": {
|
||||
"author": "Alice",
|
||||
"views": 100,
|
||||
"featured": true
|
||||
}
|
||||
})
|
||||
|
||||
var post = db["posts"].findOne({"title": "First Post"})
|
||||
System.print(post["tags"]) // ["wren", "programming", "tutorial"]
|
||||
System.print(post["metadata"]) // {"author": "Alice", ...}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Soft delete is the default behavior. Records are not permanently removed but marked with a <code>deleted_at</code> timestamp. Use <code>hardDelete()</code> for permanent removal. All query methods automatically exclude soft-deleted records.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>The <code>uid</code> field is the primary key. Do not use <code>id</code> as a field name. If you provide a <code>uid</code> during insert, it will be used instead of auto-generating one.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,375 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "datetime" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "datetime"}] %}
|
||||
{% set prev_page = {"url": "api/sqlite.html", "title": "sqlite"} %}
|
||||
{% set next_page = {"url": "api/timer.html", "title": "timer"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>datetime</h1>
|
||||
|
||||
<p>The <code>datetime</code> module provides date and time handling with formatting, arithmetic, and duration support.</p>
|
||||
|
||||
<pre><code>import "datetime" for DateTime, Duration</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#datetime-class">DateTime Class</a></li>
|
||||
<li><a href="#duration-class">Duration Class</a></li>
|
||||
<li><a href="#format-patterns">Format Patterns</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="datetime-class">DateTime Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>DateTime</h3>
|
||||
<p>Date and time representation</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructors</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">DateTime.now</span>() → <span class="type">DateTime</span>
|
||||
</div>
|
||||
<p>Creates a DateTime representing the current local time.</p>
|
||||
<pre><code>var now = DateTime.now()
|
||||
System.print(now) // 2024-01-15T10:30:45</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">DateTime.fromTimestamp</span>(<span class="param">timestamp</span>) → <span class="type">DateTime</span>
|
||||
</div>
|
||||
<p>Creates a DateTime from a Unix timestamp (seconds since epoch).</p>
|
||||
<pre><code>var dt = DateTime.fromTimestamp(1705312245)
|
||||
System.print(dt) // 2024-01-15T10:30:45</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Property</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>timestamp</code></td>
|
||||
<td>Num</td>
|
||||
<td>Unix timestamp (seconds since epoch)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>year</code></td>
|
||||
<td>Num</td>
|
||||
<td>Year (e.g., 2024)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>month</code></td>
|
||||
<td>Num</td>
|
||||
<td>Month (1-12)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>day</code></td>
|
||||
<td>Num</td>
|
||||
<td>Day of month (1-31)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>hour</code></td>
|
||||
<td>Num</td>
|
||||
<td>Hour (0-23)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>minute</code></td>
|
||||
<td>Num</td>
|
||||
<td>Minute (0-59)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>second</code></td>
|
||||
<td>Num</td>
|
||||
<td>Second (0-59)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>dayOfWeek</code></td>
|
||||
<td>Num</td>
|
||||
<td>Day of week (0=Sunday, 6=Saturday)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>dayOfYear</code></td>
|
||||
<td>Num</td>
|
||||
<td>Day of year (1-366)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isDst</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if daylight saving time is in effect</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">format</span>(<span class="param">pattern</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Formats the date/time using strftime-style patterns.</p>
|
||||
<pre><code>var now = DateTime.now()
|
||||
System.print(now.format("\%Y-\%m-\%d")) // 2024-01-15
|
||||
System.print(now.format("\%H:\%M:\%S")) // 10:30:45
|
||||
System.print(now.format("\%A, \%B \%d, \%Y")) // Monday, January 15, 2024</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toIso8601</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the date/time in ISO 8601 format.</p>
|
||||
<pre><code>System.print(DateTime.now().toIso8601) // 2024-01-15T10:30:45</code></pre>
|
||||
|
||||
<h3>Operators</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">+</span>(<span class="param">duration</span>) → <span class="type">DateTime</span>
|
||||
</div>
|
||||
<p>Adds a Duration to the DateTime.</p>
|
||||
<pre><code>var now = DateTime.now()
|
||||
var later = now + Duration.fromHours(2)
|
||||
System.print(later)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">-</span>(<span class="param">other</span>) → <span class="type">DateTime|Duration</span>
|
||||
</div>
|
||||
<p>Subtracts a Duration (returns DateTime) or another DateTime (returns Duration).</p>
|
||||
<pre><code>var now = DateTime.now()
|
||||
var earlier = now - Duration.fromDays(1)
|
||||
|
||||
var start = DateTime.fromTimestamp(1705312245)
|
||||
var end = DateTime.now()
|
||||
var elapsed = end - start // Duration</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">==</span>, <span class="method-name"><</span>, <span class="method-name">></span>, <span class="method-name"><=</span>, <span class="method-name">>=</span>
|
||||
</div>
|
||||
<p>Comparison operators for comparing two DateTimes.</p>
|
||||
|
||||
<h2 id="duration-class">Duration Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Duration</h3>
|
||||
<p>Time duration representation</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructors</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Duration.fromMilliseconds</span>(<span class="param">ms</span>) → <span class="type">Duration</span>
|
||||
</div>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Duration.fromSeconds</span>(<span class="param">s</span>) → <span class="type">Duration</span>
|
||||
</div>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Duration.fromMinutes</span>(<span class="param">m</span>) → <span class="type">Duration</span>
|
||||
</div>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Duration.fromHours</span>(<span class="param">h</span>) → <span class="type">Duration</span>
|
||||
</div>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Duration.fromDays</span>(<span class="param">d</span>) → <span class="type">Duration</span>
|
||||
</div>
|
||||
|
||||
<pre><code>var oneHour = Duration.fromHours(1)
|
||||
var threeMinutes = Duration.fromMinutes(3)
|
||||
var twoAndHalfDays = Duration.fromDays(2.5)</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Property</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>milliseconds</code></td>
|
||||
<td>Num</td>
|
||||
<td>Total milliseconds</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>seconds</code></td>
|
||||
<td>Num</td>
|
||||
<td>Total seconds</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>minutes</code></td>
|
||||
<td>Num</td>
|
||||
<td>Total minutes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>hours</code></td>
|
||||
<td>Num</td>
|
||||
<td>Total hours</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>days</code></td>
|
||||
<td>Num</td>
|
||||
<td>Total days</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Operators</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">+</span>, <span class="method-name">-</span>(<span class="param">duration</span>) → <span class="type">Duration</span>
|
||||
</div>
|
||||
<p>Add or subtract durations.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">*</span>(<span class="param">factor</span>) → <span class="type">Duration</span>
|
||||
</div>
|
||||
<p>Multiply duration by a factor.</p>
|
||||
|
||||
<pre><code>var d1 = Duration.fromHours(2)
|
||||
var d2 = Duration.fromMinutes(30)
|
||||
var total = d1 + d2 // 2.5 hours
|
||||
var doubled = d1 * 2 // 4 hours</code></pre>
|
||||
|
||||
<h2 id="format-patterns">Format Patterns</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Pattern</th>
|
||||
<th>Description</th>
|
||||
<th>Example</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%Y</code></td>
|
||||
<td>4-digit year</td>
|
||||
<td>2024</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%y</code></td>
|
||||
<td>2-digit year</td>
|
||||
<td>24</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%m</code></td>
|
||||
<td>Month (01-12)</td>
|
||||
<td>01</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%d</code></td>
|
||||
<td>Day of month (01-31)</td>
|
||||
<td>15</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%H</code></td>
|
||||
<td>Hour 24h (00-23)</td>
|
||||
<td>14</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%I</code></td>
|
||||
<td>Hour 12h (01-12)</td>
|
||||
<td>02</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%M</code></td>
|
||||
<td>Minute (00-59)</td>
|
||||
<td>30</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%S</code></td>
|
||||
<td>Second (00-59)</td>
|
||||
<td>45</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%p</code></td>
|
||||
<td>AM/PM</td>
|
||||
<td>PM</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%A</code></td>
|
||||
<td>Full weekday name</td>
|
||||
<td>Monday</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%a</code></td>
|
||||
<td>Abbreviated weekday</td>
|
||||
<td>Mon</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%B</code></td>
|
||||
<td>Full month name</td>
|
||||
<td>January</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%b</code></td>
|
||||
<td>Abbreviated month</td>
|
||||
<td>Jan</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%j</code></td>
|
||||
<td>Day of year (001-366)</td>
|
||||
<td>015</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>\%w</code></td>
|
||||
<td>Weekday (0-6, Sun=0)</td>
|
||||
<td>1</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>In Wren strings, <code>%</code> starts string interpolation, so use <code>\%</code> for literal percent signs in format patterns.</p>
|
||||
</div>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Current Date and Time</h3>
|
||||
<pre><code>import "datetime" for DateTime
|
||||
|
||||
var now = DateTime.now()
|
||||
System.print("Year: %(now.year)")
|
||||
System.print("Month: %(now.month)")
|
||||
System.print("Day: %(now.day)")
|
||||
System.print("Time: %(now.hour):%(now.minute):%(now.second)")</code></pre>
|
||||
|
||||
<h3>Formatting Dates</h3>
|
||||
<pre><code>import "datetime" for DateTime
|
||||
|
||||
var now = DateTime.now()
|
||||
System.print(now.format("\%Y-\%m-\%d")) // 2024-01-15
|
||||
System.print(now.format("\%B \%d, \%Y")) // January 15, 2024
|
||||
System.print(now.format("\%I:\%M \%p")) // 02:30 PM</code></pre>
|
||||
|
||||
<h3>Date Arithmetic</h3>
|
||||
<pre><code>import "datetime" for DateTime, Duration
|
||||
|
||||
var now = DateTime.now()
|
||||
var tomorrow = now + Duration.fromDays(1)
|
||||
var nextWeek = now + Duration.fromDays(7)
|
||||
var inTwoHours = now + Duration.fromHours(2)
|
||||
|
||||
System.print("Tomorrow: %(tomorrow.format("\%Y-\%m-\%d"))")
|
||||
System.print("Next week: %(nextWeek.format("\%Y-\%m-\%d"))")</code></pre>
|
||||
|
||||
<h3>Calculating Time Differences</h3>
|
||||
<pre><code>import "datetime" for DateTime
|
||||
|
||||
var start = DateTime.fromTimestamp(1705312245)
|
||||
var end = DateTime.now()
|
||||
var elapsed = end - start
|
||||
|
||||
System.print("Elapsed: %(elapsed.days.floor) days, %(elapsed.hours.floor \% 24) hours")</code></pre>
|
||||
|
||||
<h3>Comparing Dates</h3>
|
||||
<pre><code>import "datetime" for DateTime, Duration
|
||||
|
||||
var now = DateTime.now()
|
||||
var deadline = now + Duration.fromDays(7)
|
||||
|
||||
if (now < deadline) {
|
||||
System.print("Still have time!")
|
||||
}</code></pre>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,161 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "dns" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "dns"}] %}
|
||||
{% set prev_page = {"url": "api/net.html", "title": "net"} %}
|
||||
{% set next_page = {"url": "api/json.html", "title": "json"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>dns</h1>
|
||||
|
||||
<p>The <code>dns</code> module provides DNS resolution functionality for looking up hostnames and resolving them to IP addresses.</p>
|
||||
|
||||
<pre><code>import "dns" for Dns</code></pre>
|
||||
|
||||
<h2>Dns Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Dns</h3>
|
||||
<p>DNS resolution utilities</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Dns.lookup</span>(<span class="param">hostname</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Resolves a hostname to an IP address. Uses the system's default address family preference.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">hostname</span> <span class="param-type">(String)</span> - Hostname to resolve</li>
|
||||
<li><span class="returns">Returns:</span> IP address as a string</li>
|
||||
</ul>
|
||||
<pre><code>var ip = Dns.lookup("example.com")
|
||||
System.print(ip) // 93.184.216.34</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Dns.lookup</span>(<span class="param">hostname</span>, <span class="param">family</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Resolves a hostname to an IP address with a specific address family.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">hostname</span> <span class="param-type">(String)</span> - Hostname to resolve</li>
|
||||
<li><span class="param-name">family</span> <span class="param-type">(Num)</span> - Address family: 0 (any), 4 (IPv4), or 6 (IPv6)</li>
|
||||
<li><span class="returns">Returns:</span> IP address as a string</li>
|
||||
</ul>
|
||||
<pre><code>var ipv4 = Dns.lookup("example.com", 4)
|
||||
System.print(ipv4) // 93.184.216.34
|
||||
|
||||
var ipv6 = Dns.lookup("example.com", 6)
|
||||
System.print(ipv6) // 2606:2800:220:1:248:1893:25c8:1946</code></pre>
|
||||
|
||||
<h3>Address Family Values</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Value</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>0</code></td>
|
||||
<td>Any (system default, typically prefers IPv4)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>4</code></td>
|
||||
<td>IPv4 only</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>6</code></td>
|
||||
<td>IPv6 only</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Basic DNS Lookup</h3>
|
||||
<pre><code>import "dns" for Dns
|
||||
|
||||
var domains = ["example.com", "google.com", "github.com"]
|
||||
|
||||
for (domain in domains) {
|
||||
var ip = Dns.lookup(domain)
|
||||
System.print("%(domain) -> %(ip)")
|
||||
}</code></pre>
|
||||
|
||||
<h3>IPv4 vs IPv6</h3>
|
||||
<pre><code>import "dns" for Dns
|
||||
|
||||
var hostname = "google.com"
|
||||
|
||||
var ipv4 = Dns.lookup(hostname, 4)
|
||||
System.print("IPv4: %(ipv4)")
|
||||
|
||||
var fiber = Fiber.new {
|
||||
return Dns.lookup(hostname, 6)
|
||||
}
|
||||
var result = fiber.try()
|
||||
if (fiber.error != null) {
|
||||
System.print("IPv6: Not available")
|
||||
} else {
|
||||
System.print("IPv6: %(result)")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Using with Socket Connection</h3>
|
||||
<pre><code>import "dns" for Dns
|
||||
import "net" for Socket
|
||||
|
||||
var hostname = "httpbin.org"
|
||||
var ip = Dns.lookup(hostname, 4)
|
||||
System.print("Connecting to %(hostname) (%(ip))")
|
||||
|
||||
var socket = Socket.connect(ip, 80)
|
||||
socket.write("GET /ip HTTP/1.1\r\nHost: %(hostname)\r\nConnection: close\r\n\r\n")
|
||||
|
||||
var response = ""
|
||||
while (true) {
|
||||
var data = socket.read()
|
||||
if (data == null) break
|
||||
response = response + data
|
||||
}
|
||||
|
||||
socket.close()
|
||||
System.print(response)</code></pre>
|
||||
|
||||
<h3>Using with TLS Connection</h3>
|
||||
<pre><code>import "dns" for Dns
|
||||
import "tls" for TlsSocket
|
||||
|
||||
var hostname = "example.com"
|
||||
var ip = Dns.lookup(hostname, 4)
|
||||
|
||||
var socket = TlsSocket.connect(ip, 443, hostname)
|
||||
socket.write("GET / HTTP/1.1\r\nHost: %(hostname)\r\nConnection: close\r\n\r\n")
|
||||
|
||||
var response = socket.read()
|
||||
System.print(response)
|
||||
|
||||
socket.close()</code></pre>
|
||||
|
||||
<h3>Error Handling</h3>
|
||||
<pre><code>import "dns" for Dns
|
||||
|
||||
var fiber = Fiber.new {
|
||||
return Dns.lookup("nonexistent.invalid.domain")
|
||||
}
|
||||
|
||||
var result = fiber.try()
|
||||
if (fiber.error != null) {
|
||||
System.print("DNS lookup failed: %(fiber.error)")
|
||||
} else {
|
||||
System.print("Resolved to: %(result)")
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>DNS lookups are asynchronous operations that use libuv's thread pool. The calling fiber will suspend until the lookup completes.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>The hostname must be a string. Passing a non-string value will abort the fiber with an error. Similarly, the family parameter must be 0, 4, or 6.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,208 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "env" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "env"}] %}
|
||||
{% set prev_page = {"url": "api/dns.html", "title": "dns"} %}
|
||||
{% set next_page = {"url": "api/faker.html", "title": "faker"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>env</h1>
|
||||
|
||||
<p>The <code>env</code> module provides access to environment variables for reading, writing, and deleting values.</p>
|
||||
|
||||
<pre><code>import "env" for Environment</code></pre>
|
||||
|
||||
<h2>Environment Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Environment</h3>
|
||||
<p>Environment variable access</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Environment.get</span>(<span class="param">name</span>) → <span class="type">String|null</span>
|
||||
</div>
|
||||
<p>Gets the value of an environment variable.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">name</span> <span class="param-type">(String)</span> - Name of the environment variable</li>
|
||||
<li><span class="returns">Returns:</span> Value of the variable, or null if not set</li>
|
||||
</ul>
|
||||
<pre><code>var home = Environment.get("HOME")
|
||||
System.print(home) // /home/alice
|
||||
|
||||
var missing = Environment.get("UNDEFINED_VAR")
|
||||
System.print(missing) // null</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Environment.set</span>(<span class="param">name</span>, <span class="param">value</span>)
|
||||
</div>
|
||||
<p>Sets an environment variable.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">name</span> <span class="param-type">(String)</span> - Name of the environment variable</li>
|
||||
<li><span class="param-name">value</span> <span class="param-type">(String)</span> - Value to set</li>
|
||||
</ul>
|
||||
<pre><code>Environment.set("MY_APP_DEBUG", "true")
|
||||
System.print(Environment.get("MY_APP_DEBUG")) // true</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Environment.delete</span>(<span class="param">name</span>)
|
||||
</div>
|
||||
<p>Deletes an environment variable.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">name</span> <span class="param-type">(String)</span> - Name of the environment variable to delete</li>
|
||||
</ul>
|
||||
<pre><code>Environment.delete("MY_APP_DEBUG")
|
||||
System.print(Environment.get("MY_APP_DEBUG")) // null</code></pre>
|
||||
|
||||
<h3>Static Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Environment.all</span> → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Returns a map of all environment variables.</p>
|
||||
<pre><code>var env = Environment.all
|
||||
for (entry in env) {
|
||||
System.print("%(entry.key) = %(entry.value)")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Reading Configuration from Environment</h3>
|
||||
<pre><code>import "env" for Environment
|
||||
|
||||
var host = Environment.get("APP_HOST")
|
||||
if (host == null) host = "localhost"
|
||||
|
||||
var port = Environment.get("APP_PORT")
|
||||
if (port == null) port = "8080"
|
||||
|
||||
var debug = Environment.get("APP_DEBUG") == "true"
|
||||
|
||||
System.print("Starting server on %(host):%(port)")
|
||||
System.print("Debug mode: %(debug)")</code></pre>
|
||||
|
||||
<h3>Default Values Pattern</h3>
|
||||
<pre><code>import "env" for Environment
|
||||
|
||||
class Config {
|
||||
static get(name, defaultValue) {
|
||||
var value = Environment.get(name)
|
||||
return value != null ? value : defaultValue
|
||||
}
|
||||
|
||||
static getInt(name, defaultValue) {
|
||||
var value = Environment.get(name)
|
||||
if (value == null) return defaultValue
|
||||
return Num.fromString(value)
|
||||
}
|
||||
|
||||
static getBool(name, defaultValue) {
|
||||
var value = Environment.get(name)
|
||||
if (value == null) return defaultValue
|
||||
return value == "true" || value == "1"
|
||||
}
|
||||
}
|
||||
|
||||
var timeout = Config.getInt("TIMEOUT", 30)
|
||||
var verbose = Config.getBool("VERBOSE", false)
|
||||
var logFile = Config.get("LOG_FILE", "/var/log/app.log")
|
||||
|
||||
System.print("Timeout: %(timeout)s")
|
||||
System.print("Verbose: %(verbose)")
|
||||
System.print("Log file: %(logFile)")</code></pre>
|
||||
|
||||
<h3>Setting Environment for Subprocesses</h3>
|
||||
<pre><code>import "env" for Environment
|
||||
import "subprocess" for Subprocess
|
||||
|
||||
Environment.set("NODE_ENV", "production")
|
||||
Environment.set("PORT", "3000")
|
||||
|
||||
var result = Subprocess.run("node server.js")
|
||||
System.print(result.stdout)</code></pre>
|
||||
|
||||
<h3>Listing All Environment Variables</h3>
|
||||
<pre><code>import "env" for Environment
|
||||
|
||||
System.print("=== Environment Variables ===")
|
||||
var env = Environment.all
|
||||
var keys = []
|
||||
for (entry in env) {
|
||||
keys.add(entry.key)
|
||||
}
|
||||
keys.sort()
|
||||
|
||||
for (key in keys) {
|
||||
System.print("%(key) = %(env[key])")</code></pre>
|
||||
|
||||
<h3>Checking Required Environment Variables</h3>
|
||||
<pre><code>import "env" for Environment
|
||||
|
||||
var required = ["DATABASE_URL", "API_KEY", "SECRET_KEY"]
|
||||
var missing = []
|
||||
|
||||
for (name in required) {
|
||||
if (Environment.get(name) == null) {
|
||||
missing.add(name)
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.count > 0) {
|
||||
System.print("Missing required environment variables:")
|
||||
for (name in missing) {
|
||||
System.print(" - %(name)")
|
||||
}
|
||||
Fiber.abort("Configuration error")
|
||||
}
|
||||
|
||||
System.print("All required environment variables are set")</code></pre>
|
||||
|
||||
<h3>Temporary Environment Modification</h3>
|
||||
<pre><code>import "env" for Environment
|
||||
|
||||
var originalPath = Environment.get("PATH")
|
||||
|
||||
Environment.set("PATH", "/custom/bin:" + originalPath)
|
||||
System.print("Modified PATH for operations...")
|
||||
|
||||
Environment.set("PATH", originalPath)
|
||||
System.print("Restored original PATH")</code></pre>
|
||||
|
||||
<h3>Database Connection String from Environment</h3>
|
||||
<pre><code>import "env" for Environment
|
||||
|
||||
var dbUrl = Environment.get("DATABASE_URL")
|
||||
if (dbUrl != null) {
|
||||
System.print("Using database: %(dbUrl)")
|
||||
} else {
|
||||
var host = Environment.get("DB_HOST")
|
||||
if (host == null) host = "localhost"
|
||||
var port = Environment.get("DB_PORT")
|
||||
if (port == null) port = "5432"
|
||||
var name = Environment.get("DB_NAME")
|
||||
if (name == null) name = "myapp"
|
||||
var user = Environment.get("DB_USER")
|
||||
if (user == null) user = "postgres"
|
||||
|
||||
dbUrl = "postgres://%(user)@%(host):%(port)/%(name)"
|
||||
System.print("Constructed database URL: %(dbUrl)")
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Environment variables modified with <code>set</code> or <code>delete</code> only affect the current process and any child processes. They do not modify the parent shell's environment.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>For configuration that may vary between environments (development, staging, production), use environment variables. This follows the twelve-factor app methodology.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Never log or print sensitive environment variables like API keys, passwords, or secrets. Use them directly in your application without exposing their values.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,814 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "faker" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "faker"}] %}
|
||||
{% set prev_page = {"url": "api/env.html", "title": "env"} %}
|
||||
{% set next_page = {"url": "api/fswatch.html", "title": "fswatch"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>faker</h1>
|
||||
|
||||
<p>The <code>faker</code> module generates realistic fake data for testing, seeding databases, and prototyping. It provides deterministic output when seeded for reproducible test cases.</p>
|
||||
|
||||
<pre><code>import "faker" for Faker</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#seeding">Seeding & Random</a></li>
|
||||
<li><a href="#format-helpers">Format Helpers</a></li>
|
||||
<li><a href="#person">Person & Names</a></li>
|
||||
<li><a href="#address">Address & Location</a></li>
|
||||
<li><a href="#internet">Internet & Network</a></li>
|
||||
<li><a href="#datetime">Date & Time</a></li>
|
||||
<li><a href="#text">Text & Lorem</a></li>
|
||||
<li><a href="#colors">Colors</a></li>
|
||||
<li><a href="#company">Company & Job</a></li>
|
||||
<li><a href="#commerce">Commerce & Products</a></li>
|
||||
<li><a href="#banking">Banking & Finance</a></li>
|
||||
<li><a href="#files">Files & Hashes</a></li>
|
||||
<li><a href="#utilities">Utilities</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>Faker Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Faker</h3>
|
||||
<p>Generates realistic fake data across many categories</p>
|
||||
</div>
|
||||
|
||||
<h2 id="seeding">Seeding & Random</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.seed</span>(<span class="param">value</span>)
|
||||
</div>
|
||||
<p>Sets the random seed for deterministic output. Use the same seed to generate identical sequences.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">value</span> <span class="param-type">(Num)</span> - Integer seed value</li>
|
||||
</ul>
|
||||
<pre><code>Faker.seed(12345)
|
||||
System.print(Faker.name()) // Always produces the same name with this seed</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.reset</span>()
|
||||
</div>
|
||||
<p>Resets to unseeded mode, using cryptographically random values.</p>
|
||||
<pre><code>Faker.reset()
|
||||
System.print(Faker.name()) // Now produces random names</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.randomElement</span>(<span class="param">list</span>) → <span class="type">Any</span>
|
||||
</div>
|
||||
<p>Returns a random element from a list.</p>
|
||||
<pre><code>var colors = ["red", "green", "blue"]
|
||||
System.print(Faker.randomElement(colors))</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.randomElements</span>(<span class="param">list</span>, <span class="param">count</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns multiple random elements from a list (with possible duplicates).</p>
|
||||
<pre><code>var picks = Faker.randomElements(["a", "b", "c", "d"], 3)
|
||||
System.print(picks) // e.g., ["b", "a", "b"]</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.randomInt</span>(<span class="param">min</span>, <span class="param">max</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random integer between min and max (inclusive).</p>
|
||||
<pre><code>var age = Faker.randomInt(18, 65)
|
||||
System.print(age) // e.g., 42</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.randomFloat</span>(<span class="param">min</span>, <span class="param">max</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random float between min and max.</p>
|
||||
<pre><code>var temp = Faker.randomFloat(20, 30)
|
||||
System.print(temp) // e.g., 24.7831...</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.randomFloat</span>(<span class="param">min</span>, <span class="param">max</span>, <span class="param">precision</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random float with specified decimal precision.</p>
|
||||
<pre><code>var price = Faker.randomFloat(10, 100, 2)
|
||||
System.print(price) // e.g., 47.83</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.boolean</span>() → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns a random boolean. Alias: <code>bool()</code>.</p>
|
||||
<pre><code>var isActive = Faker.boolean()
|
||||
System.print(isActive) // true or false</code></pre>
|
||||
|
||||
<h2 id="format-helpers">Format Helpers</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.numerify</span>(<span class="param">format</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Replaces <code>#</code> characters with random digits.</p>
|
||||
<pre><code>System.print(Faker.numerify("###-###-####")) // e.g., "415-555-2938"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.letterify</span>(<span class="param">format</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Replaces <code>?</code> characters with random lowercase letters.</p>
|
||||
<pre><code>System.print(Faker.letterify("???-????")) // e.g., "abc-defg"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.bothify</span>(<span class="param">format</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Replaces both <code>#</code> with digits and <code>?</code> with letters.</p>
|
||||
<pre><code>System.print(Faker.bothify("??-###")) // e.g., "ab-123"</code></pre>
|
||||
|
||||
<h2 id="person">Person & Names</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.firstName</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random first name. Gender-specific variants: <code>firstNameMale()</code>, <code>firstNameFemale()</code>.</p>
|
||||
<pre><code>System.print(Faker.firstName()) // e.g., "Emily"
|
||||
System.print(Faker.firstNameMale()) // e.g., "James"
|
||||
System.print(Faker.firstNameFemale()) // e.g., "Sarah"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.lastName</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random last name.</p>
|
||||
<pre><code>System.print(Faker.lastName()) // e.g., "Johnson"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.name</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a full name (first + last). Variants: <code>nameMale()</code>, <code>nameFemale()</code>.</p>
|
||||
<pre><code>System.print(Faker.name()) // e.g., "Emily Johnson"
|
||||
System.print(Faker.nameMale()) // e.g., "James Smith"
|
||||
System.print(Faker.nameFemale()) // e.g., "Sarah Williams"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.prefix</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a name prefix (Mr., Mrs., Ms., Miss, Dr.). Alias: <code>namePrefix()</code>.</p>
|
||||
<pre><code>System.print(Faker.prefix()) // e.g., "Dr."</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.suffix</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a name suffix (Jr., Sr., MD, PhD, etc.). Alias: <code>nameSuffix()</code>.</p>
|
||||
<pre><code>System.print(Faker.suffix()) // e.g., "Jr."</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.gender</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns "Male" or "Female". Alias: <code>sex()</code>.</p>
|
||||
<pre><code>System.print(Faker.gender()) // "Male" or "Female"</code></pre>
|
||||
|
||||
<h2 id="address">Address & Location</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.address</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a full US-style address.</p>
|
||||
<pre><code>System.print(Faker.address()) // e.g., "1234 Oak Street, Denver, CO 80201"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.streetAddress</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a street address (number + street name).</p>
|
||||
<pre><code>System.print(Faker.streetAddress()) // e.g., "1234 Oak Street"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.streetName</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a street name with suffix.</p>
|
||||
<pre><code>System.print(Faker.streetName()) // e.g., "Oak Boulevard"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.buildingNumber</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random building number (1-9999).</p>
|
||||
<pre><code>System.print(Faker.buildingNumber()) // e.g., "4521"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.city</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a US city name.</p>
|
||||
<pre><code>System.print(Faker.city()) // e.g., "Portland"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.state</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a US state name. Aliases: <code>stateFull()</code>, <code>stateName()</code>.</p>
|
||||
<pre><code>System.print(Faker.state()) // e.g., "California"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.stateAbbr</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a US state abbreviation.</p>
|
||||
<pre><code>System.print(Faker.stateAbbr()) // e.g., "CA"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.country</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a country name. Alias: <code>countryName()</code>.</p>
|
||||
<pre><code>System.print(Faker.country()) // e.g., "Germany"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.countryCode</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a two-letter country code.</p>
|
||||
<pre><code>System.print(Faker.countryCode()) // e.g., "DE"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.zipCode</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a 5-digit US ZIP code. Alias: <code>postcode()</code>.</p>
|
||||
<pre><code>System.print(Faker.zipCode()) // e.g., "90210"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.latitude</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random latitude (-90 to 90) with 6 decimal places.</p>
|
||||
<pre><code>System.print(Faker.latitude()) // e.g., 40.712776</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.latitude</span>(<span class="param">min</span>, <span class="param">max</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a latitude within a specific range.</p>
|
||||
<pre><code>System.print(Faker.latitude(30, 50)) // e.g., 42.358429</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.longitude</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random longitude (-180 to 180) with 6 decimal places.</p>
|
||||
<pre><code>System.print(Faker.longitude()) // e.g., -74.005974</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.longitude</span>(<span class="param">min</span>, <span class="param">max</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a longitude within a specific range.</p>
|
||||
<pre><code>System.print(Faker.longitude(-125, -65)) // e.g., -87.629799</code></pre>
|
||||
|
||||
<h2 id="internet">Internet & Network</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.email</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random email address.</p>
|
||||
<pre><code>System.print(Faker.email()) // e.g., "john.smith42@gmail.com"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.exampleEmail</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns an email using example.com/org/net domains (safe for testing).</p>
|
||||
<pre><code>System.print(Faker.exampleEmail()) // e.g., "alice_jones@example.org"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.username</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random username in various formats.</p>
|
||||
<pre><code>System.print(Faker.username()) // e.g., "john.smith", "emily_42"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.password</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a 12-character random password.</p>
|
||||
<pre><code>System.print(Faker.password()) // e.g., "aB3$kLm9@pQr"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.password</span>(<span class="param">length</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a password of specified length.</p>
|
||||
<pre><code>System.print(Faker.password(20)) // 20-character password</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.url</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random URL.</p>
|
||||
<pre><code>System.print(Faker.url()) // e.g., "https://smith.io"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.domainName</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a domain name.</p>
|
||||
<pre><code>System.print(Faker.domainName()) // e.g., "johnson.com"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.domainWord</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a domain word (without TLD).</p>
|
||||
<pre><code>System.print(Faker.domainWord()) // e.g., "smith"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.tld</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a top-level domain. Alias: <code>topLevelDomain()</code>.</p>
|
||||
<pre><code>System.print(Faker.tld()) // e.g., "com", "io", "org"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.protocol</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns "http" or "https".</p>
|
||||
<pre><code>System.print(Faker.protocol()) // "http" or "https"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.ipv4</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random IPv4 address.</p>
|
||||
<pre><code>System.print(Faker.ipv4()) // e.g., "192.168.45.123"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.ipv6</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random IPv6 address.</p>
|
||||
<pre><code>System.print(Faker.ipv6()) // e.g., "2001:0db8:85a3:0000:0000:8a2e:0370:7334"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.macAddress</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random MAC address.</p>
|
||||
<pre><code>System.print(Faker.macAddress()) // e.g., "00:1a:2b:3c:4d:5e"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.port</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random port number (1-65535).</p>
|
||||
<pre><code>System.print(Faker.port()) // e.g., 8080</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.hostname</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a hostname with subdomain.</p>
|
||||
<pre><code>System.print(Faker.hostname()) // e.g., "server-42.company.com"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.httpMethod</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random HTTP method.</p>
|
||||
<pre><code>System.print(Faker.httpMethod()) // "GET", "POST", "PUT", etc.</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.httpStatusCode</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a common HTTP status code.</p>
|
||||
<pre><code>System.print(Faker.httpStatusCode()) // 200, 404, 500, etc.</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.userAgent</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a realistic browser user agent string.</p>
|
||||
<pre><code>System.print(Faker.userAgent()) // e.g., "Mozilla/5.0 (Windows NT 10.0..."</code></pre>
|
||||
|
||||
<h2 id="datetime">Date & Time</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.date</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random date within the past 10 years in YYYY-MM-DD format.</p>
|
||||
<pre><code>System.print(Faker.date()) // e.g., "2021-07-15"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.dateTime</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random datetime within the past 10 years in ISO 8601 format.</p>
|
||||
<pre><code>System.print(Faker.dateTime()) // e.g., "2022-03-14T09:26:53Z"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.pastDate</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a date within the past year. Accepts optional years parameter.</p>
|
||||
<pre><code>System.print(Faker.pastDate()) // Within past year
|
||||
System.print(Faker.pastDate(5)) // Within past 5 years</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.futureDate</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a date within the next year. Accepts optional years parameter.</p>
|
||||
<pre><code>System.print(Faker.futureDate()) // Within next year
|
||||
System.print(Faker.futureDate(2)) // Within next 2 years</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.dateBetween</span>(<span class="param">start</span>, <span class="param">end</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random date between two DateTime objects.</p>
|
||||
<pre><code>import "datetime" for DateTime, Duration
|
||||
|
||||
var start = DateTime.now() - Duration.fromDays(30)
|
||||
var end = DateTime.now()
|
||||
System.print(Faker.dateBetween(start, end))</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.dateOfBirth</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a birth date for someone aged 18-80. Accepts optional min/max age.</p>
|
||||
<pre><code>System.print(Faker.dateOfBirth()) // Age 18-80
|
||||
System.print(Faker.dateOfBirth(21, 35)) // Age 21-35</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.year</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random year (1950-2025).</p>
|
||||
<pre><code>System.print(Faker.year()) // e.g., 1987</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.month</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random month number (1-12).</p>
|
||||
<pre><code>System.print(Faker.month()) // e.g., 7</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.monthName</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a month name.</p>
|
||||
<pre><code>System.print(Faker.monthName()) // e.g., "July"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.dayOfWeek</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a day of the week.</p>
|
||||
<pre><code>System.print(Faker.dayOfWeek()) // e.g., "Wednesday"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.dayOfMonth</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random day (1-28).</p>
|
||||
<pre><code>System.print(Faker.dayOfMonth()) // e.g., 15</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.time</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random time in HH:MM:SS format.</p>
|
||||
<pre><code>System.print(Faker.time()) // e.g., "14:32:07"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.hour</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random hour (0-23). Related: <code>minute()</code>, <code>second()</code>, <code>amPm()</code>.</p>
|
||||
<pre><code>System.print(Faker.hour()) // e.g., 14
|
||||
System.print(Faker.minute()) // e.g., 32
|
||||
System.print(Faker.second()) // e.g., 45
|
||||
System.print(Faker.amPm()) // "AM" or "PM"</code></pre>
|
||||
|
||||
<h2 id="text">Text & Lorem</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.word</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random lorem ipsum word.</p>
|
||||
<pre><code>System.print(Faker.word()) // e.g., "consectetur"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.words</span>(<span class="param">count</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns a list of random words.</p>
|
||||
<pre><code>System.print(Faker.words(5)) // ["lorem", "ipsum", "dolor", "sit", "amet"]</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.sentence</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a sentence (5-12 words). Accepts optional word count.</p>
|
||||
<pre><code>System.print(Faker.sentence()) // Random length
|
||||
System.print(Faker.sentence(8)) // Exactly 8 words</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.sentences</span>(<span class="param">count</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns multiple sentences joined with spaces.</p>
|
||||
<pre><code>System.print(Faker.sentences(3)) // Three sentences</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.paragraph</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a paragraph (3-6 sentences). Accepts optional sentence count.</p>
|
||||
<pre><code>System.print(Faker.paragraph()) // Random length
|
||||
System.print(Faker.paragraph(5)) // Exactly 5 sentences</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.paragraphs</span>(<span class="param">count</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns multiple paragraphs separated by double newlines.</p>
|
||||
<pre><code>System.print(Faker.paragraphs(3)) // Three paragraphs</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.text</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns approximately 200 characters of text. Accepts optional max length.</p>
|
||||
<pre><code>System.print(Faker.text()) // ~200 characters
|
||||
System.print(Faker.text(500)) // ~500 characters</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.slug</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a URL-friendly slug (3 words). Accepts optional word count.</p>
|
||||
<pre><code>System.print(Faker.slug()) // e.g., "lorem-ipsum-dolor"
|
||||
System.print(Faker.slug(5)) // e.g., "lorem-ipsum-dolor-sit-amet"</code></pre>
|
||||
|
||||
<h2 id="colors">Colors</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.colorName</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a color name.</p>
|
||||
<pre><code>System.print(Faker.colorName()) // e.g., "Crimson"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.hexColor</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a hex color code.</p>
|
||||
<pre><code>System.print(Faker.hexColor()) // e.g., "#a3c2f0"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.rgbColor</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns an RGB color string. Alias: <code>rgb()</code>.</p>
|
||||
<pre><code>System.print(Faker.rgbColor()) // e.g., "rgb(163, 194, 240)"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.rgbaCssColor</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns an RGBA color string with random alpha.</p>
|
||||
<pre><code>System.print(Faker.rgbaCssColor()) // e.g., "rgba(163, 194, 240, 0.75)"</code></pre>
|
||||
|
||||
<h2 id="company">Company & Job</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.company</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a company name. Alias: <code>companyName()</code>.</p>
|
||||
<pre><code>System.print(Faker.company()) // e.g., "Smith Industries"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.companySuffix</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a company suffix.</p>
|
||||
<pre><code>System.print(Faker.companySuffix()) // e.g., "LLC", "Inc.", "Corp."</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.job</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a job title. Alias: <code>jobTitle()</code>.</p>
|
||||
<pre><code>System.print(Faker.job()) // e.g., "Software Engineer"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.jobDescriptor</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a job level descriptor.</p>
|
||||
<pre><code>System.print(Faker.jobDescriptor()) // e.g., "Senior", "Lead", "Principal"</code></pre>
|
||||
|
||||
<h2 id="commerce">Commerce & Products</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.product</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a product name. Alias: <code>productName()</code>.</p>
|
||||
<pre><code>System.print(Faker.product()) // e.g., "Elegant Steel Chair"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.productCategory</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a product category.</p>
|
||||
<pre><code>System.print(Faker.productCategory()) // e.g., "Electronics"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.price</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a price (1-1000) with 2 decimal places. Accepts optional min/max.</p>
|
||||
<pre><code>System.print(Faker.price()) // e.g., 49.99
|
||||
System.print(Faker.price(10, 50)) // e.g., 24.95</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.currency</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a currency code.</p>
|
||||
<pre><code>System.print(Faker.currency()) // e.g., "USD", "EUR", "GBP"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.currencyName</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a currency name.</p>
|
||||
<pre><code>System.print(Faker.currencyName()) // e.g., "US Dollar"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.currencySymbol</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a currency symbol.</p>
|
||||
<pre><code>System.print(Faker.currencySymbol()) // e.g., "$", "€", "£"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.creditCardType</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a credit card type.</p>
|
||||
<pre><code>System.print(Faker.creditCardType()) // e.g., "Visa", "Mastercard"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.creditCardNumber</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a formatted credit card number.</p>
|
||||
<pre><code>System.print(Faker.creditCardNumber()) // e.g., "4123-4567-8901-234"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.creditCardCVV</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a 3-digit CVV code.</p>
|
||||
<pre><code>System.print(Faker.creditCardCVV()) // e.g., "123"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.creditCardExpiryDate</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns an expiry date in MM/YY format.</p>
|
||||
<pre><code>System.print(Faker.creditCardExpiryDate()) // e.g., "09/27"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.phoneNumber</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a US-format phone number. Alias: <code>phone()</code>.</p>
|
||||
<pre><code>System.print(Faker.phoneNumber()) // e.g., "(415) 555-1234"</code></pre>
|
||||
|
||||
<h2 id="banking">Banking & Finance</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.iban</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns an IBAN (International Bank Account Number).</p>
|
||||
<pre><code>System.print(Faker.iban()) // e.g., "DE89370400440532013000"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.accountNumber</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a 10-digit account number. Accepts optional length.</p>
|
||||
<pre><code>System.print(Faker.accountNumber()) // 10 digits
|
||||
System.print(Faker.accountNumber(12)) // 12 digits</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.routingNumber</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a 9-digit routing number.</p>
|
||||
<pre><code>System.print(Faker.routingNumber()) // e.g., "123456789"</code></pre>
|
||||
|
||||
<h2 id="files">Files & Hashes</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.fileName</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a file name with extension.</p>
|
||||
<pre><code>System.print(Faker.fileName()) // e.g., "document.pdf"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.fileExtension</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a file extension.</p>
|
||||
<pre><code>System.print(Faker.fileExtension()) // e.g., "pdf", "jpg", "txt"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.mimeType</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a MIME type.</p>
|
||||
<pre><code>System.print(Faker.mimeType()) // e.g., "application/json"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.semver</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a semantic version string.</p>
|
||||
<pre><code>System.print(Faker.semver()) // e.g., "2.14.3"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.uuid</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a UUID v4.</p>
|
||||
<pre><code>System.print(Faker.uuid()) // e.g., "550e8400-e29b-41d4-a716-446655440000"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.md5</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns an MD5 hash string.</p>
|
||||
<pre><code>System.print(Faker.md5()) // 32-character hex string</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.sha1</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a SHA-1 hash string.</p>
|
||||
<pre><code>System.print(Faker.sha1()) // 40-character hex string</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.sha256</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a SHA-256 hash string.</p>
|
||||
<pre><code>System.print(Faker.sha256()) // 64-character hex string</code></pre>
|
||||
|
||||
<h2 id="utilities">Utilities</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.digit</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a random digit (0-9). Alias: <code>randomDigit()</code>.</p>
|
||||
<pre><code>System.print(Faker.digit()) // 0-9</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.digits</span>(<span class="param">count</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns a list of random digits.</p>
|
||||
<pre><code>System.print(Faker.digits(4)) // e.g., [1, 4, 7, 2]</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.letter</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a random lowercase letter.</p>
|
||||
<pre><code>System.print(Faker.letter()) // e.g., "k"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.letters</span>(<span class="param">count</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns a string of random lowercase letters.</p>
|
||||
<pre><code>System.print(Faker.letters(6)) // e.g., "xkjmvq"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.shuffle</span>(<span class="param">list</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns a shuffled copy of the list.</p>
|
||||
<pre><code>var nums = [1, 2, 3, 4, 5]
|
||||
System.print(Faker.shuffle(nums)) // e.g., [3, 1, 5, 2, 4]</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.profile</span>() → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Returns a complete user profile with username, name, email, address, phone, job, company, and birthdate.</p>
|
||||
<pre><code>var user = Faker.profile()
|
||||
System.print(user["name"])
|
||||
System.print(user["email"])
|
||||
System.print(user["company"])</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.simpleProfile</span>() → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Returns a basic profile with username, name, email, and address.</p>
|
||||
<pre><code>var user = Faker.simpleProfile()
|
||||
System.print(user["name"])
|
||||
System.print(user["email"])</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Faker.locale</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the current locale (always "en_US").</p>
|
||||
<pre><code>System.print(Faker.locale()) // "en_US"</code></pre>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Seeding for Reproducible Tests</h3>
|
||||
<pre><code>import "faker" for Faker
|
||||
|
||||
Faker.seed(42)
|
||||
|
||||
var user1 = Faker.name()
|
||||
var user2 = Faker.name()
|
||||
|
||||
Faker.seed(42)
|
||||
|
||||
System.print(Faker.name() == user1) // true
|
||||
System.print(Faker.name() == user2) // true</code></pre>
|
||||
|
||||
<h3>Generating Test Users</h3>
|
||||
<pre><code>import "faker" for Faker
|
||||
import "json" for Json
|
||||
|
||||
var users = []
|
||||
for (i in 0...5) {
|
||||
users.add({
|
||||
"id": Faker.uuid(),
|
||||
"name": Faker.name(),
|
||||
"email": Faker.email(),
|
||||
"age": Faker.randomInt(18, 65),
|
||||
"active": Faker.boolean()
|
||||
})
|
||||
}
|
||||
|
||||
System.print(Json.stringify(users, 2))</code></pre>
|
||||
|
||||
<h3>Creating Product Catalog</h3>
|
||||
<pre><code>import "faker" for Faker
|
||||
|
||||
for (i in 0...3) {
|
||||
System.print("Product: %(Faker.product())")
|
||||
System.print("Category: %(Faker.productCategory())")
|
||||
System.print("Price: %(Faker.currencySymbol())%(Faker.price())")
|
||||
System.print("---")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Generating Addresses</h3>
|
||||
<pre><code>import "faker" for Faker
|
||||
|
||||
for (i in 0...3) {
|
||||
System.print(Faker.address())
|
||||
System.print(" Lat: %(Faker.latitude())")
|
||||
System.print(" Lng: %(Faker.longitude())")
|
||||
System.print("")
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>When unseeded, Faker uses cryptographically secure random numbers from the <code>crypto</code> module. When seeded, it uses a deterministic linear congruential generator for reproducibility.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Use seeding in tests to ensure consistent, reproducible test data. Call <code>Faker.reset()</code> to return to random mode for production use.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,255 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "fswatch" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "fswatch"}] %}
|
||||
{% set prev_page = {"url": "api/faker.html", "title": "faker"} %}
|
||||
{% set next_page = {"url": "api/html.html", "title": "html"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>fswatch</h1>
|
||||
|
||||
<p>The <code>fswatch</code> module provides file system watching capabilities, allowing scripts to monitor files and directories for changes in real-time. Built on libuv's filesystem events.</p>
|
||||
|
||||
<pre><code>import "fswatch" for FileWatcher, FsEvent</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#filewatcher-class">FileWatcher Class</a></li>
|
||||
<li><a href="#fsevent-class">FsEvent Class</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="filewatcher-class">FileWatcher Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>FileWatcher</h3>
|
||||
<p>Monitors a file or directory for changes</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructor</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">FileWatcher.new</span>(<span class="param">path</span>) → <span class="type">FileWatcher</span>
|
||||
</div>
|
||||
<p>Creates a new FileWatcher for the specified path. The path can be a file or directory.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">path</span> <span class="param-type">(String)</span> - Path to the file or directory to watch</li>
|
||||
</ul>
|
||||
<pre><code>var watcher = FileWatcher.new("./config.json")
|
||||
var dirWatcher = FileWatcher.new("./src")</code></pre>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">start</span>(<span class="param">callback</span>)
|
||||
</div>
|
||||
<p>Starts watching for changes. The callback function is invoked with an FsEvent whenever a change is detected.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">callback</span> <span class="param-type">(Fn)</span> - Function that receives an FsEvent parameter</li>
|
||||
</ul>
|
||||
<pre><code>watcher.start { |event|
|
||||
System.print("Changed: %(event.filename)")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">stop</span>()
|
||||
</div>
|
||||
<p>Stops watching for changes.</p>
|
||||
<pre><code>watcher.stop()</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isActive</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns true if the watcher is currently active.</p>
|
||||
<pre><code>if (watcher.isActive) {
|
||||
System.print("Watcher is running")
|
||||
}</code></pre>
|
||||
|
||||
<h2 id="fsevent-class">FsEvent Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>FsEvent</h3>
|
||||
<p>Represents a file system change event</p>
|
||||
</div>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">filename</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The name of the file that changed. For directory watchers, this is the relative filename within the directory.</p>
|
||||
<pre><code>System.print("File changed: %(event.filename)")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isRename</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>True if the event is a rename/move operation. This includes file creation and deletion.</p>
|
||||
<pre><code>if (event.isRename) {
|
||||
System.print("File renamed/created/deleted")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isChange</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>True if the event is a content change.</p>
|
||||
<pre><code>if (event.isChange) {
|
||||
System.print("File content modified")
|
||||
}</code></pre>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Watch a Single File</h3>
|
||||
<pre><code>import "fswatch" for FileWatcher
|
||||
|
||||
var watcher = FileWatcher.new("./config.json")
|
||||
|
||||
watcher.start { |event|
|
||||
System.print("Config changed!")
|
||||
System.print(" Rename: %(event.isRename)")
|
||||
System.print(" Change: %(event.isChange)")
|
||||
}
|
||||
|
||||
System.print("Watching config.json for changes...")
|
||||
System.print("Press Ctrl+C to stop")</code></pre>
|
||||
|
||||
<h3>Watch a Directory</h3>
|
||||
<pre><code>import "fswatch" for FileWatcher
|
||||
|
||||
var watcher = FileWatcher.new("./src")
|
||||
|
||||
watcher.start { |event|
|
||||
System.print("[%(event.filename)]")
|
||||
if (event.isRename) {
|
||||
System.print(" Created/Deleted/Renamed")
|
||||
}
|
||||
if (event.isChange) {
|
||||
System.print(" Modified")
|
||||
}
|
||||
}
|
||||
|
||||
System.print("Watching ./src directory...")
|
||||
System.print("Press Ctrl+C to stop")</code></pre>
|
||||
|
||||
<h3>Auto-Reload Configuration</h3>
|
||||
<pre><code>import "fswatch" for FileWatcher
|
||||
import "io" for File
|
||||
import "json" for Json
|
||||
|
||||
var config = {}
|
||||
|
||||
var loadConfig = Fn.new {
|
||||
var content = File.read("config.json")
|
||||
config = Json.parse(content)
|
||||
System.print("Config loaded: %(config)")
|
||||
}
|
||||
|
||||
loadConfig.call()
|
||||
|
||||
var watcher = FileWatcher.new("./config.json")
|
||||
watcher.start { |event|
|
||||
System.print("Config file changed, reloading...")
|
||||
loadConfig.call()
|
||||
}
|
||||
|
||||
System.print("Running with auto-reload...")</code></pre>
|
||||
|
||||
<h3>Build on Change</h3>
|
||||
<pre><code>import "fswatch" for FileWatcher
|
||||
import "subprocess" for Subprocess
|
||||
|
||||
var watcher = FileWatcher.new("./src")
|
||||
|
||||
var build = Fn.new {
|
||||
System.print("Building...")
|
||||
var result = Subprocess.run("make", ["build"])
|
||||
if (result.exitCode == 0) {
|
||||
System.print("Build successful!")
|
||||
} else {
|
||||
System.print("Build failed!")
|
||||
System.print(result.stderr)
|
||||
}
|
||||
}
|
||||
|
||||
watcher.start { |event|
|
||||
if (event.filename.endsWith(".c") || event.filename.endsWith(".h")) {
|
||||
System.print("%(event.filename) changed")
|
||||
build.call()
|
||||
}
|
||||
}
|
||||
|
||||
System.print("Watching for source changes...")</code></pre>
|
||||
|
||||
<h3>Multiple Watchers</h3>
|
||||
<pre><code>import "fswatch" for FileWatcher
|
||||
|
||||
var srcWatcher = FileWatcher.new("./src")
|
||||
var testWatcher = FileWatcher.new("./test")
|
||||
|
||||
srcWatcher.start { |event|
|
||||
System.print("[SRC] %(event.filename)")
|
||||
}
|
||||
|
||||
testWatcher.start { |event|
|
||||
System.print("[TEST] %(event.filename)")
|
||||
}
|
||||
|
||||
System.print("Watching src/ and test/ directories...")</code></pre>
|
||||
|
||||
<h3>Debounced Watcher</h3>
|
||||
<pre><code>import "fswatch" for FileWatcher
|
||||
import "timer" for Timer
|
||||
import "datetime" for DateTime
|
||||
|
||||
var lastChange = null
|
||||
var debounceMs = 500
|
||||
|
||||
var watcher = FileWatcher.new("./src")
|
||||
|
||||
watcher.start { |event|
|
||||
var now = DateTime.now()
|
||||
if (lastChange == null || (now - lastChange).milliseconds > debounceMs) {
|
||||
lastChange = now
|
||||
System.print("Change detected: %(event.filename)")
|
||||
}
|
||||
}
|
||||
|
||||
System.print("Watching with %(debounceMs)ms debounce...")</code></pre>
|
||||
|
||||
<h3>Graceful Shutdown</h3>
|
||||
<pre><code>import "fswatch" for FileWatcher
|
||||
import "signal" for Signal
|
||||
|
||||
var watcher = FileWatcher.new("./data")
|
||||
|
||||
watcher.start { |event|
|
||||
System.print("%(event.filename) changed")
|
||||
}
|
||||
|
||||
Signal.trap(Signal.SIGINT) {
|
||||
System.print("\nStopping watcher...")
|
||||
watcher.stop()
|
||||
System.print("Watcher stopped: %(watcher.isActive)")
|
||||
}
|
||||
|
||||
System.print("Watching ./data (Ctrl+C to stop)")</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>File system event behavior varies by operating system. On some platforms, multiple events may be delivered for a single change, or event types may overlap (both <code>isRename</code> and <code>isChange</code> true).</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>When watching directories, the <code>filename</code> property contains the relative path of the changed file within the watched directory, not the full path.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Watching a large directory tree may consume significant system resources. Consider watching specific subdirectories when possible.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,185 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "html" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "html"}] %}
|
||||
{% set prev_page = {"url": "api/fswatch.html", "title": "fswatch"} %}
|
||||
{% set next_page = {"url": "api/http.html", "title": "http"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>html</h1>
|
||||
|
||||
<p>The <code>html</code> module provides utilities for HTML and URL encoding/decoding, slug generation, and query string handling.</p>
|
||||
|
||||
<pre><code>import "html" for Html</code></pre>
|
||||
|
||||
<h2>Html Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Html</h3>
|
||||
<p>HTML and URL encoding utilities</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Html.urlencode</span>(<span class="param">string</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>URL-encodes a string for use in URLs and query parameters. Spaces become <code>+</code>, special characters become percent-encoded.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">string</span> <span class="param-type">(String)</span> - The string to encode</li>
|
||||
<li><span class="returns">Returns:</span> URL-encoded string</li>
|
||||
</ul>
|
||||
<pre><code>System.print(Html.urlencode("hello world")) // hello+world
|
||||
System.print(Html.urlencode("a=b&c=d")) // a\%3Db\%26c\%3Dd
|
||||
System.print(Html.urlencode("café")) // caf\%C3\%A9</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Html.urldecode</span>(<span class="param">string</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Decodes a URL-encoded string. Converts <code>+</code> to space and decodes percent-encoded characters.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">string</span> <span class="param-type">(String)</span> - The URL-encoded string</li>
|
||||
<li><span class="returns">Returns:</span> Decoded string</li>
|
||||
</ul>
|
||||
<pre><code>System.print(Html.urldecode("hello+world")) // hello world
|
||||
System.print(Html.urldecode("caf\%C3\%A9")) // café</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Html.slugify</span>(<span class="param">string</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts a string to a URL-friendly slug. Lowercase, alphanumeric characters with hyphens.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">string</span> <span class="param-type">(String)</span> - The string to slugify</li>
|
||||
<li><span class="returns">Returns:</span> URL-friendly slug</li>
|
||||
</ul>
|
||||
<pre><code>System.print(Html.slugify("Hello World")) // hello-world
|
||||
System.print(Html.slugify("My Blog Post!")) // my-blog-post
|
||||
System.print(Html.slugify(" Multiple Spaces ")) // multiple-spaces</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Html.quote</span>(<span class="param">string</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Escapes HTML special characters to prevent XSS attacks.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">string</span> <span class="param-type">(String)</span> - The string to escape</li>
|
||||
<li><span class="returns">Returns:</span> HTML-escaped string</li>
|
||||
</ul>
|
||||
<pre><code>System.print(Html.quote("<script>alert('xss')</script>"))
|
||||
// &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;
|
||||
|
||||
System.print(Html.quote("A & B")) // A &amp; B
|
||||
System.print(Html.quote("\"quoted\"")) // &quot;quoted&quot;</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Html.unquote</span>(<span class="param">string</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Unescapes HTML entities back to their original characters.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">string</span> <span class="param-type">(String)</span> - The HTML-escaped string</li>
|
||||
<li><span class="returns">Returns:</span> Unescaped string</li>
|
||||
</ul>
|
||||
<pre><code>System.print(Html.unquote("&lt;div&gt;")) // <div>
|
||||
System.print(Html.unquote("A &amp; B")) // A & B</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Html.encodeParams</span>(<span class="param">params</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Encodes a map of key-value pairs into a URL query string.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">params</span> <span class="param-type">(Map)</span> - Map of parameters to encode</li>
|
||||
<li><span class="returns">Returns:</span> URL-encoded query string</li>
|
||||
</ul>
|
||||
<pre><code>var params = {"name": "John Doe", "age": 30}
|
||||
System.print(Html.encodeParams(params)) // name=John+Doe&age=30
|
||||
|
||||
var search = {"q": "wren lang", "page": 1}
|
||||
System.print(Html.encodeParams(search)) // q=wren+lang&page=1</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Html.decodeParams</span>(<span class="param">string</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Decodes a URL query string into a map of key-value pairs.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">string</span> <span class="param-type">(String)</span> - URL-encoded query string</li>
|
||||
<li><span class="returns">Returns:</span> Map of decoded parameters</li>
|
||||
</ul>
|
||||
<pre><code>var params = Html.decodeParams("name=John+Doe&age=30")
|
||||
System.print(params["name"]) // John Doe
|
||||
System.print(params["age"]) // 30</code></pre>
|
||||
|
||||
<h2>Entity Reference</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Character</th>
|
||||
<th>Entity</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>&</td>
|
||||
<td>&amp;</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><</td>
|
||||
<td>&lt;</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>></td>
|
||||
<td>&gt;</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>"</td>
|
||||
<td>&quot;</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>'</td>
|
||||
<td>&#39;</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Building URLs</h3>
|
||||
<pre><code>import "html" for Html
|
||||
|
||||
var baseUrl = "https://api.example.com/search"
|
||||
var params = {
|
||||
"query": "wren programming",
|
||||
"limit": 10,
|
||||
"offset": 0
|
||||
}
|
||||
|
||||
var url = baseUrl + "?" + Html.encodeParams(params)
|
||||
System.print(url)
|
||||
// https://api.example.com/search?query=wren+programming&limit=10&offset=0</code></pre>
|
||||
|
||||
<h3>Safe HTML Output</h3>
|
||||
<pre><code>import "html" for Html
|
||||
|
||||
var userInput = "<script>alert('xss')</script>"
|
||||
var safeHtml = "<div class=\"comment\">" + Html.quote(userInput) + "</div>"
|
||||
System.print(safeHtml)</code></pre>
|
||||
|
||||
<h3>Generating Slugs for URLs</h3>
|
||||
<pre><code>import "html" for Html
|
||||
|
||||
var title = "How to Build Web Apps with Wren!"
|
||||
var slug = Html.slugify(title)
|
||||
var url = "/blog/" + slug
|
||||
System.print(url) // /blog/how-to-build-web-apps-with-wren</code></pre>
|
||||
|
||||
<h3>Parsing Query Strings</h3>
|
||||
<pre><code>import "html" for Html
|
||||
|
||||
var queryString = "category=books&sort=price&order=asc"
|
||||
var params = Html.decodeParams(queryString)
|
||||
|
||||
for (key in params.keys) {
|
||||
System.print("%(key): %(params[key])")
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Always use <code>Html.quote()</code> when inserting user-provided content into HTML to prevent cross-site scripting (XSS) attacks.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,329 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "http" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "http"}] %}
|
||||
{% set prev_page = {"url": "api/index.html", "title": "API Overview"} %}
|
||||
{% set next_page = {"url": "api/websocket.html", "title": "websocket"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>http</h1>
|
||||
|
||||
<p>The <code>http</code> module provides an HTTP client for making requests to web servers. It supports both HTTP and HTTPS, all common HTTP methods, custom headers, and JSON handling.</p>
|
||||
|
||||
<pre><code>import "http" for Http, HttpResponse, Url</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#http-class">Http Class</a></li>
|
||||
<li><a href="#httpresponse-class">HttpResponse Class</a></li>
|
||||
<li><a href="#url-class">Url Class</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="http-class">Http Class</h2>
|
||||
<p>The main class for making HTTP requests. All methods are static.</p>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Http</h3>
|
||||
<p>Static class for making HTTP requests</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.get</span>(<span class="param">url</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs an HTTP GET request.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">url</span> <span class="param-type">(String)</span> - The URL to request</li>
|
||||
<li><span class="returns">Returns:</span> HttpResponse object</li>
|
||||
</ul>
|
||||
<pre><code>var response = Http.get("https://api.example.com/users")
|
||||
System.print(response.body)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.get</span>(<span class="param">url</span>, <span class="param">headers</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs an HTTP GET request with custom headers.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">url</span> <span class="param-type">(String)</span> - The URL to request</li>
|
||||
<li><span class="param-name">headers</span> <span class="param-type">(Map)</span> - Custom headers to include</li>
|
||||
<li><span class="returns">Returns:</span> HttpResponse object</li>
|
||||
</ul>
|
||||
<pre><code>var headers = {"Authorization": "Bearer token123"}
|
||||
var response = Http.get("https://api.example.com/me", headers)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.post</span>(<span class="param">url</span>, <span class="param">body</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs an HTTP POST request with a body.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">url</span> <span class="param-type">(String)</span> - The URL to post to</li>
|
||||
<li><span class="param-name">body</span> <span class="param-type">(String|Map|List)</span> - Request body. Maps and Lists are JSON-encoded automatically.</li>
|
||||
<li><span class="returns">Returns:</span> HttpResponse object</li>
|
||||
</ul>
|
||||
<pre><code>var data = {"name": "Alice", "email": "alice@example.com"}
|
||||
var response = Http.post("https://api.example.com/users", data)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.post</span>(<span class="param">url</span>, <span class="param">body</span>, <span class="param">headers</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs an HTTP POST request with a body and custom headers.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">url</span> <span class="param-type">(String)</span> - The URL to post to</li>
|
||||
<li><span class="param-name">body</span> <span class="param-type">(String|Map|List)</span> - Request body</li>
|
||||
<li><span class="param-name">headers</span> <span class="param-type">(Map)</span> - Custom headers</li>
|
||||
<li><span class="returns">Returns:</span> HttpResponse object</li>
|
||||
</ul>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.put</span>(<span class="param">url</span>, <span class="param">body</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs an HTTP PUT request.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.put</span>(<span class="param">url</span>, <span class="param">body</span>, <span class="param">headers</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs an HTTP PUT request with custom headers.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.delete</span>(<span class="param">url</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs an HTTP DELETE request.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.delete</span>(<span class="param">url</span>, <span class="param">headers</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs an HTTP DELETE request with custom headers.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.patch</span>(<span class="param">url</span>, <span class="param">body</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs an HTTP PATCH request.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.patch</span>(<span class="param">url</span>, <span class="param">body</span>, <span class="param">headers</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs an HTTP PATCH request with custom headers.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Http.request</span>(<span class="param">url</span>, <span class="param">method</span>, <span class="param">body</span>, <span class="param">headers</span>) → <span class="type">HttpResponse</span>
|
||||
</div>
|
||||
<p>Performs a custom HTTP request with full control over method, body, and headers.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">url</span> <span class="param-type">(String)</span> - The URL to request</li>
|
||||
<li><span class="param-name">method</span> <span class="param-type">(String)</span> - HTTP method (GET, POST, PUT, DELETE, PATCH, etc.)</li>
|
||||
<li><span class="param-name">body</span> <span class="param-type">(String|Map|List|null)</span> - Request body or null</li>
|
||||
<li><span class="param-name">headers</span> <span class="param-type">(Map)</span> - Custom headers</li>
|
||||
<li><span class="returns">Returns:</span> HttpResponse object</li>
|
||||
</ul>
|
||||
<pre><code>var response = Http.request(
|
||||
"https://api.example.com/users/1",
|
||||
"OPTIONS",
|
||||
null,
|
||||
{}
|
||||
)</code></pre>
|
||||
|
||||
<h2 id="httpresponse-class">HttpResponse Class</h2>
|
||||
<p>Represents an HTTP response returned from a request.</p>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>HttpResponse</h3>
|
||||
<p>HTTP response object with status, headers, and body</p>
|
||||
</div>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">statusCode</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The HTTP status code (e.g., 200, 404, 500).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">statusText</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The HTTP status text (e.g., "OK", "Not Found").</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">headers</span> → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>A map of response headers (header name to value).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">body</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The response body as a string.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ok</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>True if the status code is in the 200-299 range.</p>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">header</span>(<span class="param">name</span>) → <span class="type">String|null</span>
|
||||
</div>
|
||||
<p>Gets a header value by name (case-insensitive).</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">name</span> <span class="param-type">(String)</span> - Header name</li>
|
||||
<li><span class="returns">Returns:</span> Header value or null if not found</li>
|
||||
</ul>
|
||||
<pre><code>var contentType = response.header("Content-Type")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">json</span> → <span class="type">Map|List|null</span>
|
||||
</div>
|
||||
<p>Parses the response body as JSON and returns the result.</p>
|
||||
<pre><code>var data = response.json
|
||||
System.print(data["name"])</code></pre>
|
||||
|
||||
<h2 id="url-class">Url Class</h2>
|
||||
<p>Utility class for parsing URLs into their components.</p>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Url</h3>
|
||||
<p>URL parser</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructor</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Url.parse</span>(<span class="param">url</span>) → <span class="type">Url</span>
|
||||
</div>
|
||||
<p>Parses a URL string into its components.</p>
|
||||
<pre><code>var url = Url.parse("https://example.com:8080/path?query=value")
|
||||
System.print(url.scheme) // https
|
||||
System.print(url.host) // example.com
|
||||
System.print(url.port) // 8080
|
||||
System.print(url.path) // /path
|
||||
System.print(url.query) // query=value</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Property</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>scheme</code></td>
|
||||
<td>String</td>
|
||||
<td>URL scheme (http, https)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>host</code></td>
|
||||
<td>String</td>
|
||||
<td>Hostname</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>port</code></td>
|
||||
<td>Num</td>
|
||||
<td>Port number (80 for http, 443 for https by default)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>path</code></td>
|
||||
<td>String</td>
|
||||
<td>URL path</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>query</code></td>
|
||||
<td>String</td>
|
||||
<td>Query string (without leading ?)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fullPath</code></td>
|
||||
<td>String</td>
|
||||
<td>Path with query string</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Simple GET Request</h3>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://httpbin.org/get")
|
||||
System.print("Status: %(response.statusCode)")
|
||||
System.print("Body: %(response.body)")</code></pre>
|
||||
|
||||
<h3>POST with JSON Body</h3>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var data = {
|
||||
"username": "alice",
|
||||
"email": "alice@example.com"
|
||||
}
|
||||
|
||||
var response = Http.post("https://httpbin.org/post", data)
|
||||
|
||||
if (response.ok) {
|
||||
System.print("User created!")
|
||||
System.print(response.json)
|
||||
} else {
|
||||
System.print("Error: %(response.statusCode)")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Custom Headers with Authentication</h3>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var headers = {
|
||||
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIs...",
|
||||
"Accept": "application/json"
|
||||
}
|
||||
|
||||
var response = Http.get("https://api.example.com/me", headers)
|
||||
var user = response.json
|
||||
System.print("Hello, %(user["name"])!")</code></pre>
|
||||
|
||||
<h3>Error Handling</h3>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var fiber = Fiber.new {
|
||||
var response = Http.get("https://invalid-domain.example")
|
||||
return response
|
||||
}
|
||||
|
||||
var result = fiber.try()
|
||||
if (fiber.error) {
|
||||
System.print("Request failed: %(fiber.error)")
|
||||
} else {
|
||||
System.print("Got response: %(result.statusCode)")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Sending Form Data</h3>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var formData = "username=alice&password=secret"
|
||||
var headers = {
|
||||
"Content-Type": "application/x-www-form-urlencoded"
|
||||
}
|
||||
|
||||
var response = Http.post("https://example.com/login", formData, headers)</code></pre>
|
||||
|
||||
<h3>Checking Response Headers</h3>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://example.com")
|
||||
|
||||
System.print("Content-Type: %(response.header("Content-Type"))")
|
||||
System.print("Server: %(response.header("Server"))")
|
||||
|
||||
for (entry in response.headers) {
|
||||
System.print("%(entry.key): %(entry.value)")
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>The HTTP module automatically handles HTTPS by using the TLS module. No additional configuration is needed for HTTPS URLs.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>When posting a Map or List, the module automatically sets <code>Content-Type: application/json</code> and JSON-encodes the body. For other content types, pass a string body and set the Content-Type header explicitly.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,349 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "API Reference" %}
|
||||
{% set breadcrumb = [{"title": "API Reference"}] %}
|
||||
{% set prev_page = {"url": "language/modules.html", "title": "Modules"} %}
|
||||
{% set next_page = {"url": "api/http.html", "title": "http"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>API Reference</h1>
|
||||
|
||||
<p>Wren-CLI provides 32 built-in modules covering networking, file I/O, data processing, system operations, and more. All modules are imported using the <code>import</code> statement.</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
import "io" for File</code></pre>
|
||||
|
||||
<h2>Core Types</h2>
|
||||
<p>Extended methods on built-in types, available without imports.</p>
|
||||
|
||||
<div class="card-grid">
|
||||
<div class="card">
|
||||
<h3><a href="string.html">String</a></h3>
|
||||
<p>Case conversion, character testing, padding, splitting, reversing, and more on all strings.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="number.html">Num</a></h3>
|
||||
<p>Query predicates, hyperbolic functions, base conversion, formatting, GCD/LCM, and more on all numbers.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Networking</h2>
|
||||
<p>Modules for HTTP, WebSocket, and low-level network operations.</p>
|
||||
|
||||
<div class="card-grid">
|
||||
<div class="card">
|
||||
<h3><a href="http.html">http</a></h3>
|
||||
<p>HTTP client for making GET, POST, PUT, DELETE, and PATCH requests. Supports HTTPS.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="websocket.html">websocket</a></h3>
|
||||
<p>WebSocket client and server implementation with full protocol support.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="tls.html">tls</a></h3>
|
||||
<p>TLS/SSL socket wrapper for encrypted connections using OpenSSL.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="net.html">net</a></h3>
|
||||
<p>Low-level TCP sockets and servers for custom network protocols.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="udp.html">udp</a></h3>
|
||||
<p>UDP datagram sockets for connectionless networking.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="dns.html">dns</a></h3>
|
||||
<p>DNS resolution for hostname to IP address lookups.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Data Processing</h2>
|
||||
<p>Modules for parsing, encoding, and transforming data.</p>
|
||||
|
||||
<div class="card-grid">
|
||||
<div class="card">
|
||||
<h3><a href="json.html">json</a></h3>
|
||||
<p>Parse and stringify JSON data with pretty-printing support.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="base64.html">base64</a></h3>
|
||||
<p>Base64 encoding and decoding for binary-to-text conversion.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="regex.html">regex</a></h3>
|
||||
<p>Regular expression matching, replacement, and splitting.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="jinja.html">jinja</a></h3>
|
||||
<p>Jinja2-compatible template engine with filters, inheritance, and macros.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="crypto.html">crypto</a></h3>
|
||||
<p>Cryptographic hashing (MD5, SHA-1, SHA-256) and random byte generation.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="uuid.html">uuid</a></h3>
|
||||
<p>UUID generation and validation with v4 support.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="html.html">html</a></h3>
|
||||
<p>HTML/URL encoding, decoding, slug generation, and query string handling.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="markdown.html">markdown</a></h3>
|
||||
<p>Convert Markdown text to HTML with safe mode support.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>System</h2>
|
||||
<p>Modules for interacting with the operating system and environment.</p>
|
||||
|
||||
<div class="card-grid">
|
||||
<div class="card">
|
||||
<h3><a href="os.html">os</a></h3>
|
||||
<p>Platform information, process details, and command-line arguments.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="env.html">env</a></h3>
|
||||
<p>Read and write environment variables.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="signal.html">signal</a></h3>
|
||||
<p>Handle Unix signals like SIGINT, SIGTERM, and SIGHUP.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="subprocess.html">subprocess</a></h3>
|
||||
<p>Run external commands and capture their output.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="io.html">io</a></h3>
|
||||
<p>File and directory operations, stdin/stdout handling.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="pathlib.html">pathlib</a></h3>
|
||||
<p>Object-oriented filesystem paths with glob, walk, and tree operations.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="sysinfo.html">sysinfo</a></h3>
|
||||
<p>System information: CPU, memory, uptime, and network interfaces.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="fswatch.html">fswatch</a></h3>
|
||||
<p>File system watching for monitoring file and directory changes.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Data & Time</h2>
|
||||
<p>Modules for databases, time, and scheduling.</p>
|
||||
|
||||
<div class="card-grid">
|
||||
<div class="card">
|
||||
<h3><a href="sqlite.html">sqlite</a></h3>
|
||||
<p>SQLite database for persistent data storage with SQL queries.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="datetime.html">datetime</a></h3>
|
||||
<p>Date and time manipulation with formatting and arithmetic.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="timer.html">timer</a></h3>
|
||||
<p>Sleep, timeouts, and interval timers.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="math.html">math</a></h3>
|
||||
<p>Mathematical functions like sqrt, sin, cos, and constants like PI.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="scheduler.html">scheduler</a></h3>
|
||||
<p>Async fiber scheduling for non-blocking I/O operations.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="dataset.html">dataset</a></h3>
|
||||
<p>Simple ORM for SQLite with automatic schema management.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Application Development</h2>
|
||||
<p>Modules for building web applications and command-line tools.</p>
|
||||
|
||||
<div class="card-grid">
|
||||
<div class="card">
|
||||
<h3><a href="web.html">web</a></h3>
|
||||
<p>Web framework with routing, middleware, sessions, and HTTP client.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="argparse.html">argparse</a></h3>
|
||||
<p>Command-line argument parsing with type conversion and help generation.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="wdantic.html">wdantic</a></h3>
|
||||
<p>Data validation with schema definitions and built-in validators.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Module Summary</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Module</th>
|
||||
<th>Main Classes</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="http.html">http</a></td>
|
||||
<td>Http, HttpResponse, Url</td>
|
||||
<td>HTTP/HTTPS client</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="websocket.html">websocket</a></td>
|
||||
<td>WebSocket, WebSocketServer, WebSocketMessage</td>
|
||||
<td>WebSocket protocol</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="tls.html">tls</a></td>
|
||||
<td>TlsSocket</td>
|
||||
<td>TLS/SSL sockets</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="net.html">net</a></td>
|
||||
<td>Socket, Server</td>
|
||||
<td>TCP networking</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="udp.html">udp</a></td>
|
||||
<td>UdpSocket, UdpMessage</td>
|
||||
<td>UDP networking</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="dns.html">dns</a></td>
|
||||
<td>Dns</td>
|
||||
<td>DNS resolution</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="json.html">json</a></td>
|
||||
<td>Json</td>
|
||||
<td>JSON parsing</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="base64.html">base64</a></td>
|
||||
<td>Base64</td>
|
||||
<td>Base64 encoding</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="regex.html">regex</a></td>
|
||||
<td>Regex, Match</td>
|
||||
<td>Regular expressions</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="jinja.html">jinja</a></td>
|
||||
<td>Environment, Template, DictLoader, FileSystemLoader</td>
|
||||
<td>Template engine</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="crypto.html">crypto</a></td>
|
||||
<td>Crypto, Hash</td>
|
||||
<td>Cryptography</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="os.html">os</a></td>
|
||||
<td>Process, Platform</td>
|
||||
<td>OS information</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="env.html">env</a></td>
|
||||
<td>Env</td>
|
||||
<td>Environment variables</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="fswatch.html">fswatch</a></td>
|
||||
<td>FileWatcher, FsEvent</td>
|
||||
<td>File system watching</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="signal.html">signal</a></td>
|
||||
<td>Signal</td>
|
||||
<td>Unix signals</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="subprocess.html">subprocess</a></td>
|
||||
<td>Subprocess</td>
|
||||
<td>External processes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="sysinfo.html">sysinfo</a></td>
|
||||
<td>SysInfo</td>
|
||||
<td>System information</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="sqlite.html">sqlite</a></td>
|
||||
<td>Sqlite</td>
|
||||
<td>SQLite database</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="datetime.html">datetime</a></td>
|
||||
<td>DateTime, Duration</td>
|
||||
<td>Date/time handling</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="timer.html">timer</a></td>
|
||||
<td>Timer, TimerHandle</td>
|
||||
<td>Timers, delays, and intervals</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="io.html">io</a></td>
|
||||
<td>File, Directory, Stdin, Stdout</td>
|
||||
<td>File I/O</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="pathlib.html">pathlib</a></td>
|
||||
<td>Path, PurePath</td>
|
||||
<td>Filesystem paths</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="scheduler.html">scheduler</a></td>
|
||||
<td>Scheduler</td>
|
||||
<td>Async scheduling</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="math.html">math</a></td>
|
||||
<td>Math</td>
|
||||
<td>Math functions</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="uuid.html">uuid</a></td>
|
||||
<td>Uuid</td>
|
||||
<td>UUID generation</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="html.html">html</a></td>
|
||||
<td>Html</td>
|
||||
<td>HTML/URL encoding</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="argparse.html">argparse</a></td>
|
||||
<td>ArgumentParser</td>
|
||||
<td>CLI arguments</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="wdantic.html">wdantic</a></td>
|
||||
<td>Validator, Field, Schema, ValidationResult</td>
|
||||
<td>Data validation</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="dataset.html">dataset</a></td>
|
||||
<td>Dataset, Table</td>
|
||||
<td>Simple ORM</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="markdown.html">markdown</a></td>
|
||||
<td>Markdown</td>
|
||||
<td>Markdown to HTML</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="web.html">web</a></td>
|
||||
<td>Application, Router, Request, Response, View, Session, Client</td>
|
||||
<td>Web framework</td>
|
||||
</tr>
|
||||
</table>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,290 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "io" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "io"}] %}
|
||||
{% set prev_page = {"url": "api/timer.html", "title": "timer"} %}
|
||||
{% set next_page = {"url": "api/pathlib.html", "title": "pathlib"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>io</h1>
|
||||
|
||||
<p>The <code>io</code> module provides file and directory operations, as well as stdin/stdout handling.</p>
|
||||
|
||||
<pre><code>import "io" for File, Directory, Stdin, Stdout, Stat</code></pre>
|
||||
|
||||
<h2>File Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>File</h3>
|
||||
<p>File operations</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">File.read</span>(<span class="param">path</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Reads the entire contents of a file.</p>
|
||||
<pre><code>var content = File.read("config.txt")
|
||||
System.print(content)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">File.write</span>(<span class="param">path</span>, <span class="param">content</span>)
|
||||
</div>
|
||||
<p>Writes content to a file (creates or overwrites).</p>
|
||||
<pre><code>File.write("output.txt", "Hello, World!")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">File.exists</span>(<span class="param">path</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns true if the file exists.</p>
|
||||
<pre><code>if (File.exists("config.txt")) {
|
||||
System.print("Config found")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">File.delete</span>(<span class="param">path</span>)
|
||||
</div>
|
||||
<p>Deletes a file.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">File.size</span>(<span class="param">path</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the size of a file in bytes.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">File.copy</span>(<span class="param">source</span>, <span class="param">dest</span>)
|
||||
</div>
|
||||
<p>Copies a file from source to destination.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">File.rename</span>(<span class="param">oldPath</span>, <span class="param">newPath</span>)
|
||||
</div>
|
||||
<p>Renames a file within the same filesystem.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">File.move</span>(<span class="param">source</span>, <span class="param">dest</span>)
|
||||
</div>
|
||||
<p>Moves a file from source to destination. Uses libuv's async rename operation.</p>
|
||||
<pre><code>File.move("old/location/file.txt", "new/location/file.txt")</code></pre>
|
||||
|
||||
<h2>Directory Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Directory</h3>
|
||||
<p>Directory operations</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Directory.list</span>(<span class="param">path</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Lists the contents of a directory.</p>
|
||||
<pre><code>var files = Directory.list(".")
|
||||
for (file in files) {
|
||||
System.print(file)
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Directory.exists</span>(<span class="param">path</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns true if the directory exists.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Directory.create</span>(<span class="param">path</span>)
|
||||
</div>
|
||||
<p>Creates a directory.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Directory.delete</span>(<span class="param">path</span>)
|
||||
</div>
|
||||
<p>Deletes an empty directory.</p>
|
||||
|
||||
<h2>Stdin Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Stdin</h3>
|
||||
<p>Standard input</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Stdin.readLine</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Reads a line from standard input.</p>
|
||||
<pre><code>System.write("Enter your name: ")
|
||||
var name = Stdin.readLine()
|
||||
System.print("Hello, %(name)!")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Stdin.read</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Reads all available data from stdin.</p>
|
||||
|
||||
<h2>Stdout Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Stdout</h3>
|
||||
<p>Standard output</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Stdout.flush</span>()
|
||||
</div>
|
||||
<p>Flushes the stdout buffer.</p>
|
||||
|
||||
<h2>Stat Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Stat</h3>
|
||||
<p>File metadata and statistics</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Stat.path</span>(<span class="param">path</span>) → <span class="type">Stat</span>
|
||||
</div>
|
||||
<p>Returns a Stat object for the specified path.</p>
|
||||
<pre><code>var stat = Stat.path("/etc/hosts")
|
||||
System.print("Size: %(stat.size) bytes")</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">size</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The size of the file in bytes.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isFile</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>True if the path is a regular file.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isDirectory</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>True if the path is a directory.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">mtime</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The modification time as a Unix timestamp (seconds since epoch).</p>
|
||||
<pre><code>var stat = Stat.path("file.txt")
|
||||
System.print("Modified: %(stat.mtime)")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">atime</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The access time as a Unix timestamp.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ctime</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The change time (inode change) as a Unix timestamp.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">mode</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The file permission mode.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">inode</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The inode number.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">device</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The device ID containing the file.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">linkCount</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The number of hard links to the file.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">user</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The user ID of the file owner.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">group</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The group ID of the file.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">blockSize</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The preferred block size for I/O operations.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">blockCount</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The number of blocks allocated for the file.</p>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Reading and Writing Files</h3>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
var content = File.read("input.txt")
|
||||
var processed = content.replace("old", "new")
|
||||
File.write("output.txt", processed)</code></pre>
|
||||
|
||||
<h3>Working with JSON Files</h3>
|
||||
<pre><code>import "io" for File
|
||||
import "json" for Json
|
||||
|
||||
var config = Json.parse(File.read("config.json"))
|
||||
config["updated"] = true
|
||||
File.write("config.json", Json.stringify(config, 2))</code></pre>
|
||||
|
||||
<h3>Processing Directory Contents</h3>
|
||||
<pre><code>import "io" for File, Directory
|
||||
|
||||
var files = Directory.list("./data")
|
||||
for (file in files) {
|
||||
if (file.endsWith(".txt")) {
|
||||
var path = "./data/%(file)"
|
||||
var size = File.size(path)
|
||||
System.print("%(file): %(size) bytes")
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Interactive Input</h3>
|
||||
<pre><code>import "io" for Stdin
|
||||
|
||||
System.write("Username: ")
|
||||
var username = Stdin.readLine()
|
||||
|
||||
System.write("Age: ")
|
||||
var age = Num.fromString(Stdin.readLine())
|
||||
|
||||
System.print("Hello %(username), you are %(age) years old")</code></pre>
|
||||
|
||||
<h3>File Backup</h3>
|
||||
<pre><code>import "io" for File
|
||||
import "datetime" for DateTime
|
||||
|
||||
var backup = Fn.new { |path|
|
||||
if (!File.exists(path)) return
|
||||
|
||||
var timestamp = DateTime.now().format("\%Y\%m\%d_\%H\%M\%S")
|
||||
var backupPath = "%(path).%(timestamp).bak"
|
||||
File.copy(path, backupPath)
|
||||
System.print("Backed up to %(backupPath)")
|
||||
}
|
||||
|
||||
backup.call("important.txt")</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>File operations are synchronous but use libuv internally for async I/O. The fiber suspends during I/O operations.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,166 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "json" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "json"}] %}
|
||||
{% set prev_page = {"url": "api/dns.html", "title": "dns"} %}
|
||||
{% set next_page = {"url": "api/base64.html", "title": "base64"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>json</h1>
|
||||
|
||||
<p>The <code>json</code> module provides JSON parsing and stringification. It uses the cJSON library for parsing and implements stringify in Wren.</p>
|
||||
|
||||
<pre><code>import "json" for Json</code></pre>
|
||||
|
||||
<h2>Json Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Json</h3>
|
||||
<p>JSON parsing and stringification</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Json.parse</span>(<span class="param">string</span>) → <span class="type">Map|List|String|Num|Bool|null</span>
|
||||
</div>
|
||||
<p>Parses a JSON string and returns the corresponding Wren value.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">string</span> <span class="param-type">(String)</span> - JSON string to parse</li>
|
||||
<li><span class="returns">Returns:</span> Parsed value (Map, List, String, Num, Bool, or null)</li>
|
||||
</ul>
|
||||
<pre><code>var data = Json.parse('{"name": "Alice", "age": 30}')
|
||||
System.print(data["name"]) // Alice
|
||||
System.print(data["age"]) // 30
|
||||
|
||||
var list = Json.parse('[1, 2, 3]')
|
||||
System.print(list[0]) // 1</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Json.stringify</span>(<span class="param">value</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts a Wren value to a JSON string (compact, no whitespace).</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">value</span> <span class="param-type">(any)</span> - Value to stringify</li>
|
||||
<li><span class="returns">Returns:</span> JSON string</li>
|
||||
</ul>
|
||||
<pre><code>var json = Json.stringify({"name": "Alice", "age": 30})
|
||||
System.print(json) // {"name":"Alice","age":30}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Json.stringify</span>(<span class="param">value</span>, <span class="param">indent</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts a Wren value to a formatted JSON string with indentation.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">value</span> <span class="param-type">(any)</span> - Value to stringify</li>
|
||||
<li><span class="param-name">indent</span> <span class="param-type">(Num|String)</span> - Number of spaces or indent string</li>
|
||||
<li><span class="returns">Returns:</span> Formatted JSON string</li>
|
||||
</ul>
|
||||
<pre><code>var json = Json.stringify({"name": "Alice"}, 2)
|
||||
System.print(json)
|
||||
// {
|
||||
// "name": "Alice"
|
||||
// }
|
||||
|
||||
var json2 = Json.stringify({"name": "Bob"}, "\t")
|
||||
// Uses tab for indentation</code></pre>
|
||||
|
||||
<h2>Type Mapping</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<th>JSON Type</th>
|
||||
<th>Wren Type</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>object</td>
|
||||
<td>Map</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>array</td>
|
||||
<td>List</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>string</td>
|
||||
<td>String</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>number</td>
|
||||
<td>Num</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>true/false</td>
|
||||
<td>Bool</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>null</td>
|
||||
<td>null</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Parsing JSON</h3>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var jsonString = '{"users": [{"name": "Alice"}, {"name": "Bob"}]}'
|
||||
var data = Json.parse(jsonString)
|
||||
|
||||
for (user in data["users"]) {
|
||||
System.print("User: %(user["name"])")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Building and Stringifying</h3>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var data = {
|
||||
"name": "Product",
|
||||
"price": 29.99,
|
||||
"tags": ["electronics", "sale"],
|
||||
"inStock": true,
|
||||
"metadata": null
|
||||
}
|
||||
|
||||
System.print(Json.stringify(data, 2))</code></pre>
|
||||
|
||||
<h3>Nested Structures</h3>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var config = {
|
||||
"server": {
|
||||
"host": "localhost",
|
||||
"port": 8080
|
||||
},
|
||||
"database": {
|
||||
"url": "sqlite://data.db"
|
||||
}
|
||||
}
|
||||
|
||||
var json = Json.stringify(config)
|
||||
System.print(json)
|
||||
|
||||
var parsed = Json.parse(json)
|
||||
System.print(parsed["server"]["port"]) // 8080</code></pre>
|
||||
|
||||
<h3>Special Values</h3>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var special = {
|
||||
"infinity": 1/0,
|
||||
"nan": 0/0
|
||||
}
|
||||
|
||||
System.print(Json.stringify(special))
|
||||
// {"infinity":null,"nan":null}
|
||||
// Infinity and NaN are converted to null</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Map keys are converted to strings in JSON output. Non-string keys will have their <code>toString</code> method called.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Invalid JSON strings will cause a runtime error. Use <code>Fiber.try()</code> to catch parsing errors.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,334 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "markdown" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "markdown"}] %}
|
||||
{% set prev_page = {"url": "api/dataset.html", "title": "dataset"} %}
|
||||
{% set next_page = {"url": "api/web.html", "title": "web"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>markdown</h1>
|
||||
|
||||
<p>The <code>markdown</code> module provides bidirectional conversion between Markdown and HTML. It supports common Markdown syntax including headings, emphasis, code blocks, lists, links, and images.</p>
|
||||
|
||||
<pre><code>import "markdown" for Markdown</code></pre>
|
||||
|
||||
<h2>Markdown Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Markdown</h3>
|
||||
<p>Markdown to HTML converter</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Markdown.toHtml</span>(<span class="param">text</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts Markdown text to HTML.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">text</span> <span class="param-type">(String)</span> - Markdown text</li>
|
||||
<li><span class="returns">Returns:</span> HTML string</li>
|
||||
</ul>
|
||||
<pre><code>var html = Markdown.toHtml("# Hello World")
|
||||
System.print(html) // <h1>Hello World</h1></code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Markdown.toHtml</span>(<span class="param">text</span>, <span class="param">options</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts Markdown text to HTML with options.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">text</span> <span class="param-type">(String)</span> - Markdown text</li>
|
||||
<li><span class="param-name">options</span> <span class="param-type">(Map)</span> - Conversion options</li>
|
||||
<li><span class="returns">Returns:</span> HTML string</li>
|
||||
</ul>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Markdown.fromHtml</span>(<span class="param">html</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts HTML to Markdown text.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">html</span> <span class="param-type">(String)</span> - HTML string</li>
|
||||
<li><span class="returns">Returns:</span> Markdown text</li>
|
||||
</ul>
|
||||
<pre><code>var md = Markdown.fromHtml("<h1>Hello World</h1>")
|
||||
System.print(md) // # Hello World</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Markdown.fromHtml</span>(<span class="param">html</span>, <span class="param">options</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts HTML to Markdown text with options.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">html</span> <span class="param-type">(String)</span> - HTML string</li>
|
||||
<li><span class="param-name">options</span> <span class="param-type">(Map)</span> - Conversion options</li>
|
||||
<li><span class="returns">Returns:</span> Markdown text</li>
|
||||
</ul>
|
||||
|
||||
<h2>Options</h2>
|
||||
|
||||
<h3>toHtml Options</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Option</th>
|
||||
<th>Type</th>
|
||||
<th>Default</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>safeMode</code></td>
|
||||
<td>Bool</td>
|
||||
<td><code>false</code></td>
|
||||
<td>Escape HTML in input to prevent XSS</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>fromHtml Options</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Option</th>
|
||||
<th>Type</th>
|
||||
<th>Default</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>stripUnknown</code></td>
|
||||
<td>Bool</td>
|
||||
<td><code>true</code></td>
|
||||
<td>Strip unknown HTML tags, keeping their content</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Supported Syntax</h2>
|
||||
|
||||
<h3>Headings</h3>
|
||||
<pre><code># Heading 1
|
||||
## Heading 2
|
||||
### Heading 3
|
||||
#### Heading 4
|
||||
##### Heading 5
|
||||
###### Heading 6</code></pre>
|
||||
<p>Converts to <code><h1></code> through <code><h6></code> tags.</p>
|
||||
|
||||
<h3>Emphasis</h3>
|
||||
<pre><code>*italic* or _italic_
|
||||
**bold** or __bold__
|
||||
~~strikethrough~~</code></pre>
|
||||
<p>Converts to <code><em></code>, <code><strong></code>, and <code><del></code> tags.</p>
|
||||
|
||||
<h3>Code</h3>
|
||||
<pre><code>Inline `code` here
|
||||
|
||||
```
|
||||
Code block
|
||||
Multiple lines
|
||||
```</code></pre>
|
||||
<p>Inline code uses <code><code></code>, blocks use <code><pre><code></code>.</p>
|
||||
|
||||
<h3>Lists</h3>
|
||||
<pre><code>Unordered:
|
||||
- Item 1
|
||||
- Item 2
|
||||
* Also works
|
||||
+ And this
|
||||
|
||||
Ordered:
|
||||
1. First
|
||||
2. Second
|
||||
3. Third</code></pre>
|
||||
<p>Creates <code><ul></code> and <code><ol></code> with <code><li></code> items.</p>
|
||||
|
||||
<h3>Links and Images</h3>
|
||||
<pre><code>[Link text](https://example.com)
|
||||
</code></pre>
|
||||
<p>Creates <code><a href="..."></code> and <code><img src="..." alt="..."></code>.</p>
|
||||
|
||||
<h3>Blockquotes</h3>
|
||||
<pre><code>> This is a quote
|
||||
> Multiple lines</code></pre>
|
||||
<p>Creates <code><blockquote></code> with <code><p></code> content.</p>
|
||||
|
||||
<h3>Horizontal Rule</h3>
|
||||
<pre><code>---
|
||||
***
|
||||
___</code></pre>
|
||||
<p>Creates <code><hr></code> tag.</p>
|
||||
|
||||
<h3>Paragraphs</h3>
|
||||
<p>Text separated by blank lines becomes <code><p></code> elements.</p>
|
||||
|
||||
<h2>HTML to Markdown Conversions</h2>
|
||||
|
||||
<p>The <code>fromHtml</code> method converts the following HTML elements to Markdown:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>HTML</th>
|
||||
<th>Markdown</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><h1></code> to <code><h6></code></td>
|
||||
<td><code>#</code> to <code>######</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><strong></code>, <code><b></code></td>
|
||||
<td><code>**text**</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><em></code>, <code><i></code></td>
|
||||
<td><code>*text*</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><code></code></td>
|
||||
<td><code>`text`</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><pre><code></code></td>
|
||||
<td>Fenced code block</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><a href="url"></code></td>
|
||||
<td><code>[text](url)</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><img src="url" alt=""></code></td>
|
||||
<td><code></code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><ul><li></code></td>
|
||||
<td><code>- item</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><ol><li></code></td>
|
||||
<td><code>1. item</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><blockquote></code></td>
|
||||
<td><code>> text</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><hr></code></td>
|
||||
<td><code>---</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code><del></code>, <code><s></code></td>
|
||||
<td><code>~~text~~</code></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p>Container tags (<code><div></code>, <code><span></code>, <code><section></code>, etc.) are stripped but their content is preserved. Script and style tags are removed entirely.</p>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Basic Conversion</h3>
|
||||
<pre><code>import "markdown" for Markdown
|
||||
|
||||
var md = "
|
||||
# Welcome
|
||||
|
||||
This is a **Markdown** document with:
|
||||
|
||||
- Lists
|
||||
- *Emphasis*
|
||||
- `Code`
|
||||
|
||||
Visit [Wren](https://wren.io) for more.
|
||||
"
|
||||
|
||||
var html = Markdown.toHtml(md)
|
||||
System.print(html)</code></pre>
|
||||
|
||||
<h3>Safe Mode for User Content</h3>
|
||||
<pre><code>import "markdown" for Markdown
|
||||
|
||||
var userInput = "# Title\n<script>alert('xss')</script>\nContent here."
|
||||
|
||||
var safeHtml = Markdown.toHtml(userInput, {"safeMode": true})
|
||||
System.print(safeHtml)</code></pre>
|
||||
|
||||
<h3>Rendering a Blog Post</h3>
|
||||
<pre><code>import "markdown" for Markdown
|
||||
import "io" for File
|
||||
|
||||
var postContent = File.read("post.md")
|
||||
var html = Markdown.toHtml(postContent)
|
||||
|
||||
var page = "<html>
|
||||
<head><title>Blog</title></head>
|
||||
<body>
|
||||
<article>
|
||||
%(html)
|
||||
</article>
|
||||
</body>
|
||||
</html>"
|
||||
|
||||
File.write("post.html", page)</code></pre>
|
||||
|
||||
<h3>Code Blocks with Language Hints</h3>
|
||||
<pre><code>import "markdown" for Markdown
|
||||
|
||||
var md = "
|
||||
```wren
|
||||
System.print(\"Hello, World!\")
|
||||
```
|
||||
"
|
||||
|
||||
var html = Markdown.toHtml(md)
|
||||
System.print(html)
|
||||
// <pre><code>System.print("Hello, World!")</code></pre></code></pre>
|
||||
|
||||
<h3>Combining with Templates</h3>
|
||||
<pre><code>import "markdown" for Markdown
|
||||
import "jinja" for Environment, DictLoader
|
||||
|
||||
var env = Environment.new(DictLoader.new({
|
||||
"base": "<html><body>{{ content }}</body></html>"
|
||||
}))
|
||||
|
||||
var md = "# Hello\n\nThis is **Markdown**."
|
||||
var content = Markdown.toHtml(md)
|
||||
|
||||
var html = env.getTemplate("base").render({"content": content})
|
||||
System.print(html)</code></pre>
|
||||
|
||||
<h3>Converting HTML to Markdown</h3>
|
||||
<pre><code>import "markdown" for Markdown
|
||||
|
||||
var html = "
|
||||
<html>
|
||||
<body>
|
||||
<h1>Article Title</h1>
|
||||
<p>This is <strong>important</strong> content.</p>
|
||||
<ul>
|
||||
<li>First item</li>
|
||||
<li>Second item</li>
|
||||
</ul>
|
||||
</body>
|
||||
</html>
|
||||
"
|
||||
|
||||
var md = Markdown.fromHtml(html)
|
||||
System.print(md)
|
||||
// # Article Title
|
||||
//
|
||||
// This is **important** content.
|
||||
//
|
||||
// - First item
|
||||
// - Second item</code></pre>
|
||||
|
||||
<h3>Cleaning HTML for Plain Text</h3>
|
||||
<pre><code>import "markdown" for Markdown
|
||||
|
||||
var webContent = "<div><script>alert('xss')</script><p>Safe <b>content</b></p></div>"
|
||||
var clean = Markdown.fromHtml(webContent)
|
||||
System.print(clean) // Safe **content**</code></pre>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>When rendering user-provided Markdown, always use <code>safeMode: true</code> to prevent cross-site scripting (XSS) attacks. Safe mode escapes HTML entities in the input text.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Language identifiers after code fences (e.g., <code>```wren</code>) are currently ignored. The code is rendered without syntax highlighting. Consider using a client-side syntax highlighter like Prism.js or highlight.js for the resulting HTML.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,200 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "math" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "math"}] %}
|
||||
{% set prev_page = {"url": "api/scheduler.html", "title": "scheduler"} %}
|
||||
{% set next_page = {"url": "tutorials/index.html", "title": "Tutorials"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>math</h1>
|
||||
|
||||
<p>The <code>math</code> module provides mathematical functions and constants.</p>
|
||||
|
||||
<pre><code>import "math" for Math</code></pre>
|
||||
|
||||
<h2>Math Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Math</h3>
|
||||
<p>Mathematical functions and constants</p>
|
||||
</div>
|
||||
|
||||
<h3>Constants</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Constant</th>
|
||||
<th>Value</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Math.pi</code></td>
|
||||
<td>3.14159...</td>
|
||||
<td>Pi</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Math.e</code></td>
|
||||
<td>2.71828...</td>
|
||||
<td>Euler's number</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Math.tau</code></td>
|
||||
<td>6.28318...</td>
|
||||
<td>Tau (2 * Pi)</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Basic Functions</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.abs</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the absolute value.</p>
|
||||
<pre><code>Math.abs(-5) // 5
|
||||
Math.abs(3.14) // 3.14</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.min</span>(<span class="param">a</span>, <span class="param">b</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the smaller of two values.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.max</span>(<span class="param">a</span>, <span class="param">b</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the larger of two values.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.clamp</span>(<span class="param">value</span>, <span class="param">min</span>, <span class="param">max</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Clamps a value to a range.</p>
|
||||
<pre><code>Math.clamp(15, 0, 10) // 10
|
||||
Math.clamp(5, 0, 10) // 5
|
||||
Math.clamp(-5, 0, 10) // 0</code></pre>
|
||||
|
||||
<h3>Rounding</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.floor</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Rounds down to the nearest integer.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.ceil</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Rounds up to the nearest integer.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.round</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Rounds to the nearest integer.</p>
|
||||
|
||||
<pre><code>Math.floor(3.7) // 3
|
||||
Math.ceil(3.2) // 4
|
||||
Math.round(3.5) // 4</code></pre>
|
||||
|
||||
<h3>Powers and Roots</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.sqrt</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the square root.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.pow</span>(<span class="param">base</span>, <span class="param">exp</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns base raised to the power of exp.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.exp</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns e raised to the power of x.</p>
|
||||
|
||||
<pre><code>Math.sqrt(16) // 4
|
||||
Math.pow(2, 10) // 1024
|
||||
Math.exp(1) // 2.71828...</code></pre>
|
||||
|
||||
<h3>Logarithms</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.log</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the natural logarithm (base e).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.log10</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the base-10 logarithm.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.log2</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the base-2 logarithm.</p>
|
||||
|
||||
<h3>Trigonometry</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.sin</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the sine (x in radians).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.cos</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the cosine (x in radians).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.tan</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the tangent (x in radians).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.asin</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the arcsine in radians.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.acos</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the arccosine in radians.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.atan</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the arctangent in radians.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Math.atan2</span>(<span class="param">y</span>, <span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the angle in radians between the positive x-axis and the point (x, y).</p>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Distance Calculation</h3>
|
||||
<pre><code>import "math" for Math
|
||||
|
||||
var distance = Fn.new { |x1, y1, x2, y2|
|
||||
var dx = x2 - x1
|
||||
var dy = y2 - y1
|
||||
return Math.sqrt(dx * dx + dy * dy)
|
||||
}
|
||||
|
||||
System.print(distance.call(0, 0, 3, 4)) // 5</code></pre>
|
||||
|
||||
<h3>Degrees to Radians</h3>
|
||||
<pre><code>import "math" for Math
|
||||
|
||||
var toRadians = Fn.new { |degrees| degrees * Math.pi / 180 }
|
||||
var toDegrees = Fn.new { |radians| radians * 180 / Math.pi }
|
||||
|
||||
System.print(Math.sin(toRadians.call(90))) // 1</code></pre>
|
||||
|
||||
<h3>Circle Area</h3>
|
||||
<pre><code>import "math" for Math
|
||||
|
||||
var circleArea = Fn.new { |radius|
|
||||
return Math.pi * radius * radius
|
||||
}
|
||||
|
||||
System.print(circleArea.call(5)) // 78.539...</code></pre>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,240 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "net" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "net"}] %}
|
||||
{% set prev_page = {"url": "api/tls.html", "title": "tls"} %}
|
||||
{% set next_page = {"url": "api/dns.html", "title": "dns"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>net</h1>
|
||||
|
||||
<p>The <code>net</code> module provides low-level TCP socket and server functionality for network programming. All operations are asynchronous using libuv.</p>
|
||||
|
||||
<pre><code>import "net" for Socket, Server</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#socket-class">Socket Class</a></li>
|
||||
<li><a href="#server-class">Server Class</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="socket-class">Socket Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Socket</h3>
|
||||
<p>TCP socket for client connections</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Socket.connect</span>(<span class="param">host</span>, <span class="param">port</span>) → <span class="type">Socket</span>
|
||||
</div>
|
||||
<p>Establishes a TCP connection to a remote server.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">host</span> <span class="param-type">(String)</span> - Hostname or IP address to connect to</li>
|
||||
<li><span class="param-name">port</span> <span class="param-type">(Num)</span> - Port number</li>
|
||||
<li><span class="returns">Returns:</span> Connected Socket instance</li>
|
||||
</ul>
|
||||
<pre><code>var socket = Socket.connect("127.0.0.1", 8080)</code></pre>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">write</span>(<span class="param">data</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Writes data to the socket. Blocks until the data is sent.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(String)</span> - Data to send</li>
|
||||
<li><span class="returns">Returns:</span> Number of bytes written</li>
|
||||
</ul>
|
||||
<pre><code>socket.write("Hello, server!")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">read</span>() → <span class="type">String|null</span>
|
||||
</div>
|
||||
<p>Reads data from the socket. Blocks until data is available. Returns null when the connection is closed by the remote end.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="returns">Returns:</span> Data received as a string, or null if connection closed</li>
|
||||
</ul>
|
||||
<pre><code>var data = socket.read()
|
||||
if (data != null) {
|
||||
System.print("Received: %(data)")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>()
|
||||
</div>
|
||||
<p>Closes the socket connection.</p>
|
||||
<pre><code>socket.close()</code></pre>
|
||||
|
||||
<h2 id="server-class">Server Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Server</h3>
|
||||
<p>TCP server for accepting client connections</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Server.bind</span>(<span class="param">host</span>, <span class="param">port</span>) → <span class="type">Server</span>
|
||||
</div>
|
||||
<p>Creates a TCP server listening on the specified host and port.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">host</span> <span class="param-type">(String)</span> - Host to bind to (e.g., "0.0.0.0" for all interfaces, "127.0.0.1" for localhost only)</li>
|
||||
<li><span class="param-name">port</span> <span class="param-type">(Num)</span> - Port number to listen on</li>
|
||||
<li><span class="returns">Returns:</span> Bound Server instance</li>
|
||||
</ul>
|
||||
<pre><code>var server = Server.bind("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">accept</span>() → <span class="type">Socket|null</span>
|
||||
</div>
|
||||
<p>Accepts an incoming connection. Blocks until a client connects. Returns a Socket instance for the connected client.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="returns">Returns:</span> Socket for the accepted connection</li>
|
||||
</ul>
|
||||
<pre><code>var client = server.accept()
|
||||
System.print("Client connected!")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>()
|
||||
</div>
|
||||
<p>Stops the server and closes the listening socket.</p>
|
||||
<pre><code>server.close()</code></pre>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Simple TCP Client</h3>
|
||||
<pre><code>import "net" for Socket
|
||||
|
||||
var socket = Socket.connect("example.com", 80)
|
||||
|
||||
socket.write("GET / HTTP/1.1\r\n")
|
||||
socket.write("Host: example.com\r\n")
|
||||
socket.write("Connection: close\r\n")
|
||||
socket.write("\r\n")
|
||||
|
||||
var response = ""
|
||||
while (true) {
|
||||
var chunk = socket.read()
|
||||
if (chunk == null) break
|
||||
response = response + chunk
|
||||
}
|
||||
|
||||
socket.close()
|
||||
System.print(response)</code></pre>
|
||||
|
||||
<h3>Echo Server</h3>
|
||||
<pre><code>import "net" for Server
|
||||
|
||||
var server = Server.bind("0.0.0.0", 8080)
|
||||
System.print("Echo server listening on port 8080")
|
||||
|
||||
while (true) {
|
||||
var client = server.accept()
|
||||
System.print("Client connected")
|
||||
|
||||
while (true) {
|
||||
var data = client.read()
|
||||
if (data == null) {
|
||||
System.print("Client disconnected")
|
||||
break
|
||||
}
|
||||
System.print("Received: %(data)")
|
||||
client.write(data)
|
||||
}
|
||||
|
||||
client.close()
|
||||
}</code></pre>
|
||||
|
||||
<h3>Line-Based Protocol Server</h3>
|
||||
<pre><code>import "net" for Server
|
||||
|
||||
var server = Server.bind("127.0.0.1", 9000)
|
||||
System.print("Chat server on port 9000")
|
||||
|
||||
while (true) {
|
||||
var client = server.accept()
|
||||
client.write("Welcome! Type messages and press Enter.\n")
|
||||
|
||||
var buffer = ""
|
||||
while (true) {
|
||||
var data = client.read()
|
||||
if (data == null) break
|
||||
|
||||
buffer = buffer + data
|
||||
while (buffer.contains("\n")) {
|
||||
var lineEnd = buffer.indexOf("\n")
|
||||
var line = buffer[0...lineEnd]
|
||||
buffer = buffer[lineEnd + 1..-1]
|
||||
|
||||
if (line == "quit") {
|
||||
client.write("Goodbye!\n")
|
||||
client.close()
|
||||
break
|
||||
}
|
||||
|
||||
client.write("You said: %(line)\n")
|
||||
}
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Connecting with DNS Resolution</h3>
|
||||
<pre><code>import "net" for Socket
|
||||
import "dns" for Dns
|
||||
|
||||
var hostname = "httpbin.org"
|
||||
var ip = Dns.lookup(hostname)
|
||||
System.print("Resolved %(hostname) to %(ip)")
|
||||
|
||||
var socket = Socket.connect(ip, 80)
|
||||
socket.write("GET /ip HTTP/1.1\r\nHost: %(hostname)\r\nConnection: close\r\n\r\n")
|
||||
|
||||
var response = ""
|
||||
while (true) {
|
||||
var data = socket.read()
|
||||
if (data == null) break
|
||||
response = response + data
|
||||
}
|
||||
|
||||
socket.close()
|
||||
System.print(response)</code></pre>
|
||||
|
||||
<h3>Simple Request-Response Client</h3>
|
||||
<pre><code>import "net" for Socket
|
||||
|
||||
var socket = Socket.connect("127.0.0.1", 8080)
|
||||
|
||||
socket.write("PING\n")
|
||||
var response = socket.read()
|
||||
System.print("Server responded: %(response)")
|
||||
|
||||
socket.write("ECHO Hello World\n")
|
||||
response = socket.read()
|
||||
System.print("Server responded: %(response)")
|
||||
|
||||
socket.close()</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>The Socket class uses TCP, which is a stream-based protocol. Data may arrive in chunks that do not correspond to message boundaries. For protocols that require message framing, implement appropriate buffering and parsing logic.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>For secure connections, use the <code>tls</code> module's TlsSocket class instead of Socket. For HTTP/HTTPS requests, the higher-level <code>http</code> module handles protocol details automatically.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Both host and port arguments are validated. Providing a non-string host or non-number port will abort the fiber with an error message.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,401 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Num" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "Num"}] %}
|
||||
{% set prev_page = {"url": "api/string.html", "title": "String"} %}
|
||||
{% set next_page = {"url": "api/http.html", "title": "http"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Num</h1>
|
||||
|
||||
<p>The <code>Num</code> class is the core numeric type in Wren. All numbers are double-precision floating point. The class provides arithmetic, trigonometric, bitwise, rounding, query, conversion, and formatting methods.</p>
|
||||
|
||||
<h2>Static Constants</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Num.pi</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The ratio of a circle's circumference to its diameter (3.14159...).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Num.tau</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Two times pi (6.28318...).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Num.e</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Euler's number (2.71828...).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Num.infinity</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Positive infinity.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Num.nan</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Not-a-number value.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Num.largest</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The largest representable double value.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Num.smallest</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The smallest positive representable double value.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Num.maxSafeInteger</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The largest integer representable without loss of precision (9007199254740991).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Num.minSafeInteger</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The smallest integer representable without loss of precision (-9007199254740991).</p>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Num.fromString</span>(<span class="param">string</span>) → <span class="type">Num|null</span>
|
||||
</div>
|
||||
<p>Parses a string as a number. Returns <code>null</code> if the string is not a valid number.</p>
|
||||
<pre><code>Num.fromString("42") // 42
|
||||
Num.fromString("3.14") // 3.14
|
||||
Num.fromString("nope") // null</code></pre>
|
||||
|
||||
<h2>Query Methods</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isInteger</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the number is an integer (has no fractional part).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isNan</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the number is NaN.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isInfinity</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the number is positive or negative infinity.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isFinite</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the number is finite (not infinity and not NaN).</p>
|
||||
<pre><code>42.isFinite // true
|
||||
(1/0).isFinite // false
|
||||
(0/0).isFinite // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isZero</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the number equals zero.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isPositive</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the number is strictly greater than zero.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isNegative</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the number is strictly less than zero.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isEven</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the number is an even integer.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isOdd</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the number is an odd integer.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isBetween</span>(<span class="param">min</span>, <span class="param">max</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the number is within the inclusive range [min, max].</p>
|
||||
<pre><code>5.isBetween(1, 10) // true
|
||||
0.isBetween(1, 10) // false
|
||||
10.isBetween(1, 10) // true</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">sign</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns 1 for positive, -1 for negative, or 0 for zero.</p>
|
||||
|
||||
<h2>Arithmetic</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">abs</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Absolute value.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">min</span>(<span class="param">other</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the smaller of this number and <code>other</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">max</span>(<span class="param">other</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the larger of this number and <code>other</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">clamp</span>(<span class="param">min</span>, <span class="param">max</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Constrains this number to the range [min, max].</p>
|
||||
<pre><code>15.clamp(0, 10) // 10
|
||||
5.clamp(0, 10) // 5
|
||||
(-3).clamp(0, 10) // 0</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">pow</span>(<span class="param">exponent</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Raises this number to the given power.</p>
|
||||
|
||||
<h2>Rounding</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ceil</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Rounds up to the nearest integer.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">floor</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Rounds down to the nearest integer.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">round</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Rounds to the nearest integer.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">truncate</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Removes the fractional part, rounding toward zero.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">fraction</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the fractional part of the number.</p>
|
||||
|
||||
<h2>Roots & Exponents</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">sqrt</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Square root.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">cbrt</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Cube root.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">exp</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns e raised to this power.</p>
|
||||
|
||||
<h2>Logarithms</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">log</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Natural logarithm (base e).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">log2</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Base-2 logarithm.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">log10</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Base-10 logarithm.</p>
|
||||
<pre><code>100.log10 // 2
|
||||
1000.log10 // 3
|
||||
1.log10 // 0</code></pre>
|
||||
|
||||
<h2>Trigonometry</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">sin</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Sine (argument in radians).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">cos</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Cosine (argument in radians).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">tan</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Tangent (argument in radians).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">asin</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Arc sine, returns radians.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">acos</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Arc cosine, returns radians.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">atan</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Arc tangent, returns radians.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">atan</span>(<span class="param">x</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Two-argument arc tangent (atan2). Returns the angle between the positive x-axis and the point (x, this).</p>
|
||||
|
||||
<h3>Hyperbolic Functions</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">sinh</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Hyperbolic sine.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">cosh</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Hyperbolic cosine.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">tanh</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Hyperbolic tangent.</p>
|
||||
<pre><code>0.sinh // 0
|
||||
0.cosh // 1
|
||||
0.tanh // 0</code></pre>
|
||||
|
||||
<h2>Angle Conversion</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toDegrees</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Converts radians to degrees.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toRadians</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Converts degrees to radians.</p>
|
||||
<pre><code>Num.pi.toDegrees // 180
|
||||
180.toRadians // 3.14159...</code></pre>
|
||||
|
||||
<h2>Conversion</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toString</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts the number to its string representation.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toChar</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the Unicode character for this code point.</p>
|
||||
<pre><code>65.toChar // "A"
|
||||
97.toChar // "a"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toBase</span>(<span class="param">radix</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts the integer part to a string in the given base (2-36).</p>
|
||||
<pre><code>255.toBase(16) // "ff"
|
||||
255.toBase(2) // "11111111"
|
||||
255.toBase(8) // "377"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toHex</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Shorthand for <code>toBase(16)</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toBinary</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Shorthand for <code>toBase(2)</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toOctal</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Shorthand for <code>toBase(8)</code>.</p>
|
||||
|
||||
<h2>Formatting</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">format</span>(<span class="param">decimals</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Formats the number with a fixed number of decimal places (0-20).</p>
|
||||
<pre><code>3.14159.format(2) // "3.14"
|
||||
42.format(3) // "42.000"
|
||||
(-1.5).format(1) // "-1.5"</code></pre>
|
||||
|
||||
<h2>Integer Operations</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">gcd</span>(<span class="param">other</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Greatest common divisor using the Euclidean algorithm. Operates on absolute values.</p>
|
||||
<pre><code>12.gcd(8) // 4
|
||||
54.gcd(24) // 6
|
||||
7.gcd(13) // 1</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">lcm</span>(<span class="param">other</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Least common multiple.</p>
|
||||
<pre><code>4.lcm(6) // 12
|
||||
3.lcm(5) // 15</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">digits</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns a list of the individual digits of the integer's absolute value. Aborts if the number is not an integer.</p>
|
||||
<pre><code>123.digits // [1, 2, 3]
|
||||
0.digits // [0]
|
||||
(-456).digits // [4, 5, 6]</code></pre>
|
||||
|
||||
<h2>Bitwise Operations</h2>
|
||||
|
||||
<p>Bitwise operators work on 32-bit unsigned integers.</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Operator</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr><td><code>&(other)</code></td><td>Bitwise AND</td></tr>
|
||||
<tr><td><code>|(other)</code></td><td>Bitwise OR</td></tr>
|
||||
<tr><td><code>^(other)</code></td><td>Bitwise XOR</td></tr>
|
||||
<tr><td><code><<(other)</code></td><td>Left shift</td></tr>
|
||||
<tr><td><code>>>(other)</code></td><td>Right shift</td></tr>
|
||||
<tr><td><code>~</code></td><td>Bitwise NOT</td></tr>
|
||||
</table>
|
||||
|
||||
<h2>Ranges</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">..</span>(<span class="param">to</span>) → <span class="type">Range</span>
|
||||
</div>
|
||||
<p>Creates an inclusive range from this number to <code>to</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">...</span>(<span class="param">to</span>) → <span class="type">Range</span>
|
||||
</div>
|
||||
<p>Creates an exclusive range from this number to <code>to</code> (excludes the end).</p>
|
||||
<pre><code>for (i in 1..5) System.print(i) // 1 2 3 4 5
|
||||
for (i in 1...5) System.print(i) // 1 2 3 4</code></pre>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,226 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "os" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "os"}] %}
|
||||
{% set prev_page = {"url": "api/crypto.html", "title": "crypto"} %}
|
||||
{% set next_page = {"url": "api/env.html", "title": "env"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>os</h1>
|
||||
|
||||
<p>The <code>os</code> module provides information about the operating system, platform, and current process.</p>
|
||||
|
||||
<pre><code>import "os" for Platform, Process</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#platform-class">Platform Class</a></li>
|
||||
<li><a href="#process-class">Process Class</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="platform-class">Platform Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Platform</h3>
|
||||
<p>Operating system and platform information</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Platform.name</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The name of the operating system (e.g., "Linux", "macOS", "Windows", "FreeBSD").</p>
|
||||
<pre><code>System.print(Platform.name) // Linux</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Platform.isPosix</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>True if running on a POSIX-compatible system (Linux, macOS, BSD, etc.).</p>
|
||||
<pre><code>if (Platform.isPosix) {
|
||||
System.print("Running on a POSIX system")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Platform.isWindows</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>True if running on Windows.</p>
|
||||
<pre><code>if (Platform.isWindows) {
|
||||
System.print("Running on Windows")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Platform.homePath</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The current user's home directory path.</p>
|
||||
<pre><code>System.print(Platform.homePath) // /home/alice (Linux) or C:\Users\alice (Windows)</code></pre>
|
||||
|
||||
<h2 id="process-class">Process Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Process</h3>
|
||||
<p>Current process information and arguments</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Process.arguments</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Command-line arguments passed to the script (excludes the interpreter and script path).</p>
|
||||
<pre><code>// Running: wren_cli script.wren arg1 arg2
|
||||
System.print(Process.arguments) // [arg1, arg2]</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Process.allArguments</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>All command-line arguments including the interpreter path and script path.</p>
|
||||
<pre><code>// Running: wren_cli script.wren arg1 arg2
|
||||
System.print(Process.allArguments) // [wren_cli, script.wren, arg1, arg2]</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Process.cwd</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The current working directory.</p>
|
||||
<pre><code>System.print(Process.cwd) // /home/alice/projects</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Process.pid</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The process ID of the current process.</p>
|
||||
<pre><code>System.print(Process.pid) // 12345</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Process.ppid</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The parent process ID.</p>
|
||||
<pre><code>System.print(Process.ppid) // 12300</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Process.version</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The version string of the Wren-CLI runtime.</p>
|
||||
<pre><code>System.print(Process.version) // 0.4.0</code></pre>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Process.exit</span>(<span class="param">code</span>)
|
||||
</div>
|
||||
<p>Terminates the process with the specified exit code.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">code</span> <span class="param-type">(Num)</span> - Exit code (0 for success, non-zero for error)</li>
|
||||
</ul>
|
||||
<pre><code>if (hasError) {
|
||||
Process.exit(1)
|
||||
}
|
||||
Process.exit(0)</code></pre>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Platform-Specific Behavior</h3>
|
||||
<pre><code>import "os" for Platform
|
||||
|
||||
var configPath
|
||||
if (Platform.isWindows) {
|
||||
configPath = Platform.homePath + "\\AppData\\Local\\myapp\\config.json"
|
||||
} else {
|
||||
configPath = Platform.homePath + "/.config/myapp/config.json"
|
||||
}
|
||||
|
||||
System.print("Config path: %(configPath)")</code></pre>
|
||||
|
||||
<h3>Processing Command-Line Arguments</h3>
|
||||
<pre><code>import "os" for Process
|
||||
|
||||
var args = Process.arguments
|
||||
|
||||
if (args.count == 0) {
|
||||
System.print("Usage: script.wren <command> [options]")
|
||||
} else {
|
||||
var command = args[0]
|
||||
if (command == "help") {
|
||||
System.print("Available commands: help, version, run")
|
||||
} else if (command == "version") {
|
||||
System.print("Version 1.0.0")
|
||||
} else if (command == "run") {
|
||||
if (args.count > 1) {
|
||||
System.print("Running: %(args[1])")
|
||||
} else {
|
||||
System.print("Error: run requires a file argument")
|
||||
}
|
||||
} else {
|
||||
System.print("Unknown command: %(command)")
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Script Information</h3>
|
||||
<pre><code>import "os" for Platform, Process
|
||||
|
||||
System.print("=== System Information ===")
|
||||
System.print("Platform: %(Platform.name)")
|
||||
System.print("POSIX: %(Platform.isPosix)")
|
||||
System.print("Home: %(Platform.homePath)")
|
||||
System.print("")
|
||||
System.print("=== Process Information ===")
|
||||
System.print("PID: %(Process.pid)")
|
||||
System.print("Parent PID: %(Process.ppid)")
|
||||
System.print("Working Directory: %(Process.cwd)")
|
||||
System.print("Wren Version: %(Process.version)")
|
||||
System.print("")
|
||||
System.print("=== Arguments ===")
|
||||
System.print("Arguments: %(Process.arguments)")</code></pre>
|
||||
|
||||
<h3>Building File Paths</h3>
|
||||
<pre><code>import "os" for Platform, Process
|
||||
|
||||
var separator = Platform.isWindows ? "\\" : "/"
|
||||
|
||||
var dataDir = Process.cwd + separator + "data"
|
||||
var configFile = Platform.homePath + separator + ".myapprc"
|
||||
|
||||
System.print("Data directory: %(dataDir)")
|
||||
System.print("Config file: %(configFile)")</code></pre>
|
||||
|
||||
<h3>Argument Parsing with Flags</h3>
|
||||
<pre><code>import "os" for Process
|
||||
|
||||
var verbose = false
|
||||
var outputFile = "output.txt"
|
||||
var inputFiles = []
|
||||
|
||||
var i = 0
|
||||
var args = Process.arguments
|
||||
while (i < args.count) {
|
||||
var arg = args[i]
|
||||
if (arg == "-v" || arg == "--verbose") {
|
||||
verbose = true
|
||||
} else if (arg == "-o" || arg == "--output") {
|
||||
i = i + 1
|
||||
if (i < args.count) {
|
||||
outputFile = args[i]
|
||||
}
|
||||
} else if (!arg.startsWith("-")) {
|
||||
inputFiles.add(arg)
|
||||
}
|
||||
i = i + 1
|
||||
}
|
||||
|
||||
System.print("Verbose: %(verbose)")
|
||||
System.print("Output: %(outputFile)")
|
||||
System.print("Input files: %(inputFiles)")</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p><code>Process.arguments</code> returns only the user's arguments (after the script path), while <code>Process.allArguments</code> includes the full command line including the interpreter.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Use <code>Platform.isPosix</code> to write cross-platform code that handles path separators, shell commands, and other platform-specific differences.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,573 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "pathlib" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "pathlib"}] %}
|
||||
{% set prev_page = {"url": "api/io.html", "title": "io"} %}
|
||||
{% set next_page = {"url": "api/scheduler.html", "title": "scheduler"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>pathlib</h1>
|
||||
|
||||
<p>The <code>pathlib</code> module provides object-oriented filesystem path operations. Inspired by Python's <code>pathlib</code>, it offers immutable <code>Path</code> objects that combine path manipulation with filesystem I/O in a single interface.</p>
|
||||
|
||||
<pre><code>import "pathlib" for Path</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#purepath-class">PurePath Class</a></li>
|
||||
<li><a href="#path-class">Path Class</a></li>
|
||||
<li><a href="#path-properties">Path Properties</a></li>
|
||||
<li><a href="#path-manipulation">Path Manipulation</a></li>
|
||||
<li><a href="#filesystem-operations">Filesystem Operations</a></li>
|
||||
<li><a href="#directory-operations">Directory Operations</a></li>
|
||||
<li><a href="#symlink-operations">Symlink Operations</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="purepath-class">PurePath Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>PurePath</h3>
|
||||
<p>String-only path operations without filesystem access. Base class for <code>Path</code>.</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructor</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">PurePath.new</span>(<span class="param">path</span>) → <span class="type">PurePath</span>
|
||||
</div>
|
||||
<p>Creates a new PurePath from a string or another PurePath.</p>
|
||||
<pre><code>var p = PurePath.new("/home/user/file.txt")</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">parts</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>The individual components of the path.</p>
|
||||
<pre><code>var p = Path.new("/home/user/file.txt")
|
||||
System.print(p.parts) // [/, home, user, file.txt]</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">name</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The final component of the path (filename with extension).</p>
|
||||
<pre><code>var p = Path.new("/home/user/file.tar.gz")
|
||||
System.print(p.name) // file.tar.gz</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">stem</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The filename without the last extension.</p>
|
||||
<pre><code>var p = Path.new("/home/user/file.tar.gz")
|
||||
System.print(p.stem) // file.tar</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">suffix</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The last file extension, including the leading dot.</p>
|
||||
<pre><code>var p = Path.new("/home/user/file.tar.gz")
|
||||
System.print(p.suffix) // .gz</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">suffixes</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>All file extensions as a list.</p>
|
||||
<pre><code>var p = Path.new("/home/user/file.tar.gz")
|
||||
System.print(p.suffixes) // [.tar, .gz]</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">parent</span> → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>The logical parent of the path.</p>
|
||||
<pre><code>var p = Path.new("/home/user/file.txt")
|
||||
System.print(p.parent) // /home/user</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">parents</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>A list of all ancestor paths, from immediate parent to root.</p>
|
||||
<pre><code>var p = Path.new("/home/user/docs/file.txt")
|
||||
for (ancestor in p.parents) {
|
||||
System.print(ancestor)
|
||||
}
|
||||
// /home/user/docs
|
||||
// /home/user
|
||||
// /home
|
||||
// /</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">drive</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The drive letter (Windows only). Returns empty string on POSIX.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">root</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The root of the path. Returns <code>"/"</code> for absolute paths, empty string for relative.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">anchor</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The concatenation of drive and root.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isAbsolute</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>True if the path is absolute (has a root).</p>
|
||||
<pre><code>System.print(Path.new("/etc/hosts").isAbsolute) // true
|
||||
System.print(Path.new("relative/path").isAbsolute) // false</code></pre>
|
||||
|
||||
<h2 id="path-manipulation">Path Manipulation</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">path</span> / <span class="param">other</span> → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Joins two paths using the <code>/</code> operator. If <code>other</code> is absolute, it replaces the current path.</p>
|
||||
<pre><code>var base = Path.new("/home/user")
|
||||
var full = base / "documents" / "file.txt"
|
||||
System.print(full) // /home/user/documents/file.txt</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">joinpath</span>(<span class="param">other</span>) → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Joins paths. Accepts a string, Path, or List of components.</p>
|
||||
<pre><code>var p = Path.new("/home").joinpath("user").joinpath("file.txt")
|
||||
System.print(p) // /home/user/file.txt
|
||||
|
||||
var q = Path.new("/home").joinpath(["user", "docs", "file.txt"])
|
||||
System.print(q) // /home/user/docs/file.txt</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">withName</span>(<span class="param">newName</span>) → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Returns a new path with the filename replaced.</p>
|
||||
<pre><code>var p = Path.new("/home/user/old.txt")
|
||||
System.print(p.withName("new.txt")) // /home/user/new.txt</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">withStem</span>(<span class="param">newStem</span>) → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Returns a new path with the stem replaced, keeping the extension.</p>
|
||||
<pre><code>var p = Path.new("/data/archive.tar.gz")
|
||||
System.print(p.withStem("backup")) // /data/backup.gz</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">withSuffix</span>(<span class="param">newSuffix</span>) → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Returns a new path with the extension replaced.</p>
|
||||
<pre><code>var p = Path.new("/data/file.txt")
|
||||
System.print(p.withSuffix(".md")) // /data/file.md</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">relativeTo</span>(<span class="param">base</span>) → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Returns a relative path from <code>base</code> to this path. Aborts if the path is not relative to <code>base</code>.</p>
|
||||
<pre><code>var p = Path.new("/home/user/docs/file.txt")
|
||||
System.print(p.relativeTo("/home/user")) // docs/file.txt</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">match</span>(<span class="param">pattern</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Matches the filename against a glob pattern. Supports <code>*</code> and <code>?</code> wildcards.</p>
|
||||
<pre><code>var p = Path.new("/home/user/notes.txt")
|
||||
System.print(p.match("*.txt")) // true
|
||||
System.print(p.match("*.md")) // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">asPosix</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the path string with forward slashes (converts backslashes on Windows).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">expanduser</span>() → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Expands a leading <code>~</code> to the user's home directory.</p>
|
||||
<pre><code>var p = Path.new("~/.config/app")
|
||||
System.print(p.expanduser()) // /home/alice/.config/app</code></pre>
|
||||
|
||||
<h3>Operators</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">==</span>(<span class="param">other</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Compares two paths for equality by their string representation.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">!=</span>(<span class="param">other</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Compares two paths for inequality.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toString</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the path as a string.</p>
|
||||
|
||||
<h2 id="path-class">Path Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Path</h3>
|
||||
<p>Extends PurePath with filesystem operations. This is the primary class for working with paths.</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructor</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Path.new</span>(<span class="param">path</span>) → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Creates a new Path from a string or another Path.</p>
|
||||
<pre><code>var p = Path.new("/home/user/file.txt")</code></pre>
|
||||
|
||||
<h3>Class Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Path.cwd</span> → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>The current working directory as a Path.</p>
|
||||
<pre><code>System.print(Path.cwd) // /home/user/projects</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Path.home</span> → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>The current user's home directory as a Path.</p>
|
||||
<pre><code>System.print(Path.home) // /home/alice</code></pre>
|
||||
|
||||
<h2 id="filesystem-operations">Filesystem Operations</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">exists</span>() → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns true if the path points to an existing file or directory.</p>
|
||||
<pre><code>if (Path.new("/etc/hosts").exists()) {
|
||||
System.print("File exists")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isFile</span>() → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns true if the path points to a regular file.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isDir</span>() → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns true if the path points to a directory.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isSymlink</span>() → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns true if the path is a symbolic link.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">stat</span>() → <span class="type">Stat</span>
|
||||
</div>
|
||||
<p>Returns a Stat object with file metadata (size, mode, timestamps).</p>
|
||||
<pre><code>var s = Path.new("/etc/hosts").stat()
|
||||
System.print(s.size) // 234</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">lstat</span>() → <span class="type">Stat</span>
|
||||
</div>
|
||||
<p>Like <code>stat()</code> but does not follow symbolic links.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">readText</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Reads the entire file contents as a string.</p>
|
||||
<pre><code>var content = Path.new("config.json").readText()
|
||||
System.print(content)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">readBytes</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Reads the entire file contents as bytes.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">writeText</span>(<span class="param">content</span>)
|
||||
</div>
|
||||
<p>Writes a string to the file, creating or overwriting it.</p>
|
||||
<pre><code>Path.new("output.txt").writeText("Hello, World!")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">writeBytes</span>(<span class="param">content</span>)
|
||||
</div>
|
||||
<p>Writes bytes to the file, creating or overwriting it.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">touch</span>()
|
||||
</div>
|
||||
<p>Creates an empty file if it does not exist, or updates its modification time if it does.</p>
|
||||
<pre><code>Path.new("marker.txt").touch()</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">unlink</span>()
|
||||
</div>
|
||||
<p>Deletes the file.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">rename</span>(<span class="param">target</span>) → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Moves or renames the file to <code>target</code>. Returns the new Path.</p>
|
||||
<pre><code>var old = Path.new("draft.txt")
|
||||
var published = old.rename("article.txt")
|
||||
System.print(published) // article.txt</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">replace</span>(<span class="param">target</span>) → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Alias for <code>rename()</code>. Replaces the target if it exists.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">copyfile</span>(<span class="param">dest</span>)
|
||||
</div>
|
||||
<p>Copies this file to <code>dest</code>.</p>
|
||||
<pre><code>Path.new("original.txt").copyfile("backup.txt")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">size</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the size of the file in bytes.</p>
|
||||
<pre><code>var bytes = Path.new("data.txt").size()
|
||||
System.print("File size: %(bytes) bytes")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">mtime</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the modification time as a Unix timestamp (seconds since epoch).</p>
|
||||
<pre><code>var modified = Path.new("file.txt").mtime()
|
||||
System.print("Last modified: %(modified)")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">atime</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the access time as a Unix timestamp.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ctime</span>() → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the change time (inode change) as a Unix timestamp.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">chmod</span>(<span class="param">mode</span>)
|
||||
</div>
|
||||
<p>Changes the file permissions. Mode is an octal number.</p>
|
||||
<pre><code>Path.new("script.sh").chmod(0x1ed) // 0755 in octal</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">resolve</span>() → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>Returns the absolute real path, resolving any symlinks.</p>
|
||||
<pre><code>var real = Path.new("./relative/../file.txt").resolve()
|
||||
System.print(real) // /home/user/file.txt</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">samefile</span>(<span class="param">other</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns true if this path and <code>other</code> refer to the same file (compares inodes).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">owner</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the username of the file owner (POSIX only).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">group</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the group name of the file (POSIX only).</p>
|
||||
|
||||
<h2 id="directory-operations">Directory Operations</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">mkdir</span>()
|
||||
</div>
|
||||
<p>Creates the directory.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">mkdir</span>(<span class="param">parents</span>)
|
||||
</div>
|
||||
<p>Creates the directory. If <code>parents</code> is true, creates all intermediate directories.</p>
|
||||
<pre><code>Path.new("/tmp/a/b/c").mkdir(true)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">rmdir</span>()
|
||||
</div>
|
||||
<p>Removes an empty directory.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">rmtree</span>()
|
||||
</div>
|
||||
<p>Recursively deletes the directory and all its contents.</p>
|
||||
<pre><code>Path.new("/tmp/build_output").rmtree()</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">iterdir</span>() → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns a list of Path objects for each entry in the directory.</p>
|
||||
<pre><code>for (entry in Path.new(".").iterdir()) {
|
||||
System.print(entry.name)
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">glob</span>(<span class="param">pattern</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns paths matching the glob pattern in this directory. Supports <code>*</code> and <code>?</code> wildcards.</p>
|
||||
<pre><code>var txtFiles = Path.new(".").glob("*.txt")
|
||||
for (f in txtFiles) {
|
||||
System.print(f.name)
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">rglob</span>(<span class="param">pattern</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Recursively matches files in this directory and all subdirectories.</p>
|
||||
<pre><code>var allWren = Path.cwd.rglob("*.wren")
|
||||
System.print("Found %(allWren.count) Wren files")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">walk</span>() → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Recursively walks the directory tree top-down. Returns a list of <code>[dirPath, dirNames, fileNames]</code> tuples.</p>
|
||||
<pre><code>for (entry in Path.new("src").walk()) {
|
||||
var dir = entry[0]
|
||||
var dirs = entry[1]
|
||||
var files = entry[2]
|
||||
for (f in files) {
|
||||
System.print(dir / f)
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">walk</span>(<span class="param">topDown</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Walks the directory tree. If <code>topDown</code> is false, visits child directories before parents.</p>
|
||||
|
||||
<h2 id="symlink-operations">Symlink Operations</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">symlinkTo</span>(<span class="param">target</span>)
|
||||
</div>
|
||||
<p>Creates a symbolic link at this path pointing to <code>target</code>.</p>
|
||||
<pre><code>Path.new("/tmp/link").symlinkTo("/etc/hosts")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">hardlinkTo</span>(<span class="param">target</span>)
|
||||
</div>
|
||||
<p>Creates a hard link at this path pointing to <code>target</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">readlink</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the target of the symbolic link.</p>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Configuration File Management</h3>
|
||||
<pre><code>import "pathlib" for Path
|
||||
import "json" for Json
|
||||
|
||||
var configDir = Path.home / ".config" / "myapp"
|
||||
if (!configDir.exists()) {
|
||||
configDir.mkdir(true)
|
||||
}
|
||||
|
||||
var configFile = configDir / "settings.json"
|
||||
if (!configFile.exists()) {
|
||||
configFile.writeText(Json.stringify({
|
||||
"theme": "dark",
|
||||
"language": "en"
|
||||
}, 2))
|
||||
}
|
||||
|
||||
var settings = Json.parse(configFile.readText())
|
||||
System.print("Theme: %(settings["theme"])")</code></pre>
|
||||
|
||||
<h3>Batch File Processing</h3>
|
||||
<pre><code>import "pathlib" for Path
|
||||
|
||||
var dataDir = Path.new("./data")
|
||||
for (file in dataDir.glob("*.csv")) {
|
||||
var size = file.stat().size
|
||||
System.print("%(file.name): %(size) bytes")
|
||||
}
|
||||
|
||||
var total = 0
|
||||
for (wren in Path.cwd.rglob("*.wren")) {
|
||||
total = total + 1
|
||||
}
|
||||
System.print("Found %(total) Wren source files")</code></pre>
|
||||
|
||||
<h3>Directory Tree Traversal</h3>
|
||||
<pre><code>import "pathlib" for Path
|
||||
|
||||
var src = Path.new("src")
|
||||
for (entry in src.walk()) {
|
||||
var dir = entry[0]
|
||||
var files = entry[2]
|
||||
if (files.count > 0) {
|
||||
System.print("%(dir.relativeTo(src)):")
|
||||
for (f in files) {
|
||||
System.print(" %(f)")
|
||||
}
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Path Manipulation</h3>
|
||||
<pre><code>import "pathlib" for Path
|
||||
|
||||
var p = Path.new("/home/user/documents/report.tar.gz")
|
||||
|
||||
System.print(p.name) // report.tar.gz
|
||||
System.print(p.stem) // report.tar
|
||||
System.print(p.suffix) // .gz
|
||||
System.print(p.suffixes) // [.tar, .gz]
|
||||
System.print(p.parent) // /home/user/documents
|
||||
|
||||
var backup = p.withSuffix(".bak")
|
||||
System.print(backup) // /home/user/documents/report.tar.bak
|
||||
|
||||
var renamed = p.withName("summary.pdf")
|
||||
System.print(renamed) // /home/user/documents/summary.pdf</code></pre>
|
||||
|
||||
<h3>Temporary File Cleanup</h3>
|
||||
<pre><code>import "pathlib" for Path
|
||||
|
||||
var tmpDir = Path.new("/tmp/build_artifacts")
|
||||
if (tmpDir.exists()) {
|
||||
tmpDir.rmtree()
|
||||
}
|
||||
|
||||
tmpDir.mkdir(true)
|
||||
(tmpDir / "output.o").touch()
|
||||
(tmpDir / "output.bin").touch()
|
||||
|
||||
var count = tmpDir.iterdir().count
|
||||
System.print("%(count) files in build directory")
|
||||
|
||||
tmpDir.rmtree()</code></pre>
|
||||
|
||||
<h3>Home Directory Expansion</h3>
|
||||
<pre><code>import "pathlib" for Path
|
||||
|
||||
var shortcuts = [
|
||||
Path.new("~/.bashrc"),
|
||||
Path.new("~/.config"),
|
||||
Path.new("~/Documents")
|
||||
]
|
||||
|
||||
for (p in shortcuts) {
|
||||
var expanded = p.expanduser()
|
||||
System.print("%(p) -> %(expanded) (exists: %(expanded.exists()))")
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Path objects are immutable. Methods like <code>withName()</code>, <code>withSuffix()</code>, and <code>joinpath()</code> return new Path objects rather than modifying the original.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Use the <code>/</code> operator for readable path construction: <code>Path.home / ".config" / "myapp" / "settings.json"</code> reads naturally and handles separator insertion automatically.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,269 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "regex" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "regex"}] %}
|
||||
{% set prev_page = {"url": "api/base64.html", "title": "base64"} %}
|
||||
{% set next_page = {"url": "api/jinja.html", "title": "jinja"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>regex</h1>
|
||||
|
||||
<p>The <code>regex</code> module provides regular expression matching, replacement, and splitting using PCRE-compatible patterns.</p>
|
||||
|
||||
<pre><code>import "regex" for Regex, Match</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#regex-class">Regex Class</a></li>
|
||||
<li><a href="#match-class">Match Class</a></li>
|
||||
<li><a href="#pattern-syntax">Pattern Syntax</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="regex-class">Regex Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Regex</h3>
|
||||
<p>Regular expression pattern</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructors</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Regex.new</span>(<span class="param">pattern</span>) → <span class="type">Regex</span>
|
||||
</div>
|
||||
<p>Creates a new regex from a pattern string.</p>
|
||||
<pre><code>var re = Regex.new("\\d+") // Match digits</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Regex.new</span>(<span class="param">pattern</span>, <span class="param">flags</span>) → <span class="type">Regex</span>
|
||||
</div>
|
||||
<p>Creates a regex with flags.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">pattern</span> <span class="param-type">(String)</span> - Regex pattern</li>
|
||||
<li><span class="param-name">flags</span> <span class="param-type">(String)</span> - Flags: "i" (case-insensitive), "m" (multiline), "s" (dotall)</li>
|
||||
</ul>
|
||||
<pre><code>var re = Regex.new("hello", "i") // Case-insensitive</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">pattern</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The pattern string.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">flags</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The flags string.</p>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">test</span>(<span class="param">string</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Tests if the pattern matches anywhere in the string.</p>
|
||||
<pre><code>var re = Regex.new("\\d+")
|
||||
System.print(re.test("abc123")) // true
|
||||
System.print(re.test("abc")) // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">match</span>(<span class="param">string</span>) → <span class="type">Match|null</span>
|
||||
</div>
|
||||
<p>Finds the first match in the string.</p>
|
||||
<pre><code>var re = Regex.new("(\\w+)@(\\w+\\.\\w+)")
|
||||
var m = re.match("email: alice@example.com")
|
||||
if (m != null) {
|
||||
System.print(m.text) // alice@example.com
|
||||
System.print(m.group(1)) // alice
|
||||
System.print(m.group(2)) // example.com
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">matchAll</span>(<span class="param">string</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Finds all matches in the string.</p>
|
||||
<pre><code>var re = Regex.new("\\d+")
|
||||
var matches = re.matchAll("a1 b22 c333")
|
||||
for (m in matches) {
|
||||
System.print(m.text) // 1, 22, 333
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">replace</span>(<span class="param">string</span>, <span class="param">replacement</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Replaces the first match with the replacement string.</p>
|
||||
<pre><code>var re = Regex.new("\\d+")
|
||||
System.print(re.replace("a1b2c3", "X")) // aXb2c3</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">replaceAll</span>(<span class="param">string</span>, <span class="param">replacement</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Replaces all matches with the replacement string.</p>
|
||||
<pre><code>var re = Regex.new("\\d+")
|
||||
System.print(re.replaceAll("a1b2c3", "X")) // aXbXcX</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">split</span>(<span class="param">string</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Splits the string by the pattern.</p>
|
||||
<pre><code>var re = Regex.new("[,;\\s]+")
|
||||
var parts = re.split("a, b; c d")
|
||||
System.print(parts) // [a, b, c, d]</code></pre>
|
||||
|
||||
<h2 id="match-class">Match Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Match</h3>
|
||||
<p>Regex match result</p>
|
||||
</div>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Property</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>text</code></td>
|
||||
<td>String</td>
|
||||
<td>The matched text</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>start</code></td>
|
||||
<td>Num</td>
|
||||
<td>Start index in the original string</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>end</code></td>
|
||||
<td>Num</td>
|
||||
<td>End index in the original string</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>groups</code></td>
|
||||
<td>List</td>
|
||||
<td>List where index 0 is the entire match, index 1+ are capture groups</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">group</span>(<span class="param">index</span>) → <span class="type">String|null</span>
|
||||
</div>
|
||||
<p>Gets a captured group by index. Group 0 is the entire match.</p>
|
||||
<pre><code>var re = Regex.new("(\\w+)-(\\d+)")
|
||||
var m = re.match("item-42")
|
||||
System.print(m.group(0)) // item-42
|
||||
System.print(m.group(1)) // item
|
||||
System.print(m.group(2)) // 42</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>The <code>groups</code> list uses 0-based indexing where <code>groups[0]</code> is the entire match (same as <code>text</code>), and <code>groups[1]</code>, <code>groups[2]</code>, etc. are the captured groups. This is consistent with <code>group(0)</code>, <code>group(1)</code>, etc.</p>
|
||||
</div>
|
||||
|
||||
<h2 id="pattern-syntax">Pattern Syntax</h2>
|
||||
|
||||
<h3>Character Classes</h3>
|
||||
<table>
|
||||
<tr><th>Pattern</th><th>Matches</th></tr>
|
||||
<tr><td><code>.</code></td><td>Any character (except newline)</td></tr>
|
||||
<tr><td><code>\d</code></td><td>Digit (0-9)</td></tr>
|
||||
<tr><td><code>\D</code></td><td>Non-digit</td></tr>
|
||||
<tr><td><code>\w</code></td><td>Word character (a-z, A-Z, 0-9, _)</td></tr>
|
||||
<tr><td><code>\W</code></td><td>Non-word character</td></tr>
|
||||
<tr><td><code>\s</code></td><td>Whitespace</td></tr>
|
||||
<tr><td><code>\S</code></td><td>Non-whitespace</td></tr>
|
||||
<tr><td><code>[abc]</code></td><td>Any of a, b, or c</td></tr>
|
||||
<tr><td><code>[^abc]</code></td><td>Not a, b, or c</td></tr>
|
||||
<tr><td><code>[a-z]</code></td><td>Range a through z</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>Quantifiers</h3>
|
||||
<table>
|
||||
<tr><th>Pattern</th><th>Matches</th></tr>
|
||||
<tr><td><code>*</code></td><td>0 or more</td></tr>
|
||||
<tr><td><code>+</code></td><td>1 or more</td></tr>
|
||||
<tr><td><code>?</code></td><td>0 or 1</td></tr>
|
||||
<tr><td><code>{n}</code></td><td>Exactly n times</td></tr>
|
||||
<tr><td><code>{n,}</code></td><td>n or more times</td></tr>
|
||||
<tr><td><code>{n,m}</code></td><td>Between n and m times</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>Anchors</h3>
|
||||
<table>
|
||||
<tr><th>Pattern</th><th>Matches</th></tr>
|
||||
<tr><td><code>^</code></td><td>Start of string/line</td></tr>
|
||||
<tr><td><code>$</code></td><td>End of string/line</td></tr>
|
||||
<tr><td><code>\b</code></td><td>Word boundary</td></tr>
|
||||
<tr><td><code>\B</code></td><td>Non-word boundary</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>Groups</h3>
|
||||
<table>
|
||||
<tr><th>Pattern</th><th>Description</th></tr>
|
||||
<tr><td><code>(abc)</code></td><td>Capturing group</td></tr>
|
||||
<tr><td><code>(?:abc)</code></td><td>Non-capturing group</td></tr>
|
||||
<tr><td><code>a|b</code></td><td>Alternation (a or b)</td></tr>
|
||||
</table>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Email Validation</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var emailRe = Regex.new("^[\\w.+-]+@[\\w-]+\\.[\\w.-]+$")
|
||||
|
||||
var emails = ["alice@example.com", "invalid", "bob@test.org"]
|
||||
for (email in emails) {
|
||||
if (emailRe.test(email)) {
|
||||
System.print("%(email) is valid")
|
||||
} else {
|
||||
System.print("%(email) is invalid")
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Extracting Data</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var logRe = Regex.new("(\\d{4}-\\d{2}-\\d{2}) (\\w+): (.+)")
|
||||
var log = "2024-01-15 ERROR: Connection failed"
|
||||
|
||||
var m = logRe.match(log)
|
||||
if (m != null) {
|
||||
System.print("Date: %(m.group(1))") // 2024-01-15
|
||||
System.print("Level: %(m.group(2))") // ERROR
|
||||
System.print("Message: %(m.group(3))") // Connection failed
|
||||
}</code></pre>
|
||||
|
||||
<h3>Find and Replace</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var text = "Call 555-1234 or 555-5678"
|
||||
var phoneRe = Regex.new("\\d{3}-\\d{4}")
|
||||
|
||||
var redacted = phoneRe.replaceAll(text, "XXX-XXXX")
|
||||
System.print(redacted) // Call XXX-XXXX or XXX-XXXX</code></pre>
|
||||
|
||||
<h3>Parsing URLs</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var urlRe = Regex.new("(https?)://([^/]+)(/.*)?")
|
||||
var url = "https://example.com/path/to/page"
|
||||
|
||||
var m = urlRe.match(url)
|
||||
System.print("Scheme: %(m.group(1))") // https
|
||||
System.print("Host: %(m.group(2))") // example.com
|
||||
System.print("Path: %(m.group(3))") // /path/to/page</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Remember to escape backslashes in Wren strings. Use <code>\\d</code> instead of <code>\d</code>.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,255 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "scheduler" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "scheduler"}] %}
|
||||
{% set prev_page = {"url": "api/pathlib.html", "title": "pathlib"} %}
|
||||
{% set next_page = {"url": "api/math.html", "title": "math"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>scheduler</h1>
|
||||
|
||||
<p>The <code>scheduler</code> module manages the async event loop and fiber scheduling. It is the foundation for all async operations in Wren-CLI.</p>
|
||||
|
||||
<pre><code>import "scheduler" for Scheduler, Future</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Quick Reference</div>
|
||||
<p>The scheduler module enables async programming with <code>async</code> and <code>await</code>:</p>
|
||||
<ul>
|
||||
<li><code>async { code }</code> — Create an async function</li>
|
||||
<li><code>await fn()</code> — Call async function and wait for result</li>
|
||||
<li><code>fn.call()</code> — Start async function, return Future (for concurrent execution)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>Scheduler Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Scheduler</h3>
|
||||
<p>Async fiber scheduler</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Scheduler.await_</span>(<span class="param">block</span>) → <span class="type">any</span>
|
||||
</div>
|
||||
<p>Suspends the current fiber until an async operation completes. Used internally by modules to implement async operations.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">block</span> <span class="param-type">(Fn)</span> - Block that initiates the async operation</li>
|
||||
<li><span class="returns">Returns:</span> Result of the async operation</li>
|
||||
</ul>
|
||||
<pre><code>var result = Scheduler.await_ {
|
||||
Timer.sleep_(1000, Fiber.current)
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Scheduler.resume_</span>(<span class="param">fiber</span>)
|
||||
</div>
|
||||
<p>Resumes a suspended fiber. Used by native code to wake up fibers when async operations complete.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Scheduler.resume_</span>(<span class="param">fiber</span>, <span class="param">value</span>)
|
||||
</div>
|
||||
<p>Resumes a fiber with a result value.</p>
|
||||
|
||||
<h2 id="await-syntax">Await Syntax</h2>
|
||||
|
||||
<p>Wren-CLI provides a convenient syntax for awaiting async functions. Instead of using <code>.call()</code>, you can call async functions directly after <code>await</code>:</p>
|
||||
|
||||
<h3>Before and After</h3>
|
||||
<pre><code>// Old syntax (still works)
|
||||
var result = await asyncFn.call(arg1, arg2)
|
||||
|
||||
// New syntax (recommended)
|
||||
var result = await asyncFn(arg1, arg2)</code></pre>
|
||||
|
||||
<p>The compiler automatically translates <code>await fn(args)</code> to <code>await fn.call(args)</code>.</p>
|
||||
|
||||
<h3>Supported Patterns</h3>
|
||||
|
||||
<table class="params-table">
|
||||
<thead>
|
||||
<tr><th>Pattern</th><th>Example</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td>No arguments</td><td><code>await getValue()</code></td></tr>
|
||||
<tr><td>Single argument</td><td><code>await double(21)</code></td></tr>
|
||||
<tr><td>Multiple arguments</td><td><code>await add(3, 4, 5)</code></td></tr>
|
||||
<tr><td>Nested awaits</td><td><code>await outer(await inner(x))</code></td></tr>
|
||||
<tr><td>In expressions</td><td><code>var x = 1 + await fn(2)</code></td></tr>
|
||||
<tr><td>In conditions</td><td><code>if (await check(x)) { }</code></td></tr>
|
||||
<tr><td>Block argument</td><td><code>await map(list) { |x| x * 2 }</code></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Method chaining after <code>await fn(args)</code> requires assigning the result first:</p>
|
||||
<pre><code>var list = await getList(5)
|
||||
System.print(list.count)</code></pre>
|
||||
</div>
|
||||
|
||||
<h3>Examples</h3>
|
||||
|
||||
<pre><code>import "scheduler" for Scheduler, Future
|
||||
|
||||
var double = async { |x| x * 2 }
|
||||
var add = async { |a, b| a + b }
|
||||
|
||||
// Basic usage
|
||||
System.print(await double(21)) // 42
|
||||
System.print(await add(3, 4)) // 7
|
||||
|
||||
// Nested awaits
|
||||
var result = await double(await add(5, 5)) // 20
|
||||
|
||||
// Method chaining
|
||||
var getList = async { |n| [1, 2, 3, n] }
|
||||
System.print(await getList(4).count) // 4
|
||||
|
||||
// In expressions
|
||||
var total = await add(10, 20) + await double(5) // 40</code></pre>
|
||||
|
||||
<h3>Class-Based Async Patterns</h3>
|
||||
|
||||
<p>Static getters that return async functions must first be assigned to a variable:</p>
|
||||
|
||||
<pre><code>import "scheduler" for Scheduler, Future
|
||||
|
||||
class Calculator {
|
||||
static add { async { |a, b| a + b } }
|
||||
static multiply { async { |a, b| a * b } }
|
||||
static square { async { |x| x * x } }
|
||||
|
||||
static compute(a, b) {
|
||||
var addFn = Calculator.add
|
||||
var multiplyFn = Calculator.multiply
|
||||
var sum = await addFn(a, b)
|
||||
var product = await multiplyFn(a, b)
|
||||
return [sum, product]
|
||||
}
|
||||
}
|
||||
|
||||
// Assign getter to variable first, then await
|
||||
var add = Calculator.add
|
||||
System.print(await add(3, 4)) // 7
|
||||
|
||||
var multiply = Calculator.multiply
|
||||
System.print(await multiply(5, 6)) // 30
|
||||
|
||||
var square = Calculator.square
|
||||
System.print(await square(8)) // 64</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>The <code>fn(args)</code> syntax only works directly after <code>await</code>. Outside of <code>await</code>, use <code>fn.call(args)</code> to invoke async functions.</p>
|
||||
</div>
|
||||
|
||||
<h2>Future Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Future</h3>
|
||||
<p>Represents a pending async result</p>
|
||||
</div>
|
||||
|
||||
<p>A <code>Future</code> is returned when you call an async function with <code>.call()</code> instead of using <code>await</code> directly. This enables concurrent execution by starting multiple operations without waiting.</p>
|
||||
|
||||
<h3>Creating Futures</h3>
|
||||
|
||||
<pre><code>import "scheduler" for Scheduler, Future
|
||||
|
||||
var double = async { |x| x * 2 }
|
||||
|
||||
// Direct call with await - waits immediately
|
||||
var result = await double(21)
|
||||
|
||||
// Using .call() returns a Future - does not wait
|
||||
var future = double.call(21)
|
||||
|
||||
// Later, await the future to get the result
|
||||
var result = await future</code></pre>
|
||||
|
||||
<h3>Concurrent Execution Pattern</h3>
|
||||
|
||||
<pre><code>import "scheduler" for Scheduler, Future
|
||||
import "web" for Client
|
||||
|
||||
var fetch = async { |url| Client.get(url) }
|
||||
|
||||
// Start all requests at once (returns Futures)
|
||||
var f1 = fetch.call("https://api.example.com/users")
|
||||
var f2 = fetch.call("https://api.example.com/posts")
|
||||
var f3 = fetch.call("https://api.example.com/comments")
|
||||
|
||||
// All three requests are now running concurrently
|
||||
// Wait for each result
|
||||
var users = await f1
|
||||
var posts = await f2
|
||||
var comments = await f3</code></pre>
|
||||
|
||||
<h2>How Async Works</h2>
|
||||
|
||||
<p>Wren-CLI uses an event loop (libuv) for non-blocking I/O. Here is how async operations work:</p>
|
||||
|
||||
<ol>
|
||||
<li>A Wren fiber calls an async method (e.g., <code>Http.get</code>)</li>
|
||||
<li>The method starts a native async operation and suspends the fiber</li>
|
||||
<li>The event loop continues processing other events</li>
|
||||
<li>When the operation completes, the fiber is resumed with the result</li>
|
||||
</ol>
|
||||
|
||||
<h3>Under the Hood</h3>
|
||||
<pre><code>// How Timer.sleep works internally
|
||||
class Timer {
|
||||
static sleep(ms) {
|
||||
return Scheduler.await_ {
|
||||
Timer.sleep_(ms, Fiber.current)
|
||||
}
|
||||
}
|
||||
|
||||
foreign static sleep_(ms, fiber)
|
||||
}</code></pre>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Sequential vs Concurrent Execution</h3>
|
||||
<p>Using <code>await fn(args)</code> executes operations sequentially:</p>
|
||||
<pre><code>import "scheduler" for Scheduler, Future
|
||||
import "web" for Client
|
||||
|
||||
var fetch = async { |url| Client.get(url) }
|
||||
|
||||
// Sequential: each request waits for the previous one
|
||||
var r1 = await fetch("https://api.example.com/1")
|
||||
var r2 = await fetch("https://api.example.com/2")
|
||||
var r3 = await fetch("https://api.example.com/3")</code></pre>
|
||||
|
||||
<p>Using <code>.call()</code> enables concurrent execution:</p>
|
||||
<pre><code>import "scheduler" for Scheduler, Future
|
||||
import "web" for Client
|
||||
|
||||
var fetch = async { |url| Client.get(url) }
|
||||
|
||||
// Start all requests at once (concurrent)
|
||||
var f1 = fetch.call("https://api.example.com/1")
|
||||
var f2 = fetch.call("https://api.example.com/2")
|
||||
var f3 = fetch.call("https://api.example.com/3")
|
||||
|
||||
// All three requests are running in parallel
|
||||
// Now wait for results
|
||||
var r1 = await f1
|
||||
var r2 = await f2
|
||||
var r3 = await f3</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>The scheduler is used internally by modules. Most user code does not need to interact with it directly. Use higher-level modules like <code>timer</code>, <code>http</code>, and <code>io</code> instead.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Async operations in Wren-CLI are cooperative, not preemptive. A fiber runs until it explicitly yields or calls an async operation.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,260 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "signal" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "signal"}] %}
|
||||
{% set prev_page = {"url": "api/scheduler.html", "title": "scheduler"} %}
|
||||
{% set next_page = {"url": "api/sqlite.html", "title": "sqlite"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>signal</h1>
|
||||
|
||||
<p>The <code>signal</code> module provides Unix signal handling capabilities, allowing scripts to trap, ignore, or reset signal handlers.</p>
|
||||
|
||||
<pre><code>import "signal" for Signal</code></pre>
|
||||
|
||||
<h2>Signal Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Signal</h3>
|
||||
<p>Unix signal handling</p>
|
||||
</div>
|
||||
|
||||
<h3>Signal Constants</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Constant</th>
|
||||
<th>Value</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Signal.SIGHUP</code></td>
|
||||
<td>1</td>
|
||||
<td>Hangup (terminal closed or controlling process ended)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Signal.SIGINT</code></td>
|
||||
<td>2</td>
|
||||
<td>Interrupt (Ctrl+C)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Signal.SIGQUIT</code></td>
|
||||
<td>3</td>
|
||||
<td>Quit (Ctrl+\)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Signal.SIGTERM</code></td>
|
||||
<td>15</td>
|
||||
<td>Termination request</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Signal.SIGUSR1</code></td>
|
||||
<td>10</td>
|
||||
<td>User-defined signal 1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Signal.SIGUSR2</code></td>
|
||||
<td>12</td>
|
||||
<td>User-defined signal 2</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Signal.trap</span>(<span class="param">signum</span>, <span class="param">fn</span>)
|
||||
</div>
|
||||
<p>Registers a handler function to be called when the signal is received. The handler will be called each time the signal is received.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">signum</span> <span class="param-type">(Num)</span> - Signal number or constant</li>
|
||||
<li><span class="param-name">fn</span> <span class="param-type">(Fn)</span> - Handler function (no arguments)</li>
|
||||
</ul>
|
||||
<pre><code>Signal.trap(Signal.SIGINT) {
|
||||
System.print("Caught Ctrl+C!")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Signal.ignore</span>(<span class="param">signum</span>)
|
||||
</div>
|
||||
<p>Ignores the specified signal. The signal will be delivered but have no effect.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">signum</span> <span class="param-type">(Num)</span> - Signal number to ignore</li>
|
||||
</ul>
|
||||
<pre><code>Signal.ignore(Signal.SIGHUP)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Signal.reset</span>(<span class="param">signum</span>)
|
||||
</div>
|
||||
<p>Resets the signal handler to the default behavior.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">signum</span> <span class="param-type">(Num)</span> - Signal number to reset</li>
|
||||
</ul>
|
||||
<pre><code>Signal.reset(Signal.SIGINT)</code></pre>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Graceful Shutdown</h3>
|
||||
<pre><code>import "signal" for Signal
|
||||
import "timer" for Timer
|
||||
|
||||
var running = true
|
||||
|
||||
Signal.trap(Signal.SIGINT) {
|
||||
System.print("\nShutting down gracefully...")
|
||||
running = false
|
||||
}
|
||||
|
||||
Signal.trap(Signal.SIGTERM) {
|
||||
System.print("\nReceived SIGTERM, shutting down...")
|
||||
running = false
|
||||
}
|
||||
|
||||
System.print("Server running. Press Ctrl+C to stop.")
|
||||
while (running) {
|
||||
Timer.sleep(1000)
|
||||
}
|
||||
|
||||
System.print("Cleanup complete. Goodbye!")</code></pre>
|
||||
|
||||
<h3>Configuration Reload on SIGHUP</h3>
|
||||
<pre><code>import "signal" for Signal
|
||||
import "timer" for Timer
|
||||
import "io" for File
|
||||
|
||||
var config = {}
|
||||
|
||||
var loadConfig = Fn.new {
|
||||
System.print("Loading configuration...")
|
||||
if (File.exists("config.json")) {
|
||||
var content = File.read("config.json")
|
||||
System.print("Config loaded: %(content)")
|
||||
}
|
||||
}
|
||||
|
||||
loadConfig.call()
|
||||
|
||||
Signal.trap(Signal.SIGHUP) {
|
||||
System.print("Received SIGHUP, reloading config...")
|
||||
loadConfig.call()
|
||||
}
|
||||
|
||||
System.print("Running. Send SIGHUP to reload config.")
|
||||
while (true) {
|
||||
Timer.sleep(1000)
|
||||
}</code></pre>
|
||||
|
||||
<h3>Custom Signal for Debug Dump</h3>
|
||||
<pre><code>import "signal" for Signal
|
||||
import "timer" for Timer
|
||||
import "datetime" for DateTime
|
||||
|
||||
var requestCount = 0
|
||||
var startTime = DateTime.now()
|
||||
|
||||
Signal.trap(Signal.SIGUSR1) {
|
||||
System.print("=== Debug Dump ===")
|
||||
System.print("Requests handled: %(requestCount)")
|
||||
var uptime = DateTime.now() - startTime
|
||||
System.print("Uptime: %(uptime.hours) hours")
|
||||
System.print("==================")
|
||||
}
|
||||
|
||||
System.print("Send SIGUSR1 for debug info (kill -USR1 pid)")
|
||||
while (true) {
|
||||
requestCount = requestCount + 1
|
||||
Timer.sleep(100)
|
||||
}</code></pre>
|
||||
|
||||
<h3>Ignoring Signals</h3>
|
||||
<pre><code>import "signal" for Signal
|
||||
import "timer" for Timer
|
||||
|
||||
Signal.ignore(Signal.SIGINT)
|
||||
System.print("SIGINT is now ignored. Ctrl+C will not stop this script.")
|
||||
System.print("Use 'kill -9 pid' to force stop.")
|
||||
|
||||
for (i in 1..10) {
|
||||
System.print("Still running... %(i)")
|
||||
Timer.sleep(1000)
|
||||
}
|
||||
|
||||
Signal.reset(Signal.SIGINT)
|
||||
System.print("SIGINT handler restored. Ctrl+C works again.")</code></pre>
|
||||
|
||||
<h3>Multiple Signal Handlers</h3>
|
||||
<pre><code>import "signal" for Signal
|
||||
import "timer" for Timer
|
||||
|
||||
var shutdownRequested = false
|
||||
var forceShutdown = false
|
||||
|
||||
Signal.trap(Signal.SIGINT) {
|
||||
if (shutdownRequested) {
|
||||
System.print("\nForce shutdown!")
|
||||
forceShutdown = true
|
||||
} else {
|
||||
System.print("\nGraceful shutdown requested. Press Ctrl+C again to force.")
|
||||
shutdownRequested = true
|
||||
}
|
||||
}
|
||||
|
||||
Signal.trap(Signal.SIGTERM) {
|
||||
System.print("\nSIGTERM received, shutting down immediately.")
|
||||
forceShutdown = true
|
||||
}
|
||||
|
||||
System.print("Running... Press Ctrl+C to stop.")
|
||||
while (!forceShutdown) {
|
||||
if (shutdownRequested) {
|
||||
System.print("Cleaning up...")
|
||||
Timer.sleep(500)
|
||||
break
|
||||
}
|
||||
Timer.sleep(100)
|
||||
}
|
||||
|
||||
System.print("Exited.")</code></pre>
|
||||
|
||||
<h3>Worker Process Control</h3>
|
||||
<pre><code>import "signal" for Signal
|
||||
import "timer" for Timer
|
||||
|
||||
var paused = false
|
||||
|
||||
Signal.trap(Signal.SIGUSR1) {
|
||||
paused = true
|
||||
System.print("Worker paused")
|
||||
}
|
||||
|
||||
Signal.trap(Signal.SIGUSR2) {
|
||||
paused = false
|
||||
System.print("Worker resumed")
|
||||
}
|
||||
|
||||
System.print("Worker running. SIGUSR1 to pause, SIGUSR2 to resume.")
|
||||
|
||||
var count = 0
|
||||
while (true) {
|
||||
if (!paused) {
|
||||
count = count + 1
|
||||
System.print("Working... %(count)")
|
||||
}
|
||||
Timer.sleep(1000)
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Signal handling is only available on POSIX systems (Linux, macOS, BSD). On Windows, signal support is limited.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Some signals like SIGKILL (9) and SIGSTOP (19) cannot be trapped or ignored. Attempting to do so will have no effect.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Always implement graceful shutdown handlers for long-running services. Use SIGTERM for clean shutdowns and reserve SIGINT for interactive termination.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,167 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "sqlite" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "sqlite"}] %}
|
||||
{% set prev_page = {"url": "api/signal.html", "title": "signal"} %}
|
||||
{% set next_page = {"url": "api/subprocess.html", "title": "subprocess"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>sqlite</h1>
|
||||
|
||||
<p>The <code>sqlite</code> module provides SQLite database functionality for persistent data storage.</p>
|
||||
|
||||
<pre><code>import "sqlite" for Sqlite</code></pre>
|
||||
|
||||
<h2>Sqlite Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Sqlite</h3>
|
||||
<p>SQLite database connection</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructors</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Sqlite.open</span>(<span class="param">path</span>) → <span class="type">Sqlite</span>
|
||||
</div>
|
||||
<p>Opens or creates an SQLite database file.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">path</span> <span class="param-type">(String)</span> - Path to the database file</li>
|
||||
<li><span class="returns">Returns:</span> Database connection</li>
|
||||
</ul>
|
||||
<pre><code>var db = Sqlite.open("data.db")</code></pre>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">execute</span>(<span class="param">sql</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Executes an SQL statement and returns the results.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">sql</span> <span class="param-type">(String)</span> - SQL statement</li>
|
||||
<li><span class="returns">Returns:</span> List of result rows (each row is a Map)</li>
|
||||
</ul>
|
||||
<pre><code>var rows = db.execute("SELECT * FROM users")
|
||||
for (row in rows) {
|
||||
System.print(row["name"])
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">execute</span>(<span class="param">sql</span>, <span class="param">params</span>) → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Executes a parameterized SQL statement (prevents SQL injection).</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">sql</span> <span class="param-type">(String)</span> - SQL with ? placeholders</li>
|
||||
<li><span class="param-name">params</span> <span class="param-type">(List)</span> - Parameter values</li>
|
||||
</ul>
|
||||
<pre><code>var rows = db.execute("SELECT * FROM users WHERE age > ?", [18])</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">lastInsertId</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the row ID of the last INSERT operation.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>()
|
||||
</div>
|
||||
<p>Closes the database connection.</p>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Creating Tables</h3>
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
|
||||
var db = Sqlite.open("app.db")
|
||||
|
||||
db.execute("
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
email TEXT UNIQUE,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
")
|
||||
|
||||
db.close()</code></pre>
|
||||
|
||||
<h3>Inserting Data</h3>
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
|
||||
var db = Sqlite.open("app.db")
|
||||
|
||||
db.execute("INSERT INTO users (name, email) VALUES (?, ?)", ["Alice", "alice@example.com"])
|
||||
System.print("Inserted user with ID: %(db.lastInsertId)")
|
||||
|
||||
db.execute("INSERT INTO users (name, email) VALUES (?, ?)", ["Bob", "bob@example.com"])
|
||||
|
||||
db.close()</code></pre>
|
||||
|
||||
<h3>Querying Data</h3>
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
|
||||
var db = Sqlite.open("app.db")
|
||||
|
||||
var users = db.execute("SELECT * FROM users ORDER BY name")
|
||||
for (user in users) {
|
||||
System.print("%(user["id"]): %(user["name"]) <%(user["email"])>")
|
||||
}
|
||||
|
||||
var user = db.execute("SELECT * FROM users WHERE id = ?", [1])
|
||||
if (user.count > 0) {
|
||||
System.print("Found: %(user[0]["name"])")
|
||||
}
|
||||
|
||||
db.close()</code></pre>
|
||||
|
||||
<h3>Updating Data</h3>
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
|
||||
var db = Sqlite.open("app.db")
|
||||
|
||||
db.execute("UPDATE users SET email = ? WHERE id = ?", ["newemail@example.com", 1])
|
||||
|
||||
db.close()</code></pre>
|
||||
|
||||
<h3>Deleting Data</h3>
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
|
||||
var db = Sqlite.open("app.db")
|
||||
|
||||
db.execute("DELETE FROM users WHERE id = ?", [2])
|
||||
|
||||
db.close()</code></pre>
|
||||
|
||||
<h3>Transactions</h3>
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
|
||||
var db = Sqlite.open("app.db")
|
||||
|
||||
db.execute("BEGIN TRANSACTION")
|
||||
|
||||
var fiber = Fiber.new {
|
||||
db.execute("INSERT INTO users (name, email) VALUES (?, ?)", ["Charlie", "charlie@example.com"])
|
||||
db.execute("INSERT INTO users (name, email) VALUES (?, ?)", ["Diana", "diana@example.com"])
|
||||
}
|
||||
|
||||
var error = fiber.try()
|
||||
if (error) {
|
||||
db.execute("ROLLBACK")
|
||||
System.print("Error: %(error)")
|
||||
} else {
|
||||
db.execute("COMMIT")
|
||||
System.print("Transaction committed")
|
||||
}
|
||||
|
||||
db.close()</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Always use parameterized queries with <code>?</code> placeholders to prevent SQL injection attacks. Never concatenate user input directly into SQL strings.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Use <code>":memory:"</code> as the path for an in-memory database that does not persist to disk.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,345 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "String" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "String"}] %}
|
||||
{% set prev_page = {"url": "api/index.html", "title": "Overview"} %}
|
||||
{% set next_page = {"url": "api/http.html", "title": "http"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>String</h1>
|
||||
|
||||
<p>The <code>String</code> class is a core type available globally without imports. Strings in Wren are immutable sequences of bytes, typically representing UTF-8 encoded text. All methods return new strings rather than modifying the original.</p>
|
||||
|
||||
<pre><code>var s = "Hello World"
|
||||
System.print(s.lower) // hello world
|
||||
System.print(s.upper) // HELLO WORLD
|
||||
System.print(s.title) // Hello World
|
||||
System.print(s.reverse) // dlroW olleH</code></pre>
|
||||
|
||||
<h2>Case Conversion</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">lower</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the string with all ASCII uppercase characters converted to lowercase.</p>
|
||||
<pre><code>"Hello World".lower // "hello world"
|
||||
"ABC 123".lower // "abc 123"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">upper</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the string with all ASCII lowercase characters converted to uppercase.</p>
|
||||
<pre><code>"Hello World".upper // "HELLO WORLD"
|
||||
"abc 123".upper // "ABC 123"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">capitalize</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the string with the first character uppercased and the rest lowercased.</p>
|
||||
<pre><code>"hello world".capitalize // "Hello world"
|
||||
"HELLO".capitalize // "Hello"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">title</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the string with the first character of each word capitalized and the rest lowercased. Words are separated by whitespace.</p>
|
||||
<pre><code>"hello world".title // "Hello World"
|
||||
"HELLO WORLD".title // "Hello World"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">swapCase</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the string with uppercase characters converted to lowercase and vice versa.</p>
|
||||
<pre><code>"Hello World".swapCase // "hELLO wORLD"</code></pre>
|
||||
|
||||
<h2>Character Testing</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isLower</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if the string contains at least one alphabetic character and all alphabetic characters are lowercase.</p>
|
||||
<pre><code>"hello".isLower // true
|
||||
"hello1".isLower // true
|
||||
"Hello".isLower // false
|
||||
"123".isLower // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isUpper</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if the string contains at least one alphabetic character and all alphabetic characters are uppercase.</p>
|
||||
<pre><code>"HELLO".isUpper // true
|
||||
"HELLO1".isUpper // true
|
||||
"Hello".isUpper // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isDigit</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if the string is non-empty and all bytes are ASCII digits (0-9).</p>
|
||||
<pre><code>"12345".isDigit // true
|
||||
"123a5".isDigit // false
|
||||
"".isDigit // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isAlpha</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if the string is non-empty and all bytes are ASCII letters (a-z, A-Z).</p>
|
||||
<pre><code>"hello".isAlpha // true
|
||||
"hello1".isAlpha // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isAlphaNumeric</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if the string is non-empty and all bytes are ASCII letters or digits.</p>
|
||||
<pre><code>"hello123".isAlphaNumeric // true
|
||||
"hello!".isAlphaNumeric // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isSpace</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if the string is non-empty and all bytes are ASCII whitespace (space, tab, newline, carriage return, form feed, vertical tab).</p>
|
||||
<pre><code>" ".isSpace // true
|
||||
" \t\n".isSpace // true
|
||||
"hello".isSpace // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isAscii</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if all bytes in the string are less than 128. Returns <code>true</code> for empty strings.</p>
|
||||
<pre><code>"hello".isAscii // true
|
||||
"".isAscii // true</code></pre>
|
||||
|
||||
<h2>Search</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">lastIndexOf</span>(<span class="param">search</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the byte index of the last occurrence of <code>search</code> in the string, or <code>-1</code> if not found.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">search</span> <span class="param-type">(String)</span> - The substring to search for</li>
|
||||
<li><span class="returns">Returns:</span> Byte index or -1</li>
|
||||
</ul>
|
||||
<pre><code>"hello world hello".lastIndexOf("hello") // 12
|
||||
"hello".lastIndexOf("x") // -1</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">lastIndexOf</span>(<span class="param">search</span>, <span class="param">start</span>) → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the byte index of the last occurrence of <code>search</code> at or before <code>start</code>, or <code>-1</code> if not found.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">search</span> <span class="param-type">(String)</span> - The substring to search for</li>
|
||||
<li><span class="param-name">start</span> <span class="param-type">(Num)</span> - Maximum byte index to search from</li>
|
||||
<li><span class="returns">Returns:</span> Byte index or -1</li>
|
||||
</ul>
|
||||
<pre><code>"hello world hello".lastIndexOf("hello", 11) // 0
|
||||
"hello world hello".lastIndexOf("hello", 12) // 12</code></pre>
|
||||
|
||||
<h2>Transformation</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">reverse</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the string with characters in reverse order. Code point aware for UTF-8 strings.</p>
|
||||
<pre><code>"hello".reverse // "olleh"
|
||||
"abcde".reverse // "edcba"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">center</span>(<span class="param">width</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Centers the string in a field of <code>width</code> characters, padded with spaces.</p>
|
||||
<pre><code>"hi".center(10) // " hi "</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">center</span>(<span class="param">width</span>, <span class="param">char</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Centers the string in a field of <code>width</code> characters, padded with the given fill character.</p>
|
||||
<pre><code>"hi".center(10, "-") // "----hi----"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">lpad</span>(<span class="param">width</span>, <span class="param">char</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Left-pads the string to <code>width</code> characters using the given fill character.</p>
|
||||
<pre><code>"42".lpad(5, "0") // "00042"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">rpad</span>(<span class="param">width</span>, <span class="param">char</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Right-pads the string to <code>width</code> characters using the given fill character.</p>
|
||||
<pre><code>"hi".rpad(5, ".") // "hi..."</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">zfill</span>(<span class="param">width</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Pads the string with leading zeros to <code>width</code> characters. Preserves a leading <code>-</code> or <code>+</code> sign.</p>
|
||||
<pre><code>"42".zfill(5) // "00042"
|
||||
"-42".zfill(6) // "-00042"
|
||||
"+42".zfill(6) // "+00042"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">removePrefix</span>(<span class="param">prefix</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>If the string starts with <code>prefix</code>, returns the string with the prefix removed. Otherwise returns the original string.</p>
|
||||
<pre><code>"HelloWorld".removePrefix("Hello") // "World"
|
||||
"HelloWorld".removePrefix("World") // "HelloWorld"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">removeSuffix</span>(<span class="param">suffix</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>If the string ends with <code>suffix</code>, returns the string with the suffix removed. Otherwise returns the original string.</p>
|
||||
<pre><code>"HelloWorld".removeSuffix("World") // "Hello"
|
||||
"HelloWorld".removeSuffix("Hello") // "HelloWorld"</code></pre>
|
||||
|
||||
<h2>Splitting & Conversion</h2>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">splitLines</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Splits the string by line endings (<code>\n</code>, <code>\r\n</code>, <code>\r</code>) and returns a list of strings.</p>
|
||||
<pre><code>"line1\nline2\nline3".splitLines // ["line1", "line2", "line3"]
|
||||
"a\r\nb\r\nc".splitLines // ["a", "b", "c"]</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">chars</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns a list of individual characters (code points) in the string.</p>
|
||||
<pre><code>"abc".chars // ["a", "b", "c"]
|
||||
"".chars // []</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">toNum</span> → <span class="type">Num</span> | <span class="type">Null</span>
|
||||
</div>
|
||||
<p>Parses the string as a number. Returns <code>null</code> if the string cannot be parsed.</p>
|
||||
<pre><code>"42".toNum // 42
|
||||
"3.14".toNum // 3.14
|
||||
"-7".toNum // -7
|
||||
"abc".toNum // null</code></pre>
|
||||
|
||||
<h2>Comparison</h2>
|
||||
|
||||
<p>Strings support lexicographic comparison using the standard comparison operators. Comparison is byte-by-byte using the raw byte values, which produces correct results for ASCII and UTF-8 encoded text.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name"><</span>(<span class="param">other</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if this string is lexicographically less than <code>other</code>.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">other</span> <span class="param-type">(String)</span> - The string to compare against</li>
|
||||
</ul>
|
||||
<pre><code>"apple" < "banana" // true
|
||||
"abc" < "abd" // true
|
||||
"abc" < "abcd" // true (prefix is less than longer string)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">></span>(<span class="param">other</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if this string is lexicographically greater than <code>other</code>.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">other</span> <span class="param-type">(String)</span> - The string to compare against</li>
|
||||
</ul>
|
||||
<pre><code>"banana" > "apple" // true
|
||||
"abd" > "abc" // true
|
||||
"abcd" > "abc" // true</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name"><=</span>(<span class="param">other</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if this string is lexicographically less than or equal to <code>other</code>.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">other</span> <span class="param-type">(String)</span> - The string to compare against</li>
|
||||
</ul>
|
||||
<pre><code>"abc" <= "abc" // true
|
||||
"abc" <= "abd" // true
|
||||
"abd" <= "abc" // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">>=</span>(<span class="param">other</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns <code>true</code> if this string is lexicographically greater than or equal to <code>other</code>.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">other</span> <span class="param-type">(String)</span> - The string to compare against</li>
|
||||
</ul>
|
||||
<pre><code>"abc" >= "abc" // true
|
||||
"abd" >= "abc" // true
|
||||
"abc" >= "abd" // false</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>String comparison is byte-based, so uppercase letters sort before lowercase letters in ASCII order (e.g., <code>"Z" < "a"</code> is <code>true</code>). If you need case-insensitive comparison, convert both strings to the same case first using <code>lower</code> or <code>upper</code>.</p>
|
||||
</div>
|
||||
|
||||
<h2>Existing Methods</h2>
|
||||
|
||||
<p>The following methods are also available on all strings as part of the core VM.</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Method</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>contains(s)</code></td>
|
||||
<td>Returns true if the string contains <code>s</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>startsWith(s)</code></td>
|
||||
<td>Returns true if the string starts with <code>s</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>endsWith(s)</code></td>
|
||||
<td>Returns true if the string ends with <code>s</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>indexOf(s)</code></td>
|
||||
<td>Returns the byte index of <code>s</code>, or -1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>indexOf(s, start)</code></td>
|
||||
<td>Returns the byte index of <code>s</code> starting from <code>start</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>split(delim)</code></td>
|
||||
<td>Splits by delimiter, returns a list</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>replace(from, to)</code></td>
|
||||
<td>Replaces all occurrences of <code>from</code> with <code>to</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>trim()</code></td>
|
||||
<td>Removes leading and trailing whitespace</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>trimStart()</code></td>
|
||||
<td>Removes leading whitespace</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>trimEnd()</code></td>
|
||||
<td>Removes trailing whitespace</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>bytes</code></td>
|
||||
<td>Returns a sequence of byte values</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>codePoints</code></td>
|
||||
<td>Returns a sequence of code point values</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>count</code></td>
|
||||
<td>Number of code points in the string</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isEmpty</code></td>
|
||||
<td>Returns true if the string has no characters</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>*(n)</code></td>
|
||||
<td>Repeats the string <code>n</code> times</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>String is a core type available globally. No <code>import</code> statement is needed. All string methods operate on ASCII characters. Multi-byte UTF-8 characters are preserved but case conversion applies only to ASCII letters (a-z, A-Z).</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,90 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "subprocess" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "subprocess"}] %}
|
||||
{% set prev_page = {"url": "api/sqlite.html", "title": "sqlite"} %}
|
||||
{% set next_page = {"url": "api/sysinfo.html", "title": "sysinfo"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>subprocess</h1>
|
||||
|
||||
<p>The <code>subprocess</code> module allows running external commands and capturing their output.</p>
|
||||
|
||||
<pre><code>import "subprocess" for Subprocess</code></pre>
|
||||
|
||||
<h2>Subprocess Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Subprocess</h3>
|
||||
<p>External process execution</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Subprocess.run</span>(<span class="param">command</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Runs a command and waits for it to complete.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">command</span> <span class="param-type">(List)</span> - Command and arguments as a list</li>
|
||||
<li><span class="returns">Returns:</span> Map with "stdout", "stderr", and "exitCode"</li>
|
||||
</ul>
|
||||
<pre><code>var result = Subprocess.run(["ls", "-la"])
|
||||
System.print("Exit code: %(result["exitCode"])")
|
||||
System.print("Output: %(result["stdout"])")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Subprocess.run</span>(<span class="param">command</span>, <span class="param">input</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Runs a command with input data provided to stdin.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">command</span> <span class="param-type">(List)</span> - Command and arguments</li>
|
||||
<li><span class="param-name">input</span> <span class="param-type">(String)</span> - Input to send to stdin</li>
|
||||
</ul>
|
||||
<pre><code>var result = Subprocess.run(["cat"], "Hello, World!")
|
||||
System.print(result["stdout"]) // Hello, World!</code></pre>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Running Commands</h3>
|
||||
<pre><code>import "subprocess" for Subprocess
|
||||
|
||||
var result = Subprocess.run(["echo", "Hello"])
|
||||
System.print(result["stdout"]) // Hello
|
||||
|
||||
var files = Subprocess.run(["ls", "-la", "/tmp"])
|
||||
System.print(files["stdout"])</code></pre>
|
||||
|
||||
<h3>Checking Exit Codes</h3>
|
||||
<pre><code>import "subprocess" for Subprocess
|
||||
|
||||
var result = Subprocess.run(["grep", "pattern", "file.txt"])
|
||||
if (result["exitCode"] == 0) {
|
||||
System.print("Found: %(result["stdout"])")
|
||||
} else {
|
||||
System.print("Not found or error")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Processing Data</h3>
|
||||
<pre><code>import "subprocess" for Subprocess
|
||||
import "json" for Json
|
||||
|
||||
var result = Subprocess.run(["curl", "-s", "https://api.example.com/data"])
|
||||
if (result["exitCode"] == 0) {
|
||||
var data = Json.parse(result["stdout"])
|
||||
System.print(data)
|
||||
}</code></pre>
|
||||
|
||||
<h3>Piping Data</h3>
|
||||
<pre><code>import "subprocess" for Subprocess
|
||||
|
||||
var input = "line1\nline2\nline3"
|
||||
var result = Subprocess.run(["wc", "-l"], input)
|
||||
System.print("Lines: %(result["stdout"].trim())")</code></pre>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Commands are not executed through a shell. Use explicit command and argument lists, not shell command strings.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,244 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "sysinfo" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "sysinfo"}] %}
|
||||
{% set prev_page = {"url": "api/subprocess.html", "title": "subprocess"} %}
|
||||
{% set next_page = {"url": "api/tempfile.html", "title": "tempfile"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>sysinfo</h1>
|
||||
|
||||
<p>The <code>sysinfo</code> module provides system information including CPU details, memory usage, uptime, and network interfaces. All values are retrieved from libuv.</p>
|
||||
|
||||
<pre><code>import "sysinfo" for SysInfo</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#sysinfo-class">SysInfo Class</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="sysinfo-class">SysInfo Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>SysInfo</h3>
|
||||
<p>System information properties</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.cpuInfo</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns a list of maps containing CPU information. Each map includes <code>model</code>, <code>speed</code>, and <code>times</code> (with <code>user</code>, <code>nice</code>, <code>sys</code>, <code>idle</code>, <code>irq</code>).</p>
|
||||
<pre><code>var cpus = SysInfo.cpuInfo
|
||||
for (cpu in cpus) {
|
||||
System.print("Model: %(cpu["model"])")
|
||||
System.print("Speed: %(cpu["speed"]) MHz")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.cpuCount</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the number of CPUs/cores available on the system.</p>
|
||||
<pre><code>System.print("CPU count: %(SysInfo.cpuCount)")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.loadAverage</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>Returns the system load averages as a list of three numbers: 1-minute, 5-minute, and 15-minute averages. On Windows, returns <code>[0, 0, 0]</code>.</p>
|
||||
<pre><code>var load = SysInfo.loadAverage
|
||||
System.print("Load: %(load[0]) %(load[1]) %(load[2])")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.totalMemory</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the total system memory in bytes.</p>
|
||||
<pre><code>var totalMB = SysInfo.totalMemory / 1024 / 1024
|
||||
System.print("Total memory: %(totalMB) MB")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.freeMemory</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the free system memory in bytes.</p>
|
||||
<pre><code>var freeMB = SysInfo.freeMemory / 1024 / 1024
|
||||
System.print("Free memory: %(freeMB) MB")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.uptime</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the system uptime in seconds.</p>
|
||||
<pre><code>var hours = (SysInfo.uptime / 3600).floor
|
||||
System.print("Uptime: %(hours) hours")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.hostname</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the system hostname.</p>
|
||||
<pre><code>System.print("Hostname: %(SysInfo.hostname)")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.networkInterfaces</span> → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Returns a map of network interfaces. Each key is an interface name, and each value is a list of address maps containing <code>address</code>, <code>netmask</code>, <code>family</code> (IPv4 or IPv6), <code>internal</code>, and <code>mac</code>.</p>
|
||||
<pre><code>var interfaces = SysInfo.networkInterfaces
|
||||
for (name in interfaces.keys) {
|
||||
System.print("Interface: %(name)")
|
||||
for (addr in interfaces[name]) {
|
||||
System.print(" %(addr["family"]): %(addr["address"])")
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.hrtime</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns a high-resolution time value in nanoseconds. Useful for precise timing measurements.</p>
|
||||
<pre><code>var start = SysInfo.hrtime
|
||||
// ... do some work ...
|
||||
var elapsed = SysInfo.hrtime - start
|
||||
System.print("Elapsed: %(elapsed / 1000000) ms")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.residentMemory</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the resident set size (RSS) of the current process in bytes.</p>
|
||||
<pre><code>var rssMB = SysInfo.residentMemory / 1024 / 1024
|
||||
System.print("Process RSS: %(rssMB) MB")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">SysInfo.constrainedMemory</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the memory limit for the process in bytes (e.g., cgroup limit). Returns 0 if no limit is set.</p>
|
||||
<pre><code>var limit = SysInfo.constrainedMemory
|
||||
if (limit > 0) {
|
||||
System.print("Memory limit: %(limit / 1024 / 1024) MB")
|
||||
} else {
|
||||
System.print("No memory limit set")
|
||||
}</code></pre>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>System Overview</h3>
|
||||
<pre><code>import "sysinfo" for SysInfo
|
||||
|
||||
System.print("=== System Information ===")
|
||||
System.print("Hostname: %(SysInfo.hostname)")
|
||||
System.print("CPUs: %(SysInfo.cpuCount)")
|
||||
System.print("")
|
||||
|
||||
System.print("=== Memory ===")
|
||||
var totalGB = (SysInfo.totalMemory / 1024 / 1024 / 1024 * 100).floor / 100
|
||||
var freeGB = (SysInfo.freeMemory / 1024 / 1024 / 1024 * 100).floor / 100
|
||||
var usedPercent = ((1 - SysInfo.freeMemory / SysInfo.totalMemory) * 100).floor
|
||||
System.print("Total: %(totalGB) GB")
|
||||
System.print("Free: %(freeGB) GB")
|
||||
System.print("Used: %(usedPercent)\%")
|
||||
System.print("")
|
||||
|
||||
System.print("=== Load Average ===")
|
||||
var load = SysInfo.loadAverage
|
||||
System.print("1 min: %(load[0])")
|
||||
System.print("5 min: %(load[1])")
|
||||
System.print("15 min: %(load[2])")
|
||||
System.print("")
|
||||
|
||||
System.print("=== Uptime ===")
|
||||
var uptime = SysInfo.uptime
|
||||
var days = (uptime / 86400).floor
|
||||
var hours = ((uptime % 86400) / 3600).floor
|
||||
var minutes = ((uptime % 3600) / 60).floor
|
||||
System.print("%(days) days, %(hours) hours, %(minutes) minutes")</code></pre>
|
||||
|
||||
<h3>CPU Information</h3>
|
||||
<pre><code>import "sysinfo" for SysInfo
|
||||
|
||||
var cpus = SysInfo.cpuInfo
|
||||
System.print("CPU Information:")
|
||||
System.print("================")
|
||||
|
||||
var i = 0
|
||||
for (cpu in cpus) {
|
||||
System.print("CPU %(i): %(cpu["model"])")
|
||||
System.print(" Speed: %(cpu["speed"]) MHz")
|
||||
var times = cpu["times"]
|
||||
var total = times["user"] + times["nice"] + times["sys"] + times["idle"] + times["irq"]
|
||||
var idle = (times["idle"] / total * 100).floor
|
||||
System.print(" Idle: %(idle)\%")
|
||||
i = i + 1
|
||||
}</code></pre>
|
||||
|
||||
<h3>Network Interfaces</h3>
|
||||
<pre><code>import "sysinfo" for SysInfo
|
||||
|
||||
var interfaces = SysInfo.networkInterfaces
|
||||
|
||||
System.print("Network Interfaces:")
|
||||
System.print("===================")
|
||||
|
||||
for (name in interfaces.keys) {
|
||||
var addrs = interfaces[name]
|
||||
System.print("%(name):")
|
||||
for (addr in addrs) {
|
||||
if (!addr["internal"]) {
|
||||
System.print(" %(addr["family"]): %(addr["address"])")
|
||||
if (addr["mac"] != "00:00:00:00:00:00") {
|
||||
System.print(" MAC: %(addr["mac"])")
|
||||
}
|
||||
}
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Performance Timing</h3>
|
||||
<pre><code>import "sysinfo" for SysInfo
|
||||
|
||||
var measure = Fn.new { |name, fn|
|
||||
var start = SysInfo.hrtime
|
||||
fn.call()
|
||||
var elapsed = SysInfo.hrtime - start
|
||||
System.print("%(name): %(elapsed / 1000000) ms")
|
||||
}
|
||||
|
||||
measure.call("String concatenation") {
|
||||
var s = ""
|
||||
for (i in 0...1000) {
|
||||
s = s + "x"
|
||||
}
|
||||
}
|
||||
|
||||
measure.call("List operations") {
|
||||
var list = []
|
||||
for (i in 0...10000) {
|
||||
list.add(i)
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Memory Monitoring</h3>
|
||||
<pre><code>import "sysinfo" for SysInfo
|
||||
import "timer" for Timer
|
||||
|
||||
System.print("Memory Monitor (press Ctrl+C to stop)")
|
||||
System.print("=====================================")
|
||||
|
||||
while (true) {
|
||||
var totalMB = (SysInfo.totalMemory / 1024 / 1024).floor
|
||||
var freeMB = (SysInfo.freeMemory / 1024 / 1024).floor
|
||||
var rssMB = (SysInfo.residentMemory / 1024 / 1024).floor
|
||||
var usedPercent = ((1 - SysInfo.freeMemory / SysInfo.totalMemory) * 100).floor
|
||||
|
||||
System.print("System: %(freeMB)/%(totalMB) MB free (%(usedPercent)\% used) | Process RSS: %(rssMB) MB")
|
||||
Timer.sleep(1000)
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Load average values are not available on Windows and will return <code>[0, 0, 0]</code>.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Use <code>SysInfo.hrtime</code> for precise performance measurements. It provides nanosecond resolution and is not affected by system clock adjustments.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,270 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "tempfile" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "tempfile"}] %}
|
||||
{% set prev_page = {"url": "api/sysinfo.html", "title": "sysinfo"} %}
|
||||
{% set next_page = {"url": "api/timer.html", "title": "timer"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>tempfile</h1>
|
||||
|
||||
<p>The <code>tempfile</code> module provides utilities for creating temporary files and directories. It mirrors Python's <code>tempfile</code> API with three classes: <code>TempFile</code> for low-level operations, <code>NamedTemporaryFile</code> for temporary files with automatic cleanup, and <code>TemporaryDirectory</code> for temporary directories with recursive cleanup.</p>
|
||||
|
||||
<pre><code>import "tempfile" for TempFile, NamedTemporaryFile, TemporaryDirectory</code></pre>
|
||||
|
||||
<h2>TempFile Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>TempFile</h3>
|
||||
<p>Low-level temporary file and directory utilities</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">TempFile.tempdir</span> → <span class="type">String|Null</span>
|
||||
</div>
|
||||
<p>Gets or sets a global override for the temporary directory. When set, <code>gettempdir()</code> returns this value instead of checking environment variables.</p>
|
||||
<pre><code>TempFile.tempdir = "/my/custom/tmp"
|
||||
System.print(TempFile.gettempdir()) // /my/custom/tmp
|
||||
TempFile.tempdir = null // Reset to default</code></pre>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">TempFile.gettempdir</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the resolved temporary directory path. Checks in order: the <code>tempdir</code> override, then <code>TMPDIR</code>, <code>TEMP</code>, <code>TMP</code> environment variables, and falls back to <code>/tmp</code> on POSIX or <code>C:\Temp</code> on Windows.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">TempFile.gettempprefix</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the default prefix for temporary file names: <code>"tmp"</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">TempFile.mktemp</span>() → <span class="type">String</span><br>
|
||||
<span class="method-name">TempFile.mktemp</span>(<span class="param">suffix</span>) → <span class="type">String</span><br>
|
||||
<span class="method-name">TempFile.mktemp</span>(<span class="param">suffix</span>, <span class="param">prefix</span>) → <span class="type">String</span><br>
|
||||
<span class="method-name">TempFile.mktemp</span>(<span class="param">suffix</span>, <span class="param">prefix</span>, <span class="param">dir</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Generates a unique temporary file path without creating any file. The generated name consists of the prefix, 8 random hexadecimal characters, and the suffix.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">suffix</span> <span class="param-type">(String)</span> - Suffix for the filename (default: <code>""</code>)</li>
|
||||
<li><span class="param-name">prefix</span> <span class="param-type">(String)</span> - Prefix for the filename (default: <code>"tmp"</code>)</li>
|
||||
<li><span class="param-name">dir</span> <span class="param-type">(String)</span> - Directory for the path (default: <code>gettempdir()</code>)</li>
|
||||
<li><span class="returns">Returns:</span> A file path string (file is not created)</li>
|
||||
</ul>
|
||||
<pre><code>var name = TempFile.mktemp(".txt", "data_")
|
||||
System.print(name) // e.g., /tmp/data_a1b2c3d4.txt</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">TempFile.mkstemp</span>() → <span class="type">String</span><br>
|
||||
<span class="method-name">TempFile.mkstemp</span>(<span class="param">suffix</span>) → <span class="type">String</span><br>
|
||||
<span class="method-name">TempFile.mkstemp</span>(<span class="param">suffix</span>, <span class="param">prefix</span>) → <span class="type">String</span><br>
|
||||
<span class="method-name">TempFile.mkstemp</span>(<span class="param">suffix</span>, <span class="param">prefix</span>, <span class="param">dir</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Creates a temporary file atomically using exclusive creation flags (<code>O_EXCL</code>), preventing race conditions. Retries up to 100 times on name collisions.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">suffix</span> <span class="param-type">(String)</span> - Suffix for the filename (default: <code>""</code>)</li>
|
||||
<li><span class="param-name">prefix</span> <span class="param-type">(String)</span> - Prefix for the filename (default: <code>"tmp"</code>)</li>
|
||||
<li><span class="param-name">dir</span> <span class="param-type">(String)</span> - Directory for the file (default: <code>gettempdir()</code>)</li>
|
||||
<li><span class="returns">Returns:</span> The path of the newly created file</li>
|
||||
</ul>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
var path = TempFile.mkstemp(".dat", "work_")
|
||||
System.print(path) // e.g., /tmp/work_e5f6a7b8.dat
|
||||
File.delete(path) // Caller must clean up</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">TempFile.mkdtemp</span>() → <span class="type">String</span><br>
|
||||
<span class="method-name">TempFile.mkdtemp</span>(<span class="param">suffix</span>) → <span class="type">String</span><br>
|
||||
<span class="method-name">TempFile.mkdtemp</span>(<span class="param">suffix</span>, <span class="param">prefix</span>) → <span class="type">String</span><br>
|
||||
<span class="method-name">TempFile.mkdtemp</span>(<span class="param">suffix</span>, <span class="param">prefix</span>, <span class="param">dir</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Creates a temporary directory. Retries up to 100 times on name collisions.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">suffix</span> <span class="param-type">(String)</span> - Suffix for the directory name (default: <code>""</code>)</li>
|
||||
<li><span class="param-name">prefix</span> <span class="param-type">(String)</span> - Prefix for the directory name (default: <code>"tmp"</code>)</li>
|
||||
<li><span class="param-name">dir</span> <span class="param-type">(String)</span> - Parent directory (default: <code>gettempdir()</code>)</li>
|
||||
<li><span class="returns">Returns:</span> The path of the newly created directory</li>
|
||||
</ul>
|
||||
<pre><code>import "io" for Directory
|
||||
|
||||
var dir = TempFile.mkdtemp("_work")
|
||||
System.print(dir) // e.g., /tmp/tmp9c0d1e2f_work
|
||||
Directory.delete(dir) // Caller must clean up</code></pre>
|
||||
|
||||
<h2>NamedTemporaryFile Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>NamedTemporaryFile</h3>
|
||||
<p>A temporary file with a visible name that is optionally deleted on close</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructors</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">NamedTemporaryFile.new</span>() → <span class="type">NamedTemporaryFile</span><br>
|
||||
<span class="method-name">NamedTemporaryFile.new</span>(<span class="param">suffix</span>) → <span class="type">NamedTemporaryFile</span><br>
|
||||
<span class="method-name">NamedTemporaryFile.new</span>(<span class="param">suffix</span>, <span class="param">prefix</span>) → <span class="type">NamedTemporaryFile</span><br>
|
||||
<span class="method-name">NamedTemporaryFile.new</span>(<span class="param">suffix</span>, <span class="param">prefix</span>, <span class="param">dir</span>) → <span class="type">NamedTemporaryFile</span><br>
|
||||
<span class="method-name">NamedTemporaryFile.new</span>(<span class="param">suffix</span>, <span class="param">prefix</span>, <span class="param">dir</span>, <span class="param">delete</span>) → <span class="type">NamedTemporaryFile</span>
|
||||
</div>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">suffix</span> <span class="param-type">(String)</span> - Suffix for the filename (default: <code>""</code>)</li>
|
||||
<li><span class="param-name">prefix</span> <span class="param-type">(String)</span> - Prefix for the filename (default: <code>"tmp"</code>)</li>
|
||||
<li><span class="param-name">dir</span> <span class="param-type">(String|Null)</span> - Directory for the file (default: <code>null</code>, uses <code>TempFile.gettempdir()</code>)</li>
|
||||
<li><span class="param-name">delete</span> <span class="param-type">(Bool)</span> - Whether to delete the file on close (default: <code>true</code>)</li>
|
||||
</ul>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.name</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The full path of the temporary file.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.path</span> → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>A <code>Path</code> object for the temporary file.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.delete</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the file will be deleted on close. Can be set.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.closed</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the file has been closed.</p>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.write</span>(<span class="param">content</span>)
|
||||
</div>
|
||||
<p>Writes string content to the file, replacing any existing content.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.read</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Reads and returns the file content as a string.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.close</span>()
|
||||
</div>
|
||||
<p>Closes the file. If <code>delete</code> is <code>true</code>, the file is deleted from disk.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.use</span>(<span class="param">fn</span>) → <span class="type">*</span>
|
||||
</div>
|
||||
<p>Executes <code>fn</code> with the file as argument and guarantees cleanup afterwards, even if an error occurs. Equivalent to Python's <code>with</code> statement.</p>
|
||||
<pre><code>NamedTemporaryFile.new(".txt").use {|f|
|
||||
f.write("temporary data")
|
||||
System.print(f.read())
|
||||
}
|
||||
// File is automatically deleted here</code></pre>
|
||||
|
||||
<h2>TemporaryDirectory Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>TemporaryDirectory</h3>
|
||||
<p>A temporary directory with recursive cleanup support</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructors</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">TemporaryDirectory.new</span>() → <span class="type">TemporaryDirectory</span><br>
|
||||
<span class="method-name">TemporaryDirectory.new</span>(<span class="param">suffix</span>) → <span class="type">TemporaryDirectory</span><br>
|
||||
<span class="method-name">TemporaryDirectory.new</span>(<span class="param">suffix</span>, <span class="param">prefix</span>) → <span class="type">TemporaryDirectory</span><br>
|
||||
<span class="method-name">TemporaryDirectory.new</span>(<span class="param">suffix</span>, <span class="param">prefix</span>, <span class="param">dir</span>) → <span class="type">TemporaryDirectory</span><br>
|
||||
<span class="method-name">TemporaryDirectory.new</span>(<span class="param">suffix</span>, <span class="param">prefix</span>, <span class="param">dir</span>, <span class="param">delete</span>) → <span class="type">TemporaryDirectory</span>
|
||||
</div>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">suffix</span> <span class="param-type">(String)</span> - Suffix for the directory name (default: <code>""</code>)</li>
|
||||
<li><span class="param-name">prefix</span> <span class="param-type">(String)</span> - Prefix for the directory name (default: <code>"tmp"</code>)</li>
|
||||
<li><span class="param-name">dir</span> <span class="param-type">(String|Null)</span> - Parent directory (default: <code>null</code>, uses <code>TempFile.gettempdir()</code>)</li>
|
||||
<li><span class="param-name">delete</span> <span class="param-type">(Bool)</span> - Whether to delete the directory on cleanup (default: <code>true</code>)</li>
|
||||
</ul>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.name</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The full path of the temporary directory.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.path</span> → <span class="type">Path</span>
|
||||
</div>
|
||||
<p>A <code>Path</code> object for the temporary directory.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.delete</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the directory will be deleted on cleanup. Can be set.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.closed</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether the directory has been cleaned up.</p>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.cleanup</span>()
|
||||
</div>
|
||||
<p>Removes the directory and all its contents recursively (using <code>Path.rmtree()</code>). If <code>delete</code> is <code>false</code>, the directory is not removed.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">.use</span>(<span class="param">fn</span>) → <span class="type">*</span>
|
||||
</div>
|
||||
<p>Executes <code>fn</code> with the directory as argument and guarantees cleanup afterwards, even if an error occurs.</p>
|
||||
<pre><code>TemporaryDirectory.new().use {|d|
|
||||
var path = d.name + "/data.txt"
|
||||
// Create files, do work...
|
||||
}
|
||||
// Directory and all contents automatically removed</code></pre>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Processing Files Safely</h3>
|
||||
<pre><code>import "tempfile" for NamedTemporaryFile
|
||||
import "pathlib" for Path
|
||||
|
||||
NamedTemporaryFile.new(".csv", "report_").use {|tmp|
|
||||
tmp.write("name,value\nalice,42\nbob,17")
|
||||
var data = tmp.read()
|
||||
System.print("Processing %(tmp.name)")
|
||||
System.print(data)
|
||||
}</code></pre>
|
||||
|
||||
<h3>Working Directory for Build Output</h3>
|
||||
<pre><code>import "tempfile" for TemporaryDirectory
|
||||
import "pathlib" for Path
|
||||
|
||||
TemporaryDirectory.new("_build").use {|build|
|
||||
var src = Path.new(build.name) / "output.txt"
|
||||
src.writeText("Build artifact")
|
||||
System.print("Build dir: %(build.name)")
|
||||
}
|
||||
// Build directory cleaned up automatically</code></pre>
|
||||
|
||||
<h3>Persistent Temporary Files</h3>
|
||||
<pre><code>import "tempfile" for NamedTemporaryFile
|
||||
|
||||
var tmp = NamedTemporaryFile.new(".log", "app_", null, false)
|
||||
tmp.write("Application started")
|
||||
tmp.close()
|
||||
// File persists at tmp.name after close
|
||||
System.print("Log file: %(tmp.name)")</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>File creation via <code>mkstemp</code> uses exclusive creation flags (<code>O_EXCL</code>) for atomic file creation, preventing race conditions between checking for existence and creating the file. Random suffixes are generated using <code>Crypto.randomBytes</code> for cryptographic quality randomness.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,227 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "timer" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "timer"}] %}
|
||||
{% set prev_page = {"url": "api/tempfile.html", "title": "tempfile"} %}
|
||||
{% set next_page = {"url": "api/tls.html", "title": "tls"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>timer</h1>
|
||||
|
||||
<p>The <code>timer</code> module provides timing functionality for delays, intervals, and immediate execution.</p>
|
||||
|
||||
<pre><code>import "timer" for Timer, TimerHandle</code></pre>
|
||||
|
||||
<h2>Timer Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Timer</h3>
|
||||
<p>Timer and delay functionality</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Timer.sleep</span>(<span class="param">milliseconds</span>)
|
||||
</div>
|
||||
<p>Pauses execution for the specified duration. The fiber suspends and other operations can proceed.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">milliseconds</span> <span class="param-type">(Num)</span> - Duration to sleep in milliseconds</li>
|
||||
</ul>
|
||||
<pre><code>System.print("Starting...")
|
||||
Timer.sleep(1000) // Wait 1 second
|
||||
System.print("Done!")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Timer.interval</span>(<span class="param">milliseconds</span>, <span class="param">fn</span>) → <span class="type">TimerHandle</span>
|
||||
</div>
|
||||
<p>Creates a repeating timer that calls the callback function at the specified interval. Returns a TimerHandle that can be used to stop the interval.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">milliseconds</span> <span class="param-type">(Num)</span> - Interval between calls in milliseconds</li>
|
||||
<li><span class="param-name">fn</span> <span class="param-type">(Fn)</span> - Callback function to execute (no arguments)</li>
|
||||
<li><span class="returns">Returns:</span> TimerHandle for controlling the interval</li>
|
||||
</ul>
|
||||
<pre><code>var count = 0
|
||||
var handle = Timer.interval(1000) {
|
||||
count = count + 1
|
||||
System.print("Tick %(count)")
|
||||
if (count >= 5) {
|
||||
handle.stop()
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Timer.immediate</span>(<span class="param">fn</span>)
|
||||
</div>
|
||||
<p>Schedules a function to run on the next iteration of the event loop. Useful for deferring execution without blocking.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">fn</span> <span class="param-type">(Fn)</span> - Callback function to execute (no arguments)</li>
|
||||
</ul>
|
||||
<pre><code>System.print("Before")
|
||||
Timer.immediate {
|
||||
System.print("Deferred execution")
|
||||
}
|
||||
System.print("After")
|
||||
// Output: Before, After, Deferred execution</code></pre>
|
||||
|
||||
<h2>TimerHandle Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>TimerHandle</h3>
|
||||
<p>Handle for controlling interval timers</p>
|
||||
</div>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">stop</span>()
|
||||
</div>
|
||||
<p>Stops the interval timer. After calling stop, the callback will no longer be invoked.</p>
|
||||
<pre><code>handle.stop()</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isActive</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Returns true if the interval timer is still active.</p>
|
||||
<pre><code>if (handle.isActive) {
|
||||
System.print("Timer is running")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Basic Delay</h3>
|
||||
<pre><code>import "timer" for Timer
|
||||
|
||||
System.print("Starting...")
|
||||
Timer.sleep(2000)
|
||||
System.print("2 seconds later...")</code></pre>
|
||||
|
||||
<h3>Polling Loop</h3>
|
||||
<pre><code>import "timer" for Timer
|
||||
import "http" for Http
|
||||
|
||||
var checkStatus = Fn.new {
|
||||
var response = Http.get("https://api.example.com/status")
|
||||
return response.json["ready"]
|
||||
}
|
||||
|
||||
while (!checkStatus.call()) {
|
||||
System.print("Waiting...")
|
||||
Timer.sleep(5000) // Check every 5 seconds
|
||||
}
|
||||
|
||||
System.print("Ready!")</code></pre>
|
||||
|
||||
<h3>Rate Limiting</h3>
|
||||
<pre><code>import "timer" for Timer
|
||||
import "http" for Http
|
||||
|
||||
var urls = [
|
||||
"https://api.example.com/1",
|
||||
"https://api.example.com/2",
|
||||
"https://api.example.com/3"
|
||||
]
|
||||
|
||||
for (url in urls) {
|
||||
var response = Http.get(url)
|
||||
System.print("%(url): %(response.statusCode)")
|
||||
Timer.sleep(1000) // 1 second between requests
|
||||
}</code></pre>
|
||||
|
||||
<h3>Timeout Pattern</h3>
|
||||
<pre><code>import "timer" for Timer
|
||||
import "datetime" for DateTime, Duration
|
||||
|
||||
var start = DateTime.now()
|
||||
var timeout = Duration.fromSeconds(30)
|
||||
|
||||
while (true) {
|
||||
var elapsed = DateTime.now() - start
|
||||
if (elapsed.seconds >= timeout.seconds) {
|
||||
System.print("Timeout!")
|
||||
break
|
||||
}
|
||||
|
||||
// Do work...
|
||||
Timer.sleep(100)
|
||||
}</code></pre>
|
||||
|
||||
<h3>Animation/Progress</h3>
|
||||
<pre><code>import "timer" for Timer
|
||||
|
||||
var frames = ["-", "\\", "|", "/"]
|
||||
var i = 0
|
||||
|
||||
for (step in 1..20) {
|
||||
System.write("\rProcessing %(frames[i]) ")
|
||||
i = (i + 1) % 4
|
||||
Timer.sleep(100)
|
||||
}
|
||||
System.print("\rDone! ")</code></pre>
|
||||
|
||||
<h3>Interval Timer</h3>
|
||||
<pre><code>import "timer" for Timer, TimerHandle
|
||||
|
||||
var seconds = 0
|
||||
var handle = Timer.interval(1000) {
|
||||
seconds = seconds + 1
|
||||
System.print("Elapsed: %(seconds) seconds")
|
||||
}
|
||||
|
||||
Timer.sleep(5000)
|
||||
handle.stop()
|
||||
System.print("Timer stopped")</code></pre>
|
||||
|
||||
<h3>Periodic Status Updates</h3>
|
||||
<pre><code>import "timer" for Timer, TimerHandle
|
||||
import "sysinfo" for SysInfo
|
||||
|
||||
var handle = Timer.interval(2000) {
|
||||
var freeMB = (SysInfo.freeMemory / 1024 / 1024).floor
|
||||
var load = SysInfo.loadAverage[0]
|
||||
System.print("Memory: %(freeMB) MB free | Load: %(load)")
|
||||
}
|
||||
|
||||
System.print("Monitoring system (runs for 10 seconds)...")
|
||||
Timer.sleep(10000)
|
||||
handle.stop()</code></pre>
|
||||
|
||||
<h3>Immediate Execution</h3>
|
||||
<pre><code>import "timer" for Timer
|
||||
|
||||
System.print("1. Synchronous")
|
||||
|
||||
Timer.immediate {
|
||||
System.print("3. Immediate callback")
|
||||
}
|
||||
|
||||
System.print("2. Still synchronous")
|
||||
|
||||
Timer.sleep(100)</code></pre>
|
||||
|
||||
<h3>Self-Stopping Interval</h3>
|
||||
<pre><code>import "timer" for Timer, TimerHandle
|
||||
|
||||
var count = 0
|
||||
var handle = Timer.interval(500) {
|
||||
count = count + 1
|
||||
System.print("Count: %(count)")
|
||||
if (count >= 10) {
|
||||
System.print("Stopping at %(count)")
|
||||
handle.stop()
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Timer.sleep is non-blocking at the event loop level. The current fiber suspends, but other scheduled operations can continue.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Use <code>Timer.interval</code> for recurring tasks like heartbeats, polling, or animations. The returned handle allows you to stop the interval from within the callback itself.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,153 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "tls" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "tls"}] %}
|
||||
{% set prev_page = {"url": "api/timer.html", "title": "timer"} %}
|
||||
{% set next_page = {"url": "api/udp.html", "title": "udp"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>tls</h1>
|
||||
|
||||
<p>The <code>tls</code> module provides SSL/TLS socket support for secure network connections. It uses OpenSSL for encryption and is used internally by the <code>http</code> module for HTTPS connections.</p>
|
||||
|
||||
<pre><code>import "tls" for TlsSocket</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#tlssocket-class">TlsSocket Class</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="tlssocket-class">TlsSocket Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>TlsSocket</h3>
|
||||
<p>SSL/TLS encrypted socket connection</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">TlsSocket.connect</span>(<span class="param">host</span>, <span class="param">port</span>, <span class="param">hostname</span>) → <span class="type">TlsSocket</span>
|
||||
</div>
|
||||
<p>Establishes a TLS connection to a remote server.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">host</span> <span class="param-type">(String)</span> - IP address to connect to</li>
|
||||
<li><span class="param-name">port</span> <span class="param-type">(Num)</span> - Port number (typically 443 for HTTPS)</li>
|
||||
<li><span class="param-name">hostname</span> <span class="param-type">(String)</span> - Server hostname for SNI (Server Name Indication)</li>
|
||||
<li><span class="returns">Returns:</span> Connected TlsSocket instance</li>
|
||||
</ul>
|
||||
<pre><code>var socket = TlsSocket.connect("93.184.216.34", 443, "example.com")</code></pre>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">write</span>(<span class="param">text</span>)
|
||||
</div>
|
||||
<p>Writes data to the TLS connection. This is an async operation that blocks until the data is sent.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">text</span> <span class="param-type">(String)</span> - Data to send</li>
|
||||
</ul>
|
||||
<pre><code>socket.write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">read</span>() → <span class="type">String|null</span>
|
||||
</div>
|
||||
<p>Reads data from the TLS connection. Blocks until data is available. Returns null when the connection is closed.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="returns">Returns:</span> Data received as a string, or null if connection closed</li>
|
||||
</ul>
|
||||
<pre><code>var data = socket.read()
|
||||
if (data != null) {
|
||||
System.print(data)
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>()
|
||||
</div>
|
||||
<p>Closes the TLS connection and releases resources.</p>
|
||||
<pre><code>socket.close()</code></pre>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Basic HTTPS Request</h3>
|
||||
<pre><code>import "tls" for TlsSocket
|
||||
import "dns" for Dns
|
||||
|
||||
var host = "example.com"
|
||||
var ip = Dns.lookup(host)
|
||||
var socket = TlsSocket.connect(ip, 443, host)
|
||||
|
||||
socket.write("GET / HTTP/1.1\r\n")
|
||||
socket.write("Host: %(host)\r\n")
|
||||
socket.write("Connection: close\r\n")
|
||||
socket.write("\r\n")
|
||||
|
||||
var response = ""
|
||||
while (true) {
|
||||
var chunk = socket.read()
|
||||
if (chunk == null) break
|
||||
response = response + chunk
|
||||
}
|
||||
|
||||
socket.close()
|
||||
System.print(response)</code></pre>
|
||||
|
||||
<h3>Reading Until Complete</h3>
|
||||
<pre><code>import "tls" for TlsSocket
|
||||
import "dns" for Dns
|
||||
|
||||
var host = "api.example.com"
|
||||
var ip = Dns.lookup(host)
|
||||
var socket = TlsSocket.connect(ip, 443, host)
|
||||
|
||||
socket.write("GET /data HTTP/1.1\r\n")
|
||||
socket.write("Host: %(host)\r\n")
|
||||
socket.write("Accept: application/json\r\n")
|
||||
socket.write("Connection: close\r\n\r\n")
|
||||
|
||||
var buffer = ""
|
||||
while (true) {
|
||||
var data = socket.read()
|
||||
if (data == null) break
|
||||
buffer = buffer + data
|
||||
}
|
||||
|
||||
socket.close()
|
||||
|
||||
var bodyStart = buffer.indexOf("\r\n\r\n")
|
||||
if (bodyStart != -1) {
|
||||
var body = buffer[bodyStart + 4..-1]
|
||||
System.print("Response body: %(body)")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Using with DNS Resolution</h3>
|
||||
<pre><code>import "tls" for TlsSocket
|
||||
import "dns" for Dns
|
||||
|
||||
var hostname = "secure.example.com"
|
||||
|
||||
var ip = Dns.lookup(hostname, 4)
|
||||
System.print("Connecting to %(ip)")
|
||||
|
||||
var socket = TlsSocket.connect(ip, 443, hostname)
|
||||
socket.write("GET /secure-endpoint HTTP/1.1\r\nHost: %(hostname)\r\n\r\n")
|
||||
|
||||
var response = socket.read()
|
||||
System.print(response)
|
||||
|
||||
socket.close()</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>The <code>hostname</code> parameter is used for SNI (Server Name Indication), which is required when connecting to servers that host multiple domains on the same IP address. It should match the domain name in the server's certificate.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>For most use cases, consider using the higher-level <code>http</code> module which handles TLS connections, HTTP protocol details, and response parsing automatically.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,318 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "udp" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "udp"}] %}
|
||||
{% set prev_page = {"url": "api/tls.html", "title": "tls"} %}
|
||||
{% set next_page = {"url": "api/uuid.html", "title": "uuid"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>udp</h1>
|
||||
|
||||
<p>The <code>udp</code> module provides UDP (User Datagram Protocol) socket functionality for connectionless networking. UDP is useful for applications requiring fast, lightweight communication without the overhead of TCP connection management.</p>
|
||||
|
||||
<pre><code>import "udp" for UdpSocket, UdpMessage</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#udpsocket-class">UdpSocket Class</a></li>
|
||||
<li><a href="#udpmessage-class">UdpMessage Class</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="udpsocket-class">UdpSocket Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>UdpSocket</h3>
|
||||
<p>UDP datagram socket for sending and receiving messages</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructor</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">UdpSocket.new</span>() → <span class="type">UdpSocket</span>
|
||||
</div>
|
||||
<p>Creates a new UDP socket.</p>
|
||||
<pre><code>var socket = UdpSocket.new()</code></pre>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">bind</span>(<span class="param">host</span>, <span class="param">port</span>)
|
||||
</div>
|
||||
<p>Binds the socket to a local address and port. Required before receiving messages.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">host</span> <span class="param-type">(String)</span> - Local address to bind (e.g., "0.0.0.0" for all interfaces)</li>
|
||||
<li><span class="param-name">port</span> <span class="param-type">(Num)</span> - Port number to bind</li>
|
||||
</ul>
|
||||
<pre><code>socket.bind("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">send</span>(<span class="param">data</span>, <span class="param">host</span>, <span class="param">port</span>)
|
||||
</div>
|
||||
<p>Sends a datagram to the specified address. Async operation.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(String)</span> - Data to send</li>
|
||||
<li><span class="param-name">host</span> <span class="param-type">(String)</span> - Destination hostname or IP</li>
|
||||
<li><span class="param-name">port</span> <span class="param-type">(Num)</span> - Destination port</li>
|
||||
</ul>
|
||||
<pre><code>socket.send("Hello!", "192.168.1.100", 8080)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">receive</span>() → <span class="type">UdpMessage</span>
|
||||
</div>
|
||||
<p>Receives a datagram. Blocks until data arrives. Returns a UdpMessage containing the data and sender information.</p>
|
||||
<pre><code>var msg = socket.receive()
|
||||
System.print("From %(msg.address):%(msg.port): %(msg.data)")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>()
|
||||
</div>
|
||||
<p>Closes the socket.</p>
|
||||
<pre><code>socket.close()</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">setBroadcast</span>(<span class="param">enabled</span>)
|
||||
</div>
|
||||
<p>Enables or disables broadcast mode. When enabled, the socket can send to broadcast addresses.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">enabled</span> <span class="param-type">(Bool)</span> - True to enable broadcast</li>
|
||||
</ul>
|
||||
<pre><code>socket.setBroadcast(true)
|
||||
socket.send("Broadcast message", "255.255.255.255", 8080)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">setMulticastTTL</span>(<span class="param">ttl</span>)
|
||||
</div>
|
||||
<p>Sets the time-to-live for multicast packets.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">ttl</span> <span class="param-type">(Num)</span> - TTL value (1-255)</li>
|
||||
</ul>
|
||||
<pre><code>socket.setMulticastTTL(64)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">setMulticastLoopback</span>(<span class="param">enabled</span>)
|
||||
</div>
|
||||
<p>Enables or disables multicast loopback. When enabled, the socket receives its own multicast messages.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">enabled</span> <span class="param-type">(Bool)</span> - True to enable loopback</li>
|
||||
</ul>
|
||||
<pre><code>socket.setMulticastLoopback(false)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">joinMulticast</span>(<span class="param">group</span>)
|
||||
</div>
|
||||
<p>Joins a multicast group on the default interface.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">group</span> <span class="param-type">(String)</span> - Multicast group address (e.g., "239.255.0.1")</li>
|
||||
</ul>
|
||||
<pre><code>socket.joinMulticast("239.255.0.1")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">joinMulticast</span>(<span class="param">group</span>, <span class="param">iface</span>)
|
||||
</div>
|
||||
<p>Joins a multicast group on a specific interface.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">group</span> <span class="param-type">(String)</span> - Multicast group address</li>
|
||||
<li><span class="param-name">iface</span> <span class="param-type">(String)</span> - Local interface address to join from</li>
|
||||
</ul>
|
||||
<pre><code>socket.joinMulticast("239.255.0.1", "192.168.1.100")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">leaveMulticast</span>(<span class="param">group</span>)
|
||||
</div>
|
||||
<p>Leaves a multicast group on the default interface.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">group</span> <span class="param-type">(String)</span> - Multicast group address</li>
|
||||
</ul>
|
||||
<pre><code>socket.leaveMulticast("239.255.0.1")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">leaveMulticast</span>(<span class="param">group</span>, <span class="param">iface</span>)
|
||||
</div>
|
||||
<p>Leaves a multicast group on a specific interface.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">group</span> <span class="param-type">(String)</span> - Multicast group address</li>
|
||||
<li><span class="param-name">iface</span> <span class="param-type">(String)</span> - Local interface address</li>
|
||||
</ul>
|
||||
<pre><code>socket.leaveMulticast("239.255.0.1", "192.168.1.100")</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">localAddress</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Returns the local address the socket is bound to.</p>
|
||||
<pre><code>System.print("Bound to: %(socket.localAddress)")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">localPort</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Returns the local port the socket is bound to.</p>
|
||||
<pre><code>System.print("Port: %(socket.localPort)")</code></pre>
|
||||
|
||||
<h2 id="udpmessage-class">UdpMessage Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>UdpMessage</h3>
|
||||
<p>Represents a received UDP datagram</p>
|
||||
</div>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">data</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The data contained in the message.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">address</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The IP address of the sender.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">port</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>The port number of the sender.</p>
|
||||
|
||||
<pre><code>var msg = socket.receive()
|
||||
System.print("Data: %(msg.data)")
|
||||
System.print("From: %(msg.address):%(msg.port)")</code></pre>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Simple UDP Server</h3>
|
||||
<pre><code>import "udp" for UdpSocket
|
||||
|
||||
var socket = UdpSocket.new()
|
||||
socket.bind("0.0.0.0", 8080)
|
||||
|
||||
System.print("UDP server listening on port 8080")
|
||||
|
||||
while (true) {
|
||||
var msg = socket.receive()
|
||||
System.print("Received from %(msg.address):%(msg.port): %(msg.data)")
|
||||
|
||||
socket.send("Echo: %(msg.data)", msg.address, msg.port)
|
||||
}</code></pre>
|
||||
|
||||
<h3>Simple UDP Client</h3>
|
||||
<pre><code>import "udp" for UdpSocket
|
||||
|
||||
var socket = UdpSocket.new()
|
||||
socket.bind("0.0.0.0", 0)
|
||||
|
||||
socket.send("Hello, server!", "127.0.0.1", 8080)
|
||||
|
||||
var response = socket.receive()
|
||||
System.print("Server responded: %(response.data)")
|
||||
|
||||
socket.close()</code></pre>
|
||||
|
||||
<h3>Broadcast Discovery</h3>
|
||||
<pre><code>import "udp" for UdpSocket
|
||||
import "timer" for Timer
|
||||
|
||||
var socket = UdpSocket.new()
|
||||
socket.bind("0.0.0.0", 0)
|
||||
socket.setBroadcast(true)
|
||||
|
||||
System.print("Sending discovery broadcast...")
|
||||
socket.send("DISCOVER", "255.255.255.255", 9999)
|
||||
|
||||
System.print("Waiting for responses...")
|
||||
|
||||
var timeout = false
|
||||
var timeoutFiber = Fiber.new {
|
||||
Timer.sleep(3000)
|
||||
timeout = true
|
||||
}
|
||||
timeoutFiber.call()
|
||||
|
||||
while (!timeout) {
|
||||
var msg = socket.receive()
|
||||
System.print("Found device at %(msg.address): %(msg.data)")
|
||||
}
|
||||
|
||||
socket.close()</code></pre>
|
||||
|
||||
<h3>Multicast Group</h3>
|
||||
<pre><code>import "udp" for UdpSocket
|
||||
|
||||
var MULTICAST_GROUP = "239.255.0.1"
|
||||
var MULTICAST_PORT = 5000
|
||||
|
||||
var socket = UdpSocket.new()
|
||||
socket.bind("0.0.0.0", MULTICAST_PORT)
|
||||
socket.joinMulticast(MULTICAST_GROUP)
|
||||
socket.setMulticastLoopback(true)
|
||||
|
||||
System.print("Joined multicast group %(MULTICAST_GROUP)")
|
||||
|
||||
socket.send("Hello multicast!", MULTICAST_GROUP, MULTICAST_PORT)
|
||||
|
||||
var msg = socket.receive()
|
||||
System.print("Received: %(msg.data) from %(msg.address)")
|
||||
|
||||
socket.leaveMulticast(MULTICAST_GROUP)
|
||||
socket.close()</code></pre>
|
||||
|
||||
<h3>DNS-Style Query/Response</h3>
|
||||
<pre><code>import "udp" for UdpSocket
|
||||
import "json" for Json
|
||||
|
||||
var socket = UdpSocket.new()
|
||||
socket.bind("0.0.0.0", 0)
|
||||
|
||||
var query = Json.stringify({
|
||||
"type": "lookup",
|
||||
"name": "example.local"
|
||||
})
|
||||
|
||||
socket.send(query, "192.168.1.1", 5353)
|
||||
|
||||
var response = socket.receive()
|
||||
var result = Json.parse(response.data)
|
||||
System.print("Lookup result: %(result)")
|
||||
|
||||
socket.close()</code></pre>
|
||||
|
||||
<h3>UDP Ping</h3>
|
||||
<pre><code>import "udp" for UdpSocket
|
||||
import "sysinfo" for SysInfo
|
||||
|
||||
var socket = UdpSocket.new()
|
||||
socket.bind("0.0.0.0", 0)
|
||||
|
||||
var target = "127.0.0.1"
|
||||
var port = 8080
|
||||
|
||||
for (i in 1..5) {
|
||||
var start = SysInfo.hrtime
|
||||
socket.send("PING %(i)", target, port)
|
||||
|
||||
var msg = socket.receive()
|
||||
var elapsed = (SysInfo.hrtime - start) / 1000000
|
||||
|
||||
System.print("Reply from %(msg.address): %(elapsed) ms")
|
||||
}
|
||||
|
||||
socket.close()</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>UDP is connectionless and does not guarantee delivery. Messages may be lost, duplicated, or arrive out of order. Use TCP (<code>net</code> module) when reliability is required.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>When binding to port 0, the system automatically assigns an available port. Use <code>localPort</code> to retrieve the assigned port number.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Multicast group addresses must be in the range 224.0.0.0 to 239.255.255.255. Using addresses outside this range will cause errors.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,127 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "uuid" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "uuid"}] %}
|
||||
{% set prev_page = {"url": "api/udp.html", "title": "udp"} %}
|
||||
{% set next_page = {"url": "api/wdantic.html", "title": "wdantic"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>uuid</h1>
|
||||
|
||||
<p>The <code>uuid</code> module provides UUID (Universally Unique Identifier) generation and validation. It supports version 4 UUIDs which are randomly generated.</p>
|
||||
|
||||
<pre><code>import "uuid" for Uuid</code></pre>
|
||||
|
||||
<h2>Uuid Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Uuid</h3>
|
||||
<p>UUID generation and validation</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Uuid.v4</span>() → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Generates a new random version 4 UUID.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="returns">Returns:</span> A 36-character UUID string in the format <code>xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx</code></li>
|
||||
</ul>
|
||||
<pre><code>var id = Uuid.v4()
|
||||
System.print(id) // e.g., "550e8400-e29b-41d4-a716-446655440000"</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Uuid.isValid</span>(<span class="param">string</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Checks if a string is a valid UUID format (any version).</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">string</span> <span class="param-type">(String)</span> - The string to validate</li>
|
||||
<li><span class="returns">Returns:</span> <code>true</code> if the string is a valid UUID format, <code>false</code> otherwise</li>
|
||||
</ul>
|
||||
<pre><code>System.print(Uuid.isValid("550e8400-e29b-41d4-a716-446655440000")) // true
|
||||
System.print(Uuid.isValid("not-a-uuid")) // false
|
||||
System.print(Uuid.isValid("550e8400e29b41d4a716446655440000")) // false (missing hyphens)</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Uuid.isV4</span>(<span class="param">string</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Checks if a string is a valid version 4 UUID.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">string</span> <span class="param-type">(String)</span> - The string to validate</li>
|
||||
<li><span class="returns">Returns:</span> <code>true</code> if the string is a valid v4 UUID, <code>false</code> otherwise</li>
|
||||
</ul>
|
||||
<pre><code>var id = Uuid.v4()
|
||||
System.print(Uuid.isV4(id)) // true
|
||||
|
||||
System.print(Uuid.isV4("550e8400-e29b-11d4-a716-446655440000")) // false (version 1)</code></pre>
|
||||
|
||||
<h2>UUID Format</h2>
|
||||
|
||||
<p>UUIDs are 128-bit identifiers represented as 32 hexadecimal characters separated by hyphens into five groups:</p>
|
||||
|
||||
<pre><code>xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
|
||||
8 4 4 4 12 = 32 hex chars + 4 hyphens = 36 chars</code></pre>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Position</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>M</td>
|
||||
<td>Version number (4 for v4 UUIDs)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>N</td>
|
||||
<td>Variant (8, 9, a, or b for RFC 4122 UUIDs)</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Generating Unique Identifiers</h3>
|
||||
<pre><code>import "uuid" for Uuid
|
||||
|
||||
var userId = Uuid.v4()
|
||||
var sessionId = Uuid.v4()
|
||||
|
||||
System.print("User ID: %(userId)")
|
||||
System.print("Session ID: %(sessionId)")</code></pre>
|
||||
|
||||
<h3>Validating User Input</h3>
|
||||
<pre><code>import "uuid" for Uuid
|
||||
|
||||
var input = "550e8400-e29b-41d4-a716-446655440000"
|
||||
|
||||
if (Uuid.isValid(input)) {
|
||||
System.print("Valid UUID")
|
||||
if (Uuid.isV4(input)) {
|
||||
System.print("This is a v4 UUID")
|
||||
}
|
||||
} else {
|
||||
System.print("Invalid UUID format")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Using with Database Records</h3>
|
||||
<pre><code>import "uuid" for Uuid
|
||||
|
||||
class User {
|
||||
construct new(name) {
|
||||
_id = Uuid.v4()
|
||||
_name = name
|
||||
}
|
||||
|
||||
id { _id }
|
||||
name { _name }
|
||||
}
|
||||
|
||||
var user = User.new("Alice")
|
||||
System.print("Created user %(user.name) with ID %(user.id)")</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Version 4 UUIDs are generated using cryptographically secure random bytes from the <code>crypto</code> module. The probability of generating duplicate UUIDs is astronomically low.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,314 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "wdantic" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "wdantic"}] %}
|
||||
{% set prev_page = {"url": "api/argparse.html", "title": "argparse"} %}
|
||||
{% set next_page = {"url": "api/dataset.html", "title": "dataset"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>wdantic</h1>
|
||||
|
||||
<p>The <code>wdantic</code> module provides data validation similar to Python's Pydantic. It includes standalone validators and a schema-based validation system for structured data.</p>
|
||||
|
||||
<pre><code>import "wdantic" for Validator, Field, Schema, ValidationResult</code></pre>
|
||||
|
||||
<h2>Validator Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Validator</h3>
|
||||
<p>Standalone validation functions</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.email</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Validates email address format.</p>
|
||||
<pre><code>Validator.email("user@example.com") // true
|
||||
Validator.email("invalid") // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.domain</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Validates domain name format.</p>
|
||||
<pre><code>Validator.domain("example.com") // true
|
||||
Validator.domain("localhost") // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.url</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Validates HTTP/HTTPS URL format.</p>
|
||||
<pre><code>Validator.url("https://example.com/path") // true
|
||||
Validator.url("ftp://example.com") // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.uuid</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Validates UUID format.</p>
|
||||
<pre><code>Validator.uuid("550e8400-e29b-41d4-a716-446655440000") // true</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.safeStr</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Checks if string contains only printable ASCII characters (32-126).</p>
|
||||
<pre><code>Validator.safeStr("Hello World") // true
|
||||
Validator.safeStr("Hello\x00") // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.base64</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Validates Base64 encoding format.</p>
|
||||
<pre><code>Validator.base64("SGVsbG8=") // true
|
||||
Validator.base64("invalid!") // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.json</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Checks if string is valid JSON.</p>
|
||||
<pre><code>Validator.json("{\"key\": \"value\"}") // true
|
||||
Validator.json("{invalid}") // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.ipv4</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Validates IPv4 address format.</p>
|
||||
<pre><code>Validator.ipv4("192.168.1.1") // true
|
||||
Validator.ipv4("256.0.0.1") // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.minLength</span>(<span class="param">value</span>, <span class="param">min</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Checks minimum length of string or list.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.maxLength</span>(<span class="param">value</span>, <span class="param">max</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Checks maximum length of string or list.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.range</span>(<span class="param">value</span>, <span class="param">min</span>, <span class="param">max</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Checks if number is within range (inclusive).</p>
|
||||
<pre><code>Validator.range(5, 1, 10) // true
|
||||
Validator.range(15, 1, 10) // false</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.positive</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Checks if number is positive (greater than 0).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.negative</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Checks if number is negative (less than 0).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.integer</span>(<span class="param">value</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Checks if number is an integer (no decimal part).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Validator.regex</span>(<span class="param">value</span>, <span class="param">pattern</span>) → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Tests if value matches a regular expression pattern.</p>
|
||||
<pre><code>Validator.regex("abc123", "^[a-z]+[0-9]+$") // true</code></pre>
|
||||
|
||||
<h2>Field Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Field</h3>
|
||||
<p>Factory for creating field definitions</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.string</span>() → <span class="type">StringField</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.string</span>(<span class="param">options</span>) → <span class="type">StringField</span>
|
||||
</div>
|
||||
<p>Creates a string field. Options: <code>minLength</code>, <code>maxLength</code>, <code>pattern</code>, <code>required</code>, <code>default</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.integer</span>() → <span class="type">IntegerField</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.integer</span>(<span class="param">options</span>) → <span class="type">IntegerField</span>
|
||||
</div>
|
||||
<p>Creates an integer field. Options: <code>min</code>, <code>max</code>, <code>required</code>, <code>default</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.number</span>() → <span class="type">NumberField</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.number</span>(<span class="param">options</span>) → <span class="type">NumberField</span>
|
||||
</div>
|
||||
<p>Creates a number field (integer or float). Options: <code>min</code>, <code>max</code>, <code>required</code>, <code>default</code>.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.email</span>() → <span class="type">EmailField</span>
|
||||
</div>
|
||||
<p>Creates a field that validates email format.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.boolean</span>() → <span class="type">BooleanField</span>
|
||||
</div>
|
||||
<p>Creates a boolean field.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.list</span>(<span class="param">itemType</span>) → <span class="type">ListField</span>
|
||||
</div>
|
||||
<p>Creates a list field with typed items.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.map</span>() → <span class="type">MapField</span>
|
||||
</div>
|
||||
<p>Creates a map/object field.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Field.optional</span>(<span class="param">fieldDef</span>) → <span class="type">OptionalField</span>
|
||||
</div>
|
||||
<p>Makes any field optional (not required).</p>
|
||||
|
||||
<h2>Schema Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Schema</h3>
|
||||
<p>Validates data against a field definition map</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructor</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Schema.new</span>(<span class="param">definition</span>) → <span class="type">Schema</span>
|
||||
</div>
|
||||
<p>Creates a schema from a map of field names to field definitions.</p>
|
||||
|
||||
<h3>Instance Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">validate</span>(<span class="param">data</span>) → <span class="type">ValidationResult</span>
|
||||
</div>
|
||||
<p>Validates data against the schema.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">validateOrAbort</span>(<span class="param">data</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Validates data and aborts on failure. Returns validated data on success.</p>
|
||||
|
||||
<h2>ValidationResult Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>ValidationResult</h3>
|
||||
<p>Result of schema validation</p>
|
||||
</div>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isValid</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>Whether validation passed.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">errors</span> → <span class="type">List</span>
|
||||
</div>
|
||||
<p>List of ValidationError objects.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">data</span> → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Validated and coerced data (null if invalid).</p>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Basic Schema Validation</h3>
|
||||
<pre><code>import "wdantic" for Field, Schema
|
||||
|
||||
var userSchema = Schema.new({
|
||||
"name": Field.string({"minLength": 1, "maxLength": 100}),
|
||||
"email": Field.email(),
|
||||
"age": Field.integer({"min": 0, "max": 150})
|
||||
})
|
||||
|
||||
var result = userSchema.validate({
|
||||
"name": "Alice",
|
||||
"email": "alice@example.com",
|
||||
"age": 30
|
||||
})
|
||||
|
||||
if (result.isValid) {
|
||||
System.print("Valid: %(result.data)")
|
||||
} else {
|
||||
for (error in result.errors) {
|
||||
System.print("Error: %(error)")
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Optional Fields</h3>
|
||||
<pre><code>import "wdantic" for Field, Schema
|
||||
|
||||
var schema = Schema.new({
|
||||
"title": Field.string(),
|
||||
"description": Field.optional(Field.string()),
|
||||
"tags": Field.optional(Field.list(Field.string()))
|
||||
})
|
||||
|
||||
var result = schema.validate({
|
||||
"title": "My Post"
|
||||
})
|
||||
|
||||
System.print(result.isValid) // true</code></pre>
|
||||
|
||||
<h3>Nested Lists</h3>
|
||||
<pre><code>import "wdantic" for Field, Schema
|
||||
|
||||
var schema = Schema.new({
|
||||
"numbers": Field.list(Field.integer({"min": 0}))
|
||||
})
|
||||
|
||||
var result = schema.validate({
|
||||
"numbers": [1, 2, 3, -1] // -1 will fail
|
||||
})
|
||||
|
||||
System.print(result.isValid) // false</code></pre>
|
||||
|
||||
<h3>Using validateOrAbort</h3>
|
||||
<pre><code>import "wdantic" for Field, Schema
|
||||
|
||||
var schema = Schema.new({
|
||||
"username": Field.string({"minLength": 3}),
|
||||
"password": Field.string({"minLength": 8})
|
||||
})
|
||||
|
||||
var data = schema.validateOrAbort({
|
||||
"username": "admin",
|
||||
"password": "secret123"
|
||||
})</code></pre>
|
||||
|
||||
<h3>Standalone Validators</h3>
|
||||
<pre><code>import "wdantic" for Validator
|
||||
|
||||
var email = "user@example.com"
|
||||
if (Validator.email(email)) {
|
||||
System.print("Valid email")
|
||||
}
|
||||
|
||||
var ip = "192.168.1.1"
|
||||
if (Validator.ipv4(ip)) {
|
||||
System.print("Valid IP address")
|
||||
}
|
||||
|
||||
var jsonStr = "{\"key\": 123}"
|
||||
if (Validator.json(jsonStr)) {
|
||||
System.print("Valid JSON")
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Field types automatically coerce values when possible. For example, <code>IntegerField</code> will convert the string <code>"42"</code> to the number <code>42</code>.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,999 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "web" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "web"}] %}
|
||||
{% set prev_page = {"url": "api/wdantic.html", "title": "wdantic"} %}
|
||||
{% set next_page = {"url": "api/websocket.html", "title": "websocket"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>web</h1>
|
||||
|
||||
<p>The <code>web</code> module provides a web framework for building HTTP servers and a client for making HTTP requests. It includes routing, middleware, sessions, static file serving, and class-based views.</p>
|
||||
|
||||
<pre><code>import "web" for Application, Router, Request, Response, View, Session, Client, WebSocketResponse</code></pre>
|
||||
|
||||
<h2>Application Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Application</h3>
|
||||
<p>HTTP server with routing and middleware</p>
|
||||
</div>
|
||||
|
||||
<h3>Constructor</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Application.new</span>() → <span class="type">Application</span>
|
||||
</div>
|
||||
<p>Creates a new web application.</p>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">router</span> → <span class="type">Router</span>
|
||||
</div>
|
||||
<p>Access to the underlying router.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">sessionStore</span> → <span class="type">SessionStore</span>
|
||||
</div>
|
||||
<p>Access to the session storage.</p>
|
||||
|
||||
<h3>Routing Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">get</span>(<span class="param">path</span>, <span class="param">handler</span>) → <span class="type">Application</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">post</span>(<span class="param">path</span>, <span class="param">handler</span>) → <span class="type">Application</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">put</span>(<span class="param">path</span>, <span class="param">handler</span>) → <span class="type">Application</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">delete</span>(<span class="param">path</span>, <span class="param">handler</span>) → <span class="type">Application</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">patch</span>(<span class="param">path</span>, <span class="param">handler</span>) → <span class="type">Application</span>
|
||||
</div>
|
||||
<p>Register route handlers. Handler receives <code>Request</code> and returns <code>Response</code>.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">path</span> <span class="param-type">(String)</span> - URL path with optional parameters (<code>:param</code>) or wildcards (<code>*</code>)</li>
|
||||
<li><span class="param-name">handler</span> <span class="param-type">(Fn)</span> - Function receiving Request, returning Response</li>
|
||||
</ul>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">addView</span>(<span class="param">path</span>, <span class="param">viewClass</span>) → <span class="type">Application</span>
|
||||
</div>
|
||||
<p>Registers a class-based view for all HTTP methods.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">static_</span>(<span class="param">prefix</span>, <span class="param">directory</span>) → <span class="type">Application</span>
|
||||
</div>
|
||||
<p>Serves static files from a directory.</p>
|
||||
<pre><code>app.static_("/assets", "./public")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">websocket</span>(<span class="param">path</span>, <span class="param">handler</span>) → <span class="type">Application</span>
|
||||
</div>
|
||||
<p>Registers a WebSocket handler for the given path. Handler receives Request and should use WebSocketResponse to handle the connection.</p>
|
||||
<pre><code>app.websocket("/ws", Fn.new { |req|
|
||||
var ws = WebSocketResponse.new()
|
||||
ws.prepare(req)
|
||||
while (ws.isOpen) {
|
||||
var msg = ws.receive()
|
||||
if (msg == null || msg.isClose) break
|
||||
if (msg.isText) ws.send("Echo: " + msg.text)
|
||||
}
|
||||
return ws
|
||||
})</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">use</span>(<span class="param">middleware</span>) → <span class="type">Application</span>
|
||||
</div>
|
||||
<p>Adds middleware function. Middleware receives Request, returns Response or null to continue.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">run</span>(<span class="param">host</span>, <span class="param">port</span>)
|
||||
</div>
|
||||
<p>Starts the server (blocking).</p>
|
||||
|
||||
<h2>Request Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Request</h3>
|
||||
<p>Incoming HTTP request</p>
|
||||
</div>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Property</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>method</code></td>
|
||||
<td>String</td>
|
||||
<td>HTTP method (GET, POST, etc.)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>path</code></td>
|
||||
<td>String</td>
|
||||
<td>Request path without query string</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>query</code></td>
|
||||
<td>Map</td>
|
||||
<td>Parsed query parameters</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>headers</code></td>
|
||||
<td>Map</td>
|
||||
<td>Request headers</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>body</code></td>
|
||||
<td>String</td>
|
||||
<td>Raw request body</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>params</code></td>
|
||||
<td>Map</td>
|
||||
<td>Route parameters from URL</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>cookies</code></td>
|
||||
<td>Map</td>
|
||||
<td>Parsed cookies</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>session</code></td>
|
||||
<td>Session</td>
|
||||
<td>Session data</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">header</span>(<span class="param">name</span>) → <span class="type">String|null</span>
|
||||
</div>
|
||||
<p>Gets header value (case-insensitive).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">json</span> → <span class="type">Map|List</span>
|
||||
</div>
|
||||
<p>Parses body as JSON (cached).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">form</span> → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Parses body as form data (cached).</p>
|
||||
|
||||
<h2>Response Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Response</h3>
|
||||
<p>HTTP response builder</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Factory Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Response.text</span>(<span class="param">content</span>) → <span class="type">Response</span>
|
||||
</div>
|
||||
<p>Creates plain text response.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Response.html</span>(<span class="param">content</span>) → <span class="type">Response</span>
|
||||
</div>
|
||||
<p>Creates HTML response.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Response.json</span>(<span class="param">data</span>) → <span class="type">Response</span>
|
||||
</div>
|
||||
<p>Creates JSON response (automatically stringifies).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Response.redirect</span>(<span class="param">url</span>) → <span class="type">Response</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Response.redirect</span>(<span class="param">url</span>, <span class="param">status</span>) → <span class="type">Response</span>
|
||||
</div>
|
||||
<p>Creates redirect response (default 302).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Response.file</span>(<span class="param">path</span>) → <span class="type">Response</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Response.file</span>(<span class="param">path</span>, <span class="param">contentType</span>) → <span class="type">Response</span>
|
||||
</div>
|
||||
<p>Serves a file. Auto-detects content type if not specified.</p>
|
||||
|
||||
<h3>Instance Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">header</span>(<span class="param">name</span>, <span class="param">value</span>) → <span class="type">Response</span>
|
||||
</div>
|
||||
<p>Sets a response header.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">cookie</span>(<span class="param">name</span>, <span class="param">value</span>) → <span class="type">Response</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">cookie</span>(<span class="param">name</span>, <span class="param">value</span>, <span class="param">options</span>) → <span class="type">Response</span>
|
||||
</div>
|
||||
<p>Sets a cookie. Options: <code>path</code>, <code>maxAge</code>, <code>httpOnly</code>, <code>secure</code>.</p>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">status</span> → <span class="type">Num</span>
|
||||
</div>
|
||||
<p>Gets or sets HTTP status code.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">body</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Gets or sets response body.</p>
|
||||
|
||||
<h2>View Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>View</h3>
|
||||
<p>Base class for class-based views</p>
|
||||
</div>
|
||||
|
||||
<p>Subclass and override methods for each HTTP method:</p>
|
||||
<pre><code>class UserView is View {
|
||||
get(request) {
|
||||
return Response.json({"users": []})
|
||||
}
|
||||
|
||||
post(request) {
|
||||
var data = request.json
|
||||
return Response.json({"created": data})
|
||||
}
|
||||
|
||||
websocket(request) {
|
||||
var ws = WebSocketResponse.new()
|
||||
ws.prepare(request)
|
||||
ws.iterate(Fn.new { |msg|
|
||||
if (msg.isText) ws.send("Echo: " + msg.text)
|
||||
})
|
||||
return ws
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h2>WebSocketResponse Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>WebSocketResponse</h3>
|
||||
<p>Server-side WebSocket connection handler (aiohttp-style API)</p>
|
||||
</div>
|
||||
|
||||
<p>The <code>WebSocketResponse</code> class provides a server-side WebSocket handler following the aiohttp-style API pattern. It handles the WebSocket handshake, frame encoding/decoding, and provides convenient methods for sending and receiving messages.</p>
|
||||
|
||||
<h3>Constructor</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">WebSocketResponse.new</span>() → <span class="type">WebSocketResponse</span>
|
||||
</div>
|
||||
<p>Creates a new WebSocket response handler. Call <code>prepare(request)</code> to complete the handshake before sending or receiving messages.</p>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Property</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isPrepared</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if the WebSocket handshake has been performed</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isOpen</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if the connection is open and ready for messages</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Connection Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">prepare</span>(<span class="param">request</span>) → <span class="type">WebSocketResponse</span>
|
||||
</div>
|
||||
<p>Performs the WebSocket handshake using the request's socket. Must be called before sending or receiving messages. Returns <code>this</code> for method chaining.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">request</span> <span class="param-type">(Request)</span> - The HTTP request containing the WebSocket upgrade headers</li>
|
||||
</ul>
|
||||
<pre><code>var ws = WebSocketResponse.new()
|
||||
ws.prepare(request)</code></pre>
|
||||
|
||||
<h3>Sending Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">send</span>(<span class="param">text</span>)
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">sendText</span>(<span class="param">text</span>)
|
||||
</div>
|
||||
<p>Sends a text message to the client. Both methods are equivalent.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">text</span> <span class="param-type">(String)</span> - Text message to send</li>
|
||||
</ul>
|
||||
<pre><code>ws.send("Hello, client!")
|
||||
ws.sendText("Another message")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">sendJson</span>(<span class="param">data</span>)
|
||||
</div>
|
||||
<p>Serializes the data to JSON and sends it as a text message. Convenience method for JSON-based protocols.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(Map|List)</span> - Data to serialize and send</li>
|
||||
</ul>
|
||||
<pre><code>ws.sendJson({"type": "update", "value": 42})
|
||||
ws.sendJson(["item1", "item2", "item3"])</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">sendBinary</span>(<span class="param">bytes</span>)
|
||||
</div>
|
||||
<p>Sends a binary message to the client.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">bytes</span> <span class="param-type">(List)</span> - List of bytes to send</li>
|
||||
</ul>
|
||||
<pre><code>ws.sendBinary([0x01, 0x02, 0x03, 0x04])
|
||||
|
||||
var imageData = File.readBytes("image.png")
|
||||
ws.sendBinary(imageData)</code></pre>
|
||||
|
||||
<h3>Receiving Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">receive</span>() → <span class="type">WebSocketMessage|null</span>
|
||||
</div>
|
||||
<p>Receives the next message from the client. Blocks until a message arrives. Returns a <code>WebSocketMessage</code> object, or <code>null</code> if the connection closed unexpectedly. Ping frames are automatically answered with pong.</p>
|
||||
<pre><code>var msg = ws.receive()
|
||||
if (msg != null && msg.isText) {
|
||||
System.print("Got: %(msg.text)")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">receiveJson</span>() → <span class="type">Map|List|WebSocketMessage|null</span>
|
||||
</div>
|
||||
<p>Receives a text message and parses it as JSON. Returns the parsed JSON data, the close frame if the connection was closed, or <code>null</code> if the connection closed unexpectedly. Aborts if a binary frame is received.</p>
|
||||
<pre><code>var data = ws.receiveJson()
|
||||
if (data is Map && data.containsKey("type")) {
|
||||
if (data["type"] == "message") {
|
||||
System.print("Message: %(data["text"])")
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">receiveText</span>() → <span class="type">String|null</span>
|
||||
</div>
|
||||
<p>Receives a message and returns only the text content. Returns <code>null</code> if the message is not a text frame, if the connection was closed, or if the connection closed unexpectedly.</p>
|
||||
<pre><code>var text = ws.receiveText()
|
||||
if (text != null) {
|
||||
System.print("Received: %(text)")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">receiveBinary</span>() → <span class="type">List|null</span>
|
||||
</div>
|
||||
<p>Receives a message and returns only the binary content. Returns <code>null</code> if the message is not a binary frame, if the connection was closed, or if the connection closed unexpectedly.</p>
|
||||
<pre><code>var bytes = ws.receiveBinary()
|
||||
if (bytes != null) {
|
||||
System.print("Received %(bytes.count) bytes")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">iterate</span>(<span class="param">callback</span>)
|
||||
</div>
|
||||
<p>Helper method that loops while the connection is open, calling the callback for each received message (excluding close frames). Simplifies the common receive loop pattern.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">callback</span> <span class="param-type">(Fn)</span> - Function to call with each WebSocketMessage</li>
|
||||
</ul>
|
||||
<pre><code>ws.iterate(Fn.new { |msg|
|
||||
if (msg.isText) {
|
||||
ws.send("Echo: " + msg.text)
|
||||
}
|
||||
})</code></pre>
|
||||
|
||||
<h3>Control Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ping</span>()
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ping</span>(<span class="param">data</span>)
|
||||
</div>
|
||||
<p>Sends a ping frame to check if the client is still connected. Payload must be 125 bytes or less.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">data</span> <span class="param-type">(String|List)</span> - Optional payload data</li>
|
||||
</ul>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">pong</span>(<span class="param">data</span>)
|
||||
</div>
|
||||
<p>Sends a pong frame. Usually automatic in response to ping, but can be sent manually.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>()
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>(<span class="param">code</span>, <span class="param">reason</span>)
|
||||
</div>
|
||||
<p>Closes the WebSocket connection. Default code is 1000 (normal closure).</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">code</span> <span class="param-type">(Num)</span> - Close status code (1000-4999)</li>
|
||||
<li><span class="param-name">reason</span> <span class="param-type">(String)</span> - Human-readable close reason</li>
|
||||
</ul>
|
||||
<pre><code>ws.close()
|
||||
ws.close(1000, "Goodbye")</code></pre>
|
||||
|
||||
<h3>WebSocketMessage Reference</h3>
|
||||
|
||||
<p>The <code>receive()</code> method returns a <code>WebSocketMessage</code> object with the following properties:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Property</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>opcode</code></td>
|
||||
<td>Num</td>
|
||||
<td>Frame opcode (1=text, 2=binary, 8=close, 9=ping, 10=pong)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fin</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is the final fragment</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isText</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is a text frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isBinary</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is a binary frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isClose</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is a close frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isPing</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is a ping frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isPong</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is a pong frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>text</code></td>
|
||||
<td>String</td>
|
||||
<td>Payload as string (for text frames)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>bytes</code></td>
|
||||
<td>List</td>
|
||||
<td>Payload as byte list</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>closeCode</code></td>
|
||||
<td>Num</td>
|
||||
<td>Close status code (for close frames)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>closeReason</code></td>
|
||||
<td>String</td>
|
||||
<td>Close reason text (for close frames)</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Close Codes Reference</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Code</th>
|
||||
<th>Meaning</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1000</td>
|
||||
<td>Normal closure</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1001</td>
|
||||
<td>Going away (server shutdown)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1002</td>
|
||||
<td>Protocol error</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1003</td>
|
||||
<td>Unsupported data type</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1005</td>
|
||||
<td>No status received</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1006</td>
|
||||
<td>Abnormal closure</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1011</td>
|
||||
<td>Server error</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>4000-4999</td>
|
||||
<td>Application-specific codes</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Ping frames received from clients are automatically answered with pong frames. You typically do not need to handle ping/pong manually unless implementing custom keepalive logic.</p>
|
||||
</div>
|
||||
|
||||
<h2>Session Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Session</h3>
|
||||
<p>Session data storage</p>
|
||||
</div>
|
||||
|
||||
<h3>Properties and Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">id</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The session ID.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">[key]</span> → <span class="type">any</span>
|
||||
</div>
|
||||
<p>Gets session value.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">[key]=</span>(<span class="param">value</span>)
|
||||
</div>
|
||||
<p>Sets session value.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">remove</span>(<span class="param">key</span>)
|
||||
</div>
|
||||
<p>Removes a session key.</p>
|
||||
|
||||
<h2>Client Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Client</h3>
|
||||
<p>HTTP client for making requests</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Client.get</span>(<span class="param">url</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Client.get</span>(<span class="param">url</span>, <span class="param">options</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Makes GET request.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Client.post</span>(<span class="param">url</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Client.post</span>(<span class="param">url</span>, <span class="param">options</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Makes POST request.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Client.put</span>(<span class="param">url</span>, <span class="param">options</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Makes PUT request.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Client.delete</span>(<span class="param">url</span>, <span class="param">options</span>) → <span class="type">Map</span>
|
||||
</div>
|
||||
<p>Makes DELETE request.</p>
|
||||
|
||||
<h3>Client Options</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Option</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>headers</code></td>
|
||||
<td>Map</td>
|
||||
<td>Request headers</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>body</code></td>
|
||||
<td>String</td>
|
||||
<td>Request body</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>json</code></td>
|
||||
<td>Map/List</td>
|
||||
<td>JSON body (auto-stringifies and sets Content-Type)</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Response Format</h3>
|
||||
<pre><code>{
|
||||
"status": 200,
|
||||
"headers": {"Content-Type": "application/json"},
|
||||
"body": "{...}"
|
||||
}</code></pre>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Basic Server</h3>
|
||||
<pre><code>import "web" for Application, Response
|
||||
|
||||
var app = Application.new()
|
||||
|
||||
app.get("/", Fn.new { |req|
|
||||
return Response.html("<h1>Hello World</h1>")
|
||||
})
|
||||
|
||||
app.get("/api/users", Fn.new { |req|
|
||||
return Response.json({"users": ["Alice", "Bob"]})
|
||||
})
|
||||
|
||||
app.run("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<h3>Route Parameters</h3>
|
||||
<pre><code>import "web" for Application, Response
|
||||
|
||||
var app = Application.new()
|
||||
|
||||
app.get("/users/:id", Fn.new { |req|
|
||||
var userId = req.params["id"]
|
||||
return Response.json({"id": userId})
|
||||
})
|
||||
|
||||
app.get("/files/*", Fn.new { |req|
|
||||
return Response.text("Wildcard route")
|
||||
})
|
||||
|
||||
app.run("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<h3>Class-Based Views</h3>
|
||||
<pre><code>import "web" for Application, Response, View
|
||||
|
||||
class ArticleView is View {
|
||||
get(request) {
|
||||
return Response.json({"articles": []})
|
||||
}
|
||||
|
||||
post(request) {
|
||||
var data = request.json
|
||||
return Response.json({"created": data})
|
||||
}
|
||||
}
|
||||
|
||||
var app = Application.new()
|
||||
app.addView("/articles", ArticleView)
|
||||
app.run("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<h3>Sessions</h3>
|
||||
<pre><code>import "web" for Application, Response
|
||||
|
||||
var app = Application.new()
|
||||
|
||||
app.get("/login", Fn.new { |req|
|
||||
req.session["user"] = "Alice"
|
||||
return Response.text("Logged in")
|
||||
})
|
||||
|
||||
app.get("/profile", Fn.new { |req|
|
||||
var user = req.session["user"]
|
||||
if (user == null) {
|
||||
return Response.redirect("/login")
|
||||
}
|
||||
return Response.text("Hello, %(user)")
|
||||
})
|
||||
|
||||
app.run("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<h3>Middleware</h3>
|
||||
<pre><code>import "web" for Application, Response
|
||||
|
||||
var app = Application.new()
|
||||
|
||||
app.use(Fn.new { |req|
|
||||
System.print("%(req.method) %(req.path)")
|
||||
return null
|
||||
})
|
||||
|
||||
app.use(Fn.new { |req|
|
||||
if (req.path.startsWith("/admin") && !req.session["isAdmin"]) {
|
||||
return Response.redirect("/login")
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
app.get("/", Fn.new { |req|
|
||||
return Response.text("Home")
|
||||
})
|
||||
|
||||
app.run("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<h3>HTTP Client</h3>
|
||||
<pre><code>import "web" for Client
|
||||
import "json" for Json
|
||||
|
||||
var response = Client.get("https://api.example.com/data")
|
||||
System.print("Status: %(response["status"])")
|
||||
System.print("Body: %(response["body"])")
|
||||
|
||||
var postResponse = Client.post("https://api.example.com/users", {
|
||||
"json": {"name": "Alice", "email": "alice@example.com"}
|
||||
})
|
||||
|
||||
var data = Json.parse(postResponse["body"])</code></pre>
|
||||
|
||||
<h3>Concurrent HTTP Requests</h3>
|
||||
<p>Use the <code>async</code> keyword to create futures and <code>await</code> to wait for results. Each request runs in its own fiber and executes in parallel while waiting for I/O.</p>
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
|
||||
var urls = [
|
||||
"https://api.example.com/users",
|
||||
"https://api.example.com/posts",
|
||||
"https://api.example.com/comments"
|
||||
]
|
||||
|
||||
var futures = []
|
||||
for (url in urls) {
|
||||
futures.add(async { Client.get(url) })
|
||||
}
|
||||
|
||||
var responses = []
|
||||
for (future in futures) {
|
||||
responses.add(await future)
|
||||
}
|
||||
|
||||
for (i in 0...urls.count) {
|
||||
System.print("%(urls[i]): %(responses[i]["status"])")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Parallel Batch Requests</h3>
|
||||
<p>For batch operations, create all futures first, then await them. The requests execute concurrently.</p>
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "json" for Json
|
||||
|
||||
var fetchUrl = async { |url| Client.get(url) }
|
||||
|
||||
class BatchClient {
|
||||
static getAll(urls) {
|
||||
var futures = []
|
||||
for (url in urls) {
|
||||
futures.add(async { Client.get(url) })
|
||||
}
|
||||
|
||||
var results = []
|
||||
for (f in futures) {
|
||||
results.add(await f)
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
static postAll(requests) {
|
||||
var futures = []
|
||||
for (req in requests) {
|
||||
futures.add(async { Client.post(req["url"], req["options"]) })
|
||||
}
|
||||
|
||||
var results = []
|
||||
for (f in futures) {
|
||||
results.add(await f)
|
||||
}
|
||||
return results
|
||||
}
|
||||
}
|
||||
|
||||
var urls = [
|
||||
"https://api.example.com/endpoint1",
|
||||
"https://api.example.com/endpoint2",
|
||||
"https://api.example.com/endpoint3"
|
||||
]
|
||||
|
||||
var results = BatchClient.getAll(urls)
|
||||
for (result in results) {
|
||||
System.print("Status: %(result["status"])")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Parameterized Async Functions</h3>
|
||||
<p>Create reusable async functions with parameters using <code>async { |args| ... }</code>. There are two ways to invoke these functions:</p>
|
||||
|
||||
<ul>
|
||||
<li><strong><code>await fn(args)</code></strong> — Direct call, waits immediately (sequential execution)</li>
|
||||
<li><strong><code>fn.call(args)</code></strong> — Returns a Future, starts execution without waiting (concurrent execution)</li>
|
||||
</ul>
|
||||
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "json" for Json
|
||||
|
||||
var fetchJson = async { |url|
|
||||
var response = Client.get(url)
|
||||
return Json.parse(response["body"])
|
||||
}
|
||||
|
||||
var postJson = async { |url, data|
|
||||
var response = Client.post(url, {"json": data})
|
||||
return Json.parse(response["body"])
|
||||
}
|
||||
|
||||
// DIRECT CALLING (preferred for sequential operations)
|
||||
// Waits for each request to complete before continuing
|
||||
var user = await fetchJson("https://api.example.com/user/1")
|
||||
System.print(user["name"])
|
||||
|
||||
// CONCURRENT EXECUTION (use .call() to start without waiting)
|
||||
// Both requests run at the same time
|
||||
var f1 = fetchJson.call("https://api.example.com/posts")
|
||||
var f2 = fetchJson.call("https://api.example.com/comments")
|
||||
|
||||
// Now wait for results
|
||||
var posts = await f1
|
||||
var comments = await f2</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Direct Calling vs .call()</div>
|
||||
<p>Use <code>await fn(args)</code> when you want sequential execution. Use <code>fn.call(args)</code> when you want to start multiple operations concurrently, then <code>await</code> their results later.</p>
|
||||
</div>
|
||||
|
||||
<h3>WebSocket Echo Server</h3>
|
||||
<pre><code>import "web" for Application, Response, WebSocketResponse
|
||||
|
||||
var app = Application.new()
|
||||
|
||||
app.get("/", Fn.new { |req|
|
||||
return Response.html("<script>var ws=new WebSocket('ws://localhost:8080/ws');ws.onmessage=e=>console.log(e.data);ws.onopen=()=>ws.send('hello');</script>")
|
||||
})
|
||||
|
||||
app.websocket("/ws", Fn.new { |req|
|
||||
var ws = WebSocketResponse.new()
|
||||
ws.prepare(req)
|
||||
|
||||
while (ws.isOpen) {
|
||||
var msg = ws.receive()
|
||||
if (msg == null || msg.isClose) break
|
||||
if (msg.isText) {
|
||||
ws.send("Echo: " + msg.text)
|
||||
}
|
||||
}
|
||||
|
||||
ws.close()
|
||||
return ws
|
||||
})
|
||||
|
||||
app.run("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<h3>WebSocket JSON API</h3>
|
||||
<pre><code>import "web" for Application, Response, WebSocketResponse
|
||||
|
||||
var app = Application.new()
|
||||
|
||||
app.websocket("/api", Fn.new { |req|
|
||||
var ws = WebSocketResponse.new()
|
||||
ws.prepare(req)
|
||||
|
||||
ws.sendJson({"type": "welcome", "message": "Connected to API"})
|
||||
|
||||
while (ws.isOpen) {
|
||||
var data = ws.receiveJson()
|
||||
if (data == null) break
|
||||
if (data is Map && data["type"] == "ping") {
|
||||
ws.sendJson({"type": "pong", "timestamp": data["timestamp"]})
|
||||
} else if (data is Map && data["type"] == "echo") {
|
||||
ws.sendJson({"type": "echo", "data": data["data"]})
|
||||
}
|
||||
}
|
||||
|
||||
return ws
|
||||
})
|
||||
|
||||
app.run("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<h3>WebSocket Binary Data Transfer</h3>
|
||||
<pre><code>import "web" for Application, Response, WebSocketResponse
|
||||
import "io" for File
|
||||
|
||||
var app = Application.new()
|
||||
|
||||
app.websocket("/binary", Fn.new { |req|
|
||||
var ws = WebSocketResponse.new()
|
||||
ws.prepare(req)
|
||||
|
||||
ws.send("Ready to receive binary data")
|
||||
|
||||
while (ws.isOpen) {
|
||||
var msg = ws.receive()
|
||||
if (msg == null || msg.isClose) break
|
||||
|
||||
if (msg.isBinary) {
|
||||
System.print("Received %(msg.bytes.count) bytes")
|
||||
ws.sendJson({"received": msg.bytes.count, "status": "ok"})
|
||||
} else if (msg.isText) {
|
||||
if (msg.text == "send-file") {
|
||||
var data = File.readBytes("example.bin")
|
||||
ws.sendBinary(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ws
|
||||
})
|
||||
|
||||
app.run("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<h3>WebSocket in Class-Based View</h3>
|
||||
<pre><code>import "web" for Application, Response, View, WebSocketResponse
|
||||
|
||||
class ChatView is View {
|
||||
get(request) {
|
||||
return Response.html("<h1>Chat Room</h1><p>Connect via WebSocket</p>")
|
||||
}
|
||||
|
||||
websocket(request) {
|
||||
var ws = WebSocketResponse.new()
|
||||
ws.prepare(request)
|
||||
|
||||
ws.sendJson({"type": "connected", "room": "general"})
|
||||
|
||||
ws.iterate(Fn.new { |msg|
|
||||
if (msg.isText) {
|
||||
var data = Json.parse(msg.text)
|
||||
if (data["type"] == "message") {
|
||||
ws.sendJson({
|
||||
"type": "broadcast",
|
||||
"from": data["from"],
|
||||
"text": data["text"]
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return ws
|
||||
}
|
||||
}
|
||||
|
||||
var app = Application.new()
|
||||
app.addView("/chat", ChatView)
|
||||
app.run("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">WebSocket Error Handling</div>
|
||||
<p>Always check for <code>null</code> or close frames when receiving messages. The connection can close at any time due to network issues or client disconnection. Wrap WebSocket handling in proper error handling to prevent server crashes.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Sessions are stored in memory by default. Data is lost when the server restarts. For production, consider persisting session data to a database.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,408 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "websocket" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "websocket"}] %}
|
||||
{% set prev_page = {"url": "api/http.html", "title": "http"} %}
|
||||
{% set next_page = {"url": "api/yaml.html", "title": "yaml"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>websocket</h1>
|
||||
|
||||
<p>The <code>websocket</code> module provides WebSocket client and server functionality implementing the RFC 6455 protocol. It supports both <code>ws://</code> and <code>wss://</code> (secure) connections.</p>
|
||||
|
||||
<pre><code>import "websocket" for WebSocket, WebSocketServer, WebSocketMessage</code></pre>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#websocket-class">WebSocket Class</a></li>
|
||||
<li><a href="#websocketserver-class">WebSocketServer Class</a></li>
|
||||
<li><a href="#websocketmessage-class">WebSocketMessage Class</a></li>
|
||||
<li><a href="#opcodes">Frame Opcodes</a></li>
|
||||
<li><a href="#examples">Examples</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="websocket-class">WebSocket Class</h2>
|
||||
<p>WebSocket client for connecting to WebSocket servers.</p>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>WebSocket</h3>
|
||||
<p>WebSocket client connection</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">WebSocket.connect</span>(<span class="param">url</span>) → <span class="type">WebSocket</span>
|
||||
</div>
|
||||
<p>Connects to a WebSocket server.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">url</span> <span class="param-type">(String)</span> - WebSocket URL (ws:// or wss://)</li>
|
||||
<li><span class="returns">Returns:</span> Connected WebSocket instance</li>
|
||||
</ul>
|
||||
<pre><code>var ws = WebSocket.connect("ws://echo.websocket.org")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">WebSocket.connect</span>(<span class="param">url</span>, <span class="param">headers</span>) → <span class="type">WebSocket</span>
|
||||
</div>
|
||||
<p>Connects with custom headers (useful for authentication).</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">url</span> <span class="param-type">(String)</span> - WebSocket URL</li>
|
||||
<li><span class="param-name">headers</span> <span class="param-type">(Map)</span> - Custom HTTP headers for handshake</li>
|
||||
</ul>
|
||||
<pre><code>var headers = {"Authorization": "Bearer token123"}
|
||||
var ws = WebSocket.connect("wss://api.example.com/ws", headers)</code></pre>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">url</span> → <span class="type">String</span>
|
||||
</div>
|
||||
<p>The URL this WebSocket is connected to.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">isOpen</span> → <span class="type">Bool</span>
|
||||
</div>
|
||||
<p>True if the connection is still open.</p>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">send</span>(<span class="param">text</span>)
|
||||
</div>
|
||||
<p>Sends a text message to the server.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">text</span> <span class="param-type">(String)</span> - Text message to send</li>
|
||||
</ul>
|
||||
<pre><code>ws.send("Hello, server!")</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">sendBinary</span>(<span class="param">bytes</span>)
|
||||
</div>
|
||||
<p>Sends a binary message to the server.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">bytes</span> <span class="param-type">(List)</span> - List of bytes to send</li>
|
||||
</ul>
|
||||
<pre><code>ws.sendBinary([0x01, 0x02, 0x03, 0x04])</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">receive</span>() → <span class="type">WebSocketMessage|null</span>
|
||||
</div>
|
||||
<p>Receives the next message from the server. Blocks until a message arrives. Returns null if the connection is closed.</p>
|
||||
<pre><code>var msg = ws.receive()
|
||||
if (msg != null && msg.isText) {
|
||||
System.print("Got: %(msg.text)")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ping</span>()
|
||||
</div>
|
||||
<p>Sends a ping frame to the server.</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ping</span>(<span class="param">data</span>)
|
||||
</div>
|
||||
<p>Sends a ping frame with payload data (max 125 bytes).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">pong</span>(<span class="param">data</span>)
|
||||
</div>
|
||||
<p>Sends a pong frame (usually automatic in response to ping).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>()
|
||||
</div>
|
||||
<p>Closes the connection with status code 1000 (normal closure).</p>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>(<span class="param">code</span>, <span class="param">reason</span>)
|
||||
</div>
|
||||
<p>Closes the connection with a custom status code and reason.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">code</span> <span class="param-type">(Num)</span> - Close status code (1000-4999)</li>
|
||||
<li><span class="param-name">reason</span> <span class="param-type">(String)</span> - Human-readable close reason</li>
|
||||
</ul>
|
||||
<pre><code>ws.close(1000, "Goodbye")</code></pre>
|
||||
|
||||
<h2 id="websocketserver-class">WebSocketServer Class</h2>
|
||||
<p>WebSocket server for accepting client connections.</p>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>WebSocketServer</h3>
|
||||
<p>WebSocket server</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">WebSocketServer.bind</span>(<span class="param">host</span>, <span class="param">port</span>) → <span class="type">WebSocketServer</span>
|
||||
</div>
|
||||
<p>Creates a WebSocket server listening on the specified host and port.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">host</span> <span class="param-type">(String)</span> - Host to bind to (e.g., "0.0.0.0", "127.0.0.1")</li>
|
||||
<li><span class="param-name">port</span> <span class="param-type">(Num)</span> - Port number</li>
|
||||
</ul>
|
||||
<pre><code>var server = WebSocketServer.bind("0.0.0.0", 8080)</code></pre>
|
||||
|
||||
<h3>Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">accept</span>() → <span class="type">WebSocket|null</span>
|
||||
</div>
|
||||
<p>Accepts and upgrades an incoming connection. Blocks until a client connects. Returns a WebSocket instance for the connected client.</p>
|
||||
<pre><code>var client = server.accept()
|
||||
if (client != null) {
|
||||
System.print("Client connected!")
|
||||
}</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">close</span>()
|
||||
</div>
|
||||
<p>Stops the server and closes the listening socket.</p>
|
||||
|
||||
<h2 id="websocketmessage-class">WebSocketMessage Class</h2>
|
||||
<p>Represents a WebSocket frame received from a connection.</p>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>WebSocketMessage</h3>
|
||||
<p>WebSocket message/frame</p>
|
||||
</div>
|
||||
|
||||
<h3>Properties</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Property</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>opcode</code></td>
|
||||
<td>Num</td>
|
||||
<td>Frame opcode (1=text, 2=binary, 8=close, 9=ping, 10=pong)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>payload</code></td>
|
||||
<td>List</td>
|
||||
<td>Raw payload bytes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fin</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is the final fragment</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isText</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is a text frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isBinary</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is a binary frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isClose</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is a close frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isPing</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is a ping frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isPong</code></td>
|
||||
<td>Bool</td>
|
||||
<td>True if this is a pong frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>text</code></td>
|
||||
<td>String</td>
|
||||
<td>Payload as string (only for text frames)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>bytes</code></td>
|
||||
<td>List</td>
|
||||
<td>Payload as byte list</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>closeCode</code></td>
|
||||
<td>Num</td>
|
||||
<td>Close status code (only for close frames)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>closeReason</code></td>
|
||||
<td>String</td>
|
||||
<td>Close reason text (only for close frames)</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2 id="opcodes">Frame Opcodes</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Opcode</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>0</td>
|
||||
<td>Continuation</td>
|
||||
<td>Continuation of fragmented message</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1</td>
|
||||
<td>Text</td>
|
||||
<td>UTF-8 text data</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td>
|
||||
<td>Binary</td>
|
||||
<td>Binary data</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>8</td>
|
||||
<td>Close</td>
|
||||
<td>Connection close</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>9</td>
|
||||
<td>Ping</td>
|
||||
<td>Ping (keepalive)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>10</td>
|
||||
<td>Pong</td>
|
||||
<td>Pong response</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Common Close Codes</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Code</th>
|
||||
<th>Meaning</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1000</td>
|
||||
<td>Normal closure</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1001</td>
|
||||
<td>Going away (server shutdown)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1002</td>
|
||||
<td>Protocol error</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1003</td>
|
||||
<td>Unsupported data type</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1005</td>
|
||||
<td>No status received</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1006</td>
|
||||
<td>Abnormal closure</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1011</td>
|
||||
<td>Server error</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2 id="examples">Examples</h2>
|
||||
|
||||
<h3>Echo Client</h3>
|
||||
<pre><code>import "websocket" for WebSocket
|
||||
|
||||
var ws = WebSocket.connect("ws://echo.websocket.org")
|
||||
|
||||
ws.send("Hello, WebSocket!")
|
||||
|
||||
var msg = ws.receive()
|
||||
if (msg != null && msg.isText) {
|
||||
System.print("Echo: %(msg.text)")
|
||||
}
|
||||
|
||||
ws.close()</code></pre>
|
||||
|
||||
<h3>Chat Client</h3>
|
||||
<pre><code>import "websocket" for WebSocket
|
||||
import "json" for Json
|
||||
|
||||
var ws = WebSocket.connect("wss://chat.example.com/socket")
|
||||
|
||||
ws.send(Json.stringify({
|
||||
"type": "join",
|
||||
"room": "general",
|
||||
"username": "alice"
|
||||
}))
|
||||
|
||||
while (ws.isOpen) {
|
||||
var msg = ws.receive()
|
||||
if (msg == null) break
|
||||
|
||||
if (msg.isClose) {
|
||||
System.print("Server closed: %(msg.closeCode) %(msg.closeReason)")
|
||||
break
|
||||
}
|
||||
|
||||
if (msg.isText) {
|
||||
var data = Json.parse(msg.text)
|
||||
if (data["type"] == "message") {
|
||||
System.print("%(data["from"]): %(data["text"])")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ws.close()</code></pre>
|
||||
|
||||
<h3>WebSocket Server</h3>
|
||||
<pre><code>import "websocket" for WebSocketServer
|
||||
|
||||
var server = WebSocketServer.bind("0.0.0.0", 8080)
|
||||
System.print("WebSocket server listening on port 8080")
|
||||
|
||||
while (true) {
|
||||
var client = server.accept()
|
||||
if (client == null) continue
|
||||
|
||||
System.print("Client connected")
|
||||
|
||||
while (client.isOpen) {
|
||||
var msg = client.receive()
|
||||
if (msg == null) break
|
||||
|
||||
if (msg.isClose) {
|
||||
System.print("Client disconnected")
|
||||
break
|
||||
}
|
||||
|
||||
if (msg.isText) {
|
||||
System.print("Received: %(msg.text)")
|
||||
client.send("Echo: %(msg.text)")
|
||||
}
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Secure WebSocket (WSS)</h3>
|
||||
<pre><code>import "websocket" for WebSocket
|
||||
|
||||
var ws = WebSocket.connect("wss://secure.example.com/socket")
|
||||
|
||||
ws.send("Secure message")
|
||||
var response = ws.receive()
|
||||
System.print(response.text)
|
||||
|
||||
ws.close()</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Ping frames are automatically responded to with pong frames. You typically do not need to handle ping/pong manually unless implementing custom keepalive logic.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,218 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "yaml" %}
|
||||
{% set breadcrumb = [{"url": "api/index.html", "title": "API Reference"}, {"title": "yaml"}] %}
|
||||
{% set prev_page = {"url": "api/websocket.html", "title": "websocket"} %}
|
||||
{% set next_page = {"url": "tutorials/index.html", "title": "Tutorial List"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>yaml</h1>
|
||||
|
||||
<p>The <code>yaml</code> module provides YAML parsing and stringification. It implements a line-based parser in pure Wren that supports common YAML features including nested structures, lists, and scalar types.</p>
|
||||
|
||||
<pre><code>import "yaml" for Yaml</code></pre>
|
||||
|
||||
<h2>Yaml Class</h2>
|
||||
|
||||
<div class="class-header">
|
||||
<h3>Yaml</h3>
|
||||
<p>YAML parsing and stringification</p>
|
||||
</div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Yaml.parse</span>(<span class="param">text</span>) → <span class="type">Map|List|String|Num|Bool|null</span>
|
||||
</div>
|
||||
<p>Parses a YAML string and returns the corresponding Wren value.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">text</span> <span class="param-type">(String)</span> - YAML string to parse</li>
|
||||
<li><span class="returns">Returns:</span> Parsed value (Map, List, String, Num, Bool, or null)</li>
|
||||
</ul>
|
||||
<pre><code>var data = Yaml.parse("name: Alice\nage: 30")
|
||||
System.print(data["name"]) // Alice
|
||||
System.print(data["age"]) // 30
|
||||
|
||||
var list = Yaml.parse("- one\n- two\n- three")
|
||||
System.print(list[0]) // one</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Yaml.stringify</span>(<span class="param">value</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts a Wren value to a YAML string with default indentation (2 spaces).</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">value</span> <span class="param-type">(any)</span> - Value to stringify</li>
|
||||
<li><span class="returns">Returns:</span> YAML string</li>
|
||||
</ul>
|
||||
<pre><code>var yaml = Yaml.stringify({"name": "Alice", "age": 30})
|
||||
System.print(yaml)
|
||||
// name: Alice
|
||||
// age: 30</code></pre>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">Yaml.stringify</span>(<span class="param">value</span>, <span class="param">indent</span>) → <span class="type">String</span>
|
||||
</div>
|
||||
<p>Converts a Wren value to a YAML string with custom indentation.</p>
|
||||
<ul class="param-list">
|
||||
<li><span class="param-name">value</span> <span class="param-type">(any)</span> - Value to stringify</li>
|
||||
<li><span class="param-name">indent</span> <span class="param-type">(Num)</span> - Number of spaces for indentation</li>
|
||||
<li><span class="returns">Returns:</span> YAML string</li>
|
||||
</ul>
|
||||
<pre><code>var yaml = Yaml.stringify({"server": {"host": "localhost"}}, 4)
|
||||
System.print(yaml)
|
||||
// server:
|
||||
// host: localhost</code></pre>
|
||||
|
||||
<h2>Supported Features</h2>
|
||||
|
||||
<h3>Key-Value Pairs</h3>
|
||||
<pre><code>var data = Yaml.parse("
|
||||
name: Alice
|
||||
age: 30
|
||||
email: alice@example.com
|
||||
")
|
||||
System.print(data["name"]) // Alice</code></pre>
|
||||
|
||||
<h3>Nested Maps</h3>
|
||||
<pre><code>var config = Yaml.parse("
|
||||
database:
|
||||
host: localhost
|
||||
port: 5432
|
||||
credentials:
|
||||
user: admin
|
||||
password: secret
|
||||
")
|
||||
System.print(config["database"]["host"]) // localhost
|
||||
System.print(config["database"]["credentials"]["user"]) // admin</code></pre>
|
||||
|
||||
<h3>Lists</h3>
|
||||
<pre><code>var data = Yaml.parse("
|
||||
languages:
|
||||
- Wren
|
||||
- C
|
||||
- Python
|
||||
")
|
||||
for (lang in data["languages"]) {
|
||||
System.print(lang)
|
||||
}</code></pre>
|
||||
|
||||
<h3>Lists of Maps</h3>
|
||||
<pre><code>var nav = Yaml.parse("
|
||||
pages:
|
||||
- file: index
|
||||
title: Home
|
||||
- file: about
|
||||
title: About Us
|
||||
")
|
||||
for (page in nav["pages"]) {
|
||||
System.print(page["title"])
|
||||
}</code></pre>
|
||||
|
||||
<h3>Comments</h3>
|
||||
<pre><code>var data = Yaml.parse("
|
||||
# This is a comment
|
||||
name: test
|
||||
# Another comment
|
||||
value: 123
|
||||
")
|
||||
System.print(data["name"]) // test</code></pre>
|
||||
|
||||
<h3>Data Types</h3>
|
||||
<pre><code>var types = Yaml.parse("
|
||||
string: hello world
|
||||
number: 42
|
||||
float: 3.14
|
||||
bool_true: true
|
||||
bool_false: false
|
||||
null_value: null
|
||||
tilde_null: ~
|
||||
quoted: \"with:special chars\"
|
||||
")
|
||||
System.print(types["string"]) // hello world (String)
|
||||
System.print(types["number"]) // 42 (Num)
|
||||
System.print(types["bool_true"]) // true (Bool)
|
||||
System.print(types["null_value"]) // null</code></pre>
|
||||
|
||||
<h2>Type Mapping</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<th>YAML Type</th>
|
||||
<th>Wren Type</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>mapping</td>
|
||||
<td>Map</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>sequence</td>
|
||||
<td>List</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>string</td>
|
||||
<td>String</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>integer/float</td>
|
||||
<td>Num</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>true/false</td>
|
||||
<td>Bool</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>null/~</td>
|
||||
<td>null</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
<h3>Configuration File</h3>
|
||||
<pre><code>import "yaml" for Yaml
|
||||
import "io" for File
|
||||
|
||||
var config = Yaml.parse(File.read("config.yaml"))
|
||||
System.print("Server: %(config["server"]["host"]):%(config["server"]["port"])")
|
||||
System.print("Database: %(config["database"]["url"])")</code></pre>
|
||||
|
||||
<h3>Building and Stringifying</h3>
|
||||
<pre><code>import "yaml" for Yaml
|
||||
|
||||
var data = {
|
||||
"name": "Project",
|
||||
"version": "1.0.0",
|
||||
"dependencies": ["wren", "libuv"],
|
||||
"settings": {
|
||||
"debug": true,
|
||||
"timeout": 30
|
||||
}
|
||||
}
|
||||
|
||||
System.print(Yaml.stringify(data))</code></pre>
|
||||
|
||||
<h3>Round-Trip</h3>
|
||||
<pre><code>import "yaml" for Yaml
|
||||
|
||||
var original = "
|
||||
title: Test
|
||||
items:
|
||||
- first
|
||||
- second
|
||||
"
|
||||
var parsed = Yaml.parse(original)
|
||||
var reserialized = Yaml.stringify(parsed)
|
||||
var reparsed = Yaml.parse(reserialized)
|
||||
|
||||
System.print(parsed["title"] == reparsed["title"]) // true</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>This module implements a subset of YAML 1.2 suitable for configuration files. Advanced features like anchors, aliases, multi-line strings with <code>|</code> or <code>></code>, and tags are not supported.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Strings containing special characters (<code>:</code>, <code>#</code>, quotes) should be quoted in YAML input. The stringify method handles this automatically.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,420 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Async Patterns" %}
|
||||
{% set breadcrumb = [{"url": "contributing/index.html", "title": "Contributing"}, {"title": "Async Patterns"}] %}
|
||||
{% set prev_page = {"url": "contributing/foreign-classes.html", "title": "Foreign Classes"} %}
|
||||
{% set next_page = {"url": "contributing/testing.html", "title": "Writing Tests"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Async Patterns</h1>
|
||||
|
||||
<p>Wren-CLI uses libuv for non-blocking I/O. Wren fibers suspend during I/O operations and resume when complete. This section explains how to implement async operations in C-backed modules.</p>
|
||||
|
||||
<h2>The Scheduler/Fiber Pattern</h2>
|
||||
|
||||
<p>The standard pattern for async operations involves:</p>
|
||||
|
||||
<ol>
|
||||
<li>A public Wren method that users call</li>
|
||||
<li>An internal foreign method (ending with <code>_</code>) that takes a fiber handle</li>
|
||||
<li>C code that stores the fiber handle and schedules async work</li>
|
||||
<li>A libuv callback that resumes the fiber with the result</li>
|
||||
</ol>
|
||||
|
||||
<h2>Basic Example</h2>
|
||||
|
||||
<h3>Wren Interface</h3>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "scheduler" for Scheduler
|
||||
|
||||
class AsyncFile {
|
||||
foreign static read_(path, fiber)
|
||||
|
||||
static read(path) {
|
||||
return Scheduler.await_ { read_(path, Fiber.current) }
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<p>The public <code>read</code> method wraps the internal <code>read_</code> method. <code>Scheduler.await_</code> suspends the current fiber until the async operation completes.</p>
|
||||
|
||||
<h3>Naming Convention</h3>
|
||||
|
||||
<ul>
|
||||
<li>Internal methods end with <code>_</code> (e.g., <code>read_</code>, <code>write_</code>)</li>
|
||||
<li>Public methods have clean names (e.g., <code>read</code>, <code>write</code>)</li>
|
||||
<li>Internal methods take a fiber as the last argument</li>
|
||||
</ul>
|
||||
|
||||
<h2>C Implementation Structure</h2>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <uv.h>
|
||||
#include "asyncfile.h"
|
||||
#include "wren.h"
|
||||
#include "vm.h"
|
||||
|
||||
typedef struct {
|
||||
WrenVM* vm;
|
||||
WrenHandle* fiber;
|
||||
uv_fs_t req;
|
||||
char* path;
|
||||
uv_buf_t buffer;
|
||||
} ReadRequest;
|
||||
|
||||
void asyncFileRead(WrenVM* vm) {
|
||||
const char* path = wrenGetSlotString(vm, 1);
|
||||
WrenHandle* fiber = wrenGetSlotHandle(vm, 2);
|
||||
|
||||
ReadRequest* request = (ReadRequest*)malloc(sizeof(ReadRequest));
|
||||
request->vm = vm;
|
||||
request->fiber = fiber;
|
||||
request->path = strdup(path);
|
||||
request->req.data = request;
|
||||
|
||||
uv_loop_t* loop = getLoop();
|
||||
uv_fs_open(loop, &request->req, path, UV_FS_O_RDONLY, 0, onFileOpened);
|
||||
}
|
||||
|
||||
void onFileOpened(uv_fs_t* req) {
|
||||
ReadRequest* request = (ReadRequest*)req->data;
|
||||
uv_fs_req_cleanup(req);
|
||||
|
||||
if (req->result < 0) {
|
||||
resumeWithError(request, "Failed to open file.");
|
||||
return;
|
||||
}
|
||||
|
||||
int fd = (int)req->result;
|
||||
uv_fs_fstat(getLoop(), &request->req, fd, onFileStat);
|
||||
}
|
||||
|
||||
// ... additional callbacks for fstat, read, close ...</code></pre>
|
||||
|
||||
<h2>Fiber Handle Management</h2>
|
||||
|
||||
<h3>Capturing the Fiber</h3>
|
||||
|
||||
<pre><code>WrenHandle* fiber = wrenGetSlotHandle(vm, 2);</code></pre>
|
||||
|
||||
<p>The fiber handle is obtained from the slot where it was passed. This handle must be stored for later use.</p>
|
||||
|
||||
<h3>Resuming the Fiber</h3>
|
||||
|
||||
<p>Use the scheduler's resume mechanism:</p>
|
||||
|
||||
<pre><code>void resumeWithResult(ReadRequest* request, const char* result) {
|
||||
WrenVM* vm = request->vm;
|
||||
|
||||
schedulerResume(request->fiber, true);
|
||||
wrenReleaseHandle(vm, request->fiber);
|
||||
|
||||
wrenEnsureSlots(vm, 1);
|
||||
wrenSetSlotString(vm, 0, result);
|
||||
|
||||
free(request->path);
|
||||
free(request);
|
||||
}
|
||||
|
||||
void resumeWithError(ReadRequest* request, const char* error) {
|
||||
WrenVM* vm = request->vm;
|
||||
|
||||
schedulerResume(request->fiber, false);
|
||||
wrenReleaseHandle(vm, request->fiber);
|
||||
|
||||
wrenEnsureSlots(vm, 1);
|
||||
wrenSetSlotString(vm, 0, error);
|
||||
|
||||
free(request->path);
|
||||
free(request);
|
||||
}</code></pre>
|
||||
|
||||
<h3>schedulerResume</h3>
|
||||
|
||||
<pre><code>void schedulerResume(WrenHandle* fiber, bool success);</code></pre>
|
||||
|
||||
<ul>
|
||||
<li><code>fiber</code>: The fiber handle to resume</li>
|
||||
<li><code>success</code>: true if the operation succeeded, false for error</li>
|
||||
</ul>
|
||||
|
||||
<p>After calling <code>schedulerResume</code>, the value in slot 0 becomes the return value (for success) or error message (for failure).</p>
|
||||
|
||||
<h2>libuv Integration</h2>
|
||||
|
||||
<h3>Getting the Event Loop</h3>
|
||||
|
||||
<pre><code>uv_loop_t* loop = getLoop();</code></pre>
|
||||
|
||||
<p>The <code>getLoop()</code> function returns the global libuv event loop used by Wren-CLI.</p>
|
||||
|
||||
<h3>Common libuv Operations</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Operation</th>
|
||||
<th>libuv Function</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>File read</td>
|
||||
<td><code>uv_fs_read</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>File write</td>
|
||||
<td><code>uv_fs_write</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>TCP connect</td>
|
||||
<td><code>uv_tcp_connect</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>DNS lookup</td>
|
||||
<td><code>uv_getaddrinfo</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Timer</td>
|
||||
<td><code>uv_timer_start</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Process spawn</td>
|
||||
<td><code>uv_spawn</code></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Request Data Pattern</h3>
|
||||
|
||||
<p>Store context in the <code>data</code> field of libuv requests:</p>
|
||||
|
||||
<pre><code>typedef struct {
|
||||
WrenVM* vm;
|
||||
WrenHandle* fiber;
|
||||
// ... operation-specific data ...
|
||||
} MyRequest;
|
||||
|
||||
MyRequest* req = malloc(sizeof(MyRequest));
|
||||
req->vm = vm;
|
||||
req->fiber = fiber;
|
||||
uvReq.data = req;</code></pre>
|
||||
|
||||
<p>In callbacks, retrieve the context:</p>
|
||||
|
||||
<pre><code>void onComplete(uv_xxx_t* uvReq) {
|
||||
MyRequest* req = (MyRequest*)uvReq->data;
|
||||
// ...
|
||||
}</code></pre>
|
||||
|
||||
<h2>Complete Async File Read Example</h2>
|
||||
|
||||
<h3>asyncfile.wren</h3>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "scheduler" for Scheduler
|
||||
|
||||
class AsyncFile {
|
||||
foreign static read_(path, fiber)
|
||||
foreign static write_(path, content, fiber)
|
||||
|
||||
static read(path) {
|
||||
return Scheduler.await_ { read_(path, Fiber.current) }
|
||||
}
|
||||
|
||||
static write(path, content) {
|
||||
return Scheduler.await_ { write_(path, content, Fiber.current) }
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>asyncfile.c (simplified)</h3>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <uv.h>
|
||||
#include "asyncfile.h"
|
||||
#include "wren.h"
|
||||
#include "vm.h"
|
||||
#include "scheduler.h"
|
||||
|
||||
typedef struct {
|
||||
WrenVM* vm;
|
||||
WrenHandle* fiber;
|
||||
uv_fs_t req;
|
||||
uv_file fd;
|
||||
char* buffer;
|
||||
size_t size;
|
||||
} FileRequest;
|
||||
|
||||
static void cleanupRequest(FileRequest* request) {
|
||||
if (request->buffer) free(request->buffer);
|
||||
wrenReleaseHandle(request->vm, request->fiber);
|
||||
free(request);
|
||||
}
|
||||
|
||||
static void onReadComplete(uv_fs_t* req) {
|
||||
FileRequest* request = (FileRequest*)req->data;
|
||||
uv_fs_req_cleanup(req);
|
||||
|
||||
if (req->result < 0) {
|
||||
schedulerResume(request->fiber, false);
|
||||
wrenEnsureSlots(request->vm, 1);
|
||||
wrenSetSlotString(request->vm, 0, "Read failed.");
|
||||
} else {
|
||||
request->buffer[req->result] = '\0';
|
||||
schedulerResume(request->fiber, true);
|
||||
wrenEnsureSlots(request->vm, 1);
|
||||
wrenSetSlotString(request->vm, 0, request->buffer);
|
||||
}
|
||||
|
||||
uv_fs_close(getLoop(), req, request->fd, NULL);
|
||||
cleanupRequest(request);
|
||||
}
|
||||
|
||||
static void onFileStatComplete(uv_fs_t* req) {
|
||||
FileRequest* request = (FileRequest*)req->data;
|
||||
uv_fs_req_cleanup(req);
|
||||
|
||||
if (req->result < 0) {
|
||||
schedulerResume(request->fiber, false);
|
||||
wrenEnsureSlots(request->vm, 1);
|
||||
wrenSetSlotString(request->vm, 0, "Stat failed.");
|
||||
uv_fs_close(getLoop(), req, request->fd, NULL);
|
||||
cleanupRequest(request);
|
||||
return;
|
||||
}
|
||||
|
||||
request->size = req->statbuf.st_size;
|
||||
request->buffer = (char*)malloc(request->size + 1);
|
||||
|
||||
uv_buf_t buf = uv_buf_init(request->buffer, request->size);
|
||||
uv_fs_read(getLoop(), &request->req, request->fd, &buf, 1, 0, onReadComplete);
|
||||
}
|
||||
|
||||
static void onFileOpenComplete(uv_fs_t* req) {
|
||||
FileRequest* request = (FileRequest*)req->data;
|
||||
uv_fs_req_cleanup(req);
|
||||
|
||||
if (req->result < 0) {
|
||||
schedulerResume(request->fiber, false);
|
||||
wrenEnsureSlots(request->vm, 1);
|
||||
wrenSetSlotString(request->vm, 0, "Open failed.");
|
||||
cleanupRequest(request);
|
||||
return;
|
||||
}
|
||||
|
||||
request->fd = (uv_file)req->result;
|
||||
uv_fs_fstat(getLoop(), &request->req, request->fd, onFileStatComplete);
|
||||
}
|
||||
|
||||
void asyncFileRead(WrenVM* vm) {
|
||||
const char* path = wrenGetSlotString(vm, 1);
|
||||
WrenHandle* fiber = wrenGetSlotHandle(vm, 2);
|
||||
|
||||
FileRequest* request = (FileRequest*)malloc(sizeof(FileRequest));
|
||||
request->vm = vm;
|
||||
request->fiber = fiber;
|
||||
request->buffer = NULL;
|
||||
request->req.data = request;
|
||||
|
||||
uv_fs_open(getLoop(), &request->req, path, UV_FS_O_RDONLY, 0, onFileOpenComplete);
|
||||
}</code></pre>
|
||||
|
||||
<h2>Error Handling in Async Operations</h2>
|
||||
|
||||
<h3>libuv Errors</h3>
|
||||
|
||||
<p>Check <code>req->result</code> for negative values:</p>
|
||||
|
||||
<pre><code>if (req->result < 0) {
|
||||
const char* msg = uv_strerror((int)req->result);
|
||||
schedulerResume(request->fiber, false);
|
||||
wrenSetSlotString(request->vm, 0, msg);
|
||||
return;
|
||||
}</code></pre>
|
||||
|
||||
<h3>Propagating to Wren</h3>
|
||||
|
||||
<p>Use <code>schedulerResume(fiber, false)</code> for errors. The value in slot 0 becomes the error that <code>Scheduler.await_</code> throws as a runtime error.</p>
|
||||
|
||||
<h2>Timer Example</h2>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
typedef struct {
|
||||
WrenVM* vm;
|
||||
WrenHandle* fiber;
|
||||
uv_timer_t timer;
|
||||
} TimerRequest;
|
||||
|
||||
static void onTimerComplete(uv_timer_t* timer) {
|
||||
TimerRequest* request = (TimerRequest*)timer->data;
|
||||
|
||||
schedulerResume(request->fiber, true);
|
||||
wrenReleaseHandle(request->vm, request->fiber);
|
||||
wrenEnsureSlots(request->vm, 1);
|
||||
wrenSetSlotNull(request->vm, 0);
|
||||
|
||||
uv_close((uv_handle_t*)timer, NULL);
|
||||
free(request);
|
||||
}
|
||||
|
||||
void timerSleep(WrenVM* vm) {
|
||||
double ms = wrenGetSlotDouble(vm, 1);
|
||||
WrenHandle* fiber = wrenGetSlotHandle(vm, 2);
|
||||
|
||||
TimerRequest* request = (TimerRequest*)malloc(sizeof(TimerRequest));
|
||||
request->vm = vm;
|
||||
request->fiber = fiber;
|
||||
request->timer.data = request;
|
||||
|
||||
uv_timer_init(getLoop(), &request->timer);
|
||||
uv_timer_start(&request->timer, onTimerComplete, (uint64_t)ms, 0);
|
||||
}</code></pre>
|
||||
|
||||
<h2>Multiple Concurrent Operations</h2>
|
||||
|
||||
<p>Each async operation gets its own request structure and fiber. Multiple operations can run concurrently:</p>
|
||||
|
||||
<pre><code>import "asyncfile" for AsyncFile
|
||||
|
||||
var fiber1 = Fiber.new {
|
||||
var a = AsyncFile.read("a.txt")
|
||||
System.print("A: %(a.count) bytes")
|
||||
}
|
||||
|
||||
var fiber2 = Fiber.new {
|
||||
var b = AsyncFile.read("b.txt")
|
||||
System.print("B: %(b.count) bytes")
|
||||
}
|
||||
|
||||
fiber1.call()
|
||||
fiber2.call()</code></pre>
|
||||
|
||||
<h2>Best Practices</h2>
|
||||
|
||||
<ul>
|
||||
<li><strong>Always release fiber handles</strong>: Call <code>wrenReleaseHandle</code> after resuming</li>
|
||||
<li><strong>Cleanup on all paths</strong>: Free resources in both success and error cases</li>
|
||||
<li><strong>Use uv_fs_req_cleanup</strong>: Required after filesystem operations</li>
|
||||
<li><strong>Close handles properly</strong>: Use <code>uv_close</code> for handles like timers and sockets</li>
|
||||
<li><strong>Check for VM validity</strong>: The VM pointer should remain valid during callbacks</li>
|
||||
</ul>
|
||||
|
||||
<h2>Debugging Tips</h2>
|
||||
|
||||
<ul>
|
||||
<li>Add logging in callbacks to trace execution flow</li>
|
||||
<li>Verify libuv error codes with <code>uv_strerror</code></li>
|
||||
<li>Use <code>make debug</code> build for symbols</li>
|
||||
<li>Check for memory leaks with valgrind</li>
|
||||
</ul>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<p>See <a href="testing.html">Writing Tests</a> for testing async operations, including the <code>// skip:</code> annotation for tests that require network access.</p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,412 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "C-Backed Modules" %}
|
||||
{% set breadcrumb = [{"url": "contributing/index.html", "title": "Contributing"}, {"title": "C-Backed Modules"}] %}
|
||||
{% set prev_page = {"url": "contributing/pure-wren-module.html", "title": "Pure-Wren Modules"} %}
|
||||
{% set next_page = {"url": "contributing/foreign-classes.html", "title": "Foreign Classes"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>C-Backed Modules</h1>
|
||||
|
||||
<p>C-backed modules implement foreign methods in C, providing access to system libraries, native performance, or functionality not available in pure Wren. Examples: json, io, net, crypto, tls, sqlite, base64.</p>
|
||||
|
||||
<h2>Step 1: Create the Wren Interface</h2>
|
||||
|
||||
<p>Create <code>src/module/<name>.wren</code> with foreign method declarations:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
class Counter {
|
||||
foreign static create()
|
||||
foreign static increment(handle)
|
||||
foreign static getValue(handle)
|
||||
foreign static destroy(handle)
|
||||
|
||||
static use(fn) {
|
||||
var handle = Counter.create()
|
||||
var result = fn.call(handle)
|
||||
Counter.destroy(handle)
|
||||
return result
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<p>The <code>foreign</code> keyword indicates the method is implemented in C. Non-foreign methods can provide higher-level Wren wrappers around the foreign primitives.</p>
|
||||
|
||||
<h2>Step 2: Generate the .wren.inc</h2>
|
||||
|
||||
<pre><code>python3 util/wren_to_c_string.py src/module/counter.wren.inc src/module/counter.wren</code></pre>
|
||||
|
||||
<h2>Step 3: Create the C Implementation</h2>
|
||||
|
||||
<p>Create <code>src/module/counter.c</code>:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include "counter.h"
|
||||
#include "wren.h"
|
||||
|
||||
typedef struct {
|
||||
int value;
|
||||
} Counter;
|
||||
|
||||
void counterCreate(WrenVM* vm) {
|
||||
Counter* counter = (Counter*)malloc(sizeof(Counter));
|
||||
if (!counter) {
|
||||
wrenSetSlotNull(vm, 0);
|
||||
return;
|
||||
}
|
||||
counter->value = 0;
|
||||
wrenSetSlotDouble(vm, 0, (double)(uintptr_t)counter);
|
||||
}
|
||||
|
||||
void counterIncrement(WrenVM* vm) {
|
||||
double handle = wrenGetSlotDouble(vm, 1);
|
||||
Counter* counter = (Counter*)(uintptr_t)handle;
|
||||
counter->value++;
|
||||
}
|
||||
|
||||
void counterGetValue(WrenVM* vm) {
|
||||
double handle = wrenGetSlotDouble(vm, 1);
|
||||
Counter* counter = (Counter*)(uintptr_t)handle;
|
||||
wrenSetSlotDouble(vm, 0, counter->value);
|
||||
}
|
||||
|
||||
void counterDestroy(WrenVM* vm) {
|
||||
double handle = wrenGetSlotDouble(vm, 1);
|
||||
Counter* counter = (Counter*)(uintptr_t)handle;
|
||||
free(counter);
|
||||
}</code></pre>
|
||||
|
||||
<h2>Step 4: Create the C Header</h2>
|
||||
|
||||
<p>Create <code>src/module/counter.h</code>:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
#ifndef counter_h
|
||||
#define counter_h
|
||||
|
||||
#include "wren.h"
|
||||
|
||||
void counterCreate(WrenVM* vm);
|
||||
void counterIncrement(WrenVM* vm);
|
||||
void counterGetValue(WrenVM* vm);
|
||||
void counterDestroy(WrenVM* vm);
|
||||
|
||||
#endif</code></pre>
|
||||
|
||||
<h2>Step 5: Register in modules.c</h2>
|
||||
|
||||
<p>Edit <code>src/cli/modules.c</code>:</p>
|
||||
|
||||
<h3>Add the Include</h3>
|
||||
<pre><code>#include "counter.wren.inc"</code></pre>
|
||||
|
||||
<h3>Add Extern Declarations</h3>
|
||||
<pre><code>extern void counterCreate(WrenVM* vm);
|
||||
extern void counterIncrement(WrenVM* vm);
|
||||
extern void counterGetValue(WrenVM* vm);
|
||||
extern void counterDestroy(WrenVM* vm);</code></pre>
|
||||
|
||||
<h3>Add the Module Entry</h3>
|
||||
<pre><code>MODULE(counter)
|
||||
CLASS(Counter)
|
||||
STATIC_METHOD("create()", counterCreate)
|
||||
STATIC_METHOD("increment(_)", counterIncrement)
|
||||
STATIC_METHOD("getValue(_)", counterGetValue)
|
||||
STATIC_METHOD("destroy(_)", counterDestroy)
|
||||
END_CLASS
|
||||
END_MODULE</code></pre>
|
||||
|
||||
<h2>Step 6: Update the Makefile</h2>
|
||||
|
||||
<p>Edit <code>projects/make/wren_cli.make</code>:</p>
|
||||
|
||||
<h3>Add to OBJECTS</h3>
|
||||
<pre><code>OBJECTS += $(OBJDIR)/counter.o</code></pre>
|
||||
|
||||
<h3>Add Compilation Rule</h3>
|
||||
<pre><code>$(OBJDIR)/counter.o: ../../src/module/counter.c
|
||||
@echo $(notdir $<)
|
||||
$(SILENT) $(CC) $(ALL_CFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<"</code></pre>
|
||||
|
||||
<h2>Step 7: Build and Test</h2>
|
||||
|
||||
<pre><code>make clean && make build
|
||||
python3 util/test.py counter</code></pre>
|
||||
|
||||
<h2>Wren/C Data Exchange</h2>
|
||||
|
||||
<h3>Getting Values from Wren</h3>
|
||||
|
||||
<pre><code>const char* str = wrenGetSlotString(vm, 1);
|
||||
double num = wrenGetSlotDouble(vm, 1);
|
||||
bool b = wrenGetSlotBool(vm, 1);
|
||||
void* foreign = wrenGetSlotForeign(vm, 0);
|
||||
WrenHandle* handle = wrenGetSlotHandle(vm, 1);
|
||||
int count = wrenGetSlotCount(vm);
|
||||
WrenType type = wrenGetSlotType(vm, 1);</code></pre>
|
||||
|
||||
<h3>Setting Return Values</h3>
|
||||
|
||||
<pre><code>wrenSetSlotString(vm, 0, "result");
|
||||
wrenSetSlotDouble(vm, 0, 42.0);
|
||||
wrenSetSlotBool(vm, 0, true);
|
||||
wrenSetSlotNull(vm, 0);
|
||||
wrenSetSlotNewList(vm, 0);</code></pre>
|
||||
|
||||
<h3>Working with Lists</h3>
|
||||
|
||||
<pre><code>wrenSetSlotNewList(vm, 0);
|
||||
wrenSetSlotString(vm, 1, "item");
|
||||
wrenInsertInList(vm, 0, -1, 1);
|
||||
|
||||
int count = wrenGetListCount(vm, 0);
|
||||
wrenGetListElement(vm, 0, index, 1);</code></pre>
|
||||
|
||||
<h3>Working with Maps</h3>
|
||||
|
||||
<pre><code>wrenSetSlotNewMap(vm, 0);
|
||||
wrenSetSlotString(vm, 1, "key");
|
||||
wrenSetSlotDouble(vm, 2, 123);
|
||||
wrenSetMapValue(vm, 0, 1, 2);</code></pre>
|
||||
|
||||
<h3>Ensuring Slots</h3>
|
||||
|
||||
<pre><code>wrenEnsureSlots(vm, 5);</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Slot 0 is used for the return value and (for instance methods) the receiver. Arguments start at slot 1.</p>
|
||||
</div>
|
||||
|
||||
<h2>Error Handling</h2>
|
||||
|
||||
<p>Use <code>wrenAbortFiber</code> to report errors:</p>
|
||||
|
||||
<pre><code>void myMethod(WrenVM* vm) {
|
||||
const char* path = wrenGetSlotString(vm, 1);
|
||||
|
||||
FILE* file = fopen(path, "r");
|
||||
if (!file) {
|
||||
wrenSetSlotString(vm, 0, "Failed to open file.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// ... process file ...
|
||||
}</code></pre>
|
||||
|
||||
<p>The error message is set in slot 0, then <code>wrenAbortFiber</code> is called with the slot containing the message.</p>
|
||||
|
||||
<h2>Type Checking</h2>
|
||||
|
||||
<p>Verify argument types before using them:</p>
|
||||
|
||||
<pre><code>void myMethod(WrenVM* vm) {
|
||||
if (wrenGetSlotType(vm, 1) != WREN_TYPE_STRING) {
|
||||
wrenSetSlotString(vm, 0, "Argument must be a string.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
const char* str = wrenGetSlotString(vm, 1);
|
||||
// ...
|
||||
}</code></pre>
|
||||
|
||||
<p>WrenType values: <code>WREN_TYPE_BOOL</code>, <code>WREN_TYPE_NUM</code>, <code>WREN_TYPE_FOREIGN</code>, <code>WREN_TYPE_LIST</code>, <code>WREN_TYPE_MAP</code>, <code>WREN_TYPE_NULL</code>, <code>WREN_TYPE_STRING</code>, <code>WREN_TYPE_UNKNOWN</code>.</p>
|
||||
|
||||
<h2>Method Signature Rules</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Wren Declaration</th>
|
||||
<th>Signature String</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>foreign static foo()</code></td>
|
||||
<td><code>"foo()"</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>foreign static foo(a)</code></td>
|
||||
<td><code>"foo(_)"</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>foreign static foo(a, b)</code></td>
|
||||
<td><code>"foo(_,_)"</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>foreign foo()</code></td>
|
||||
<td><code>"foo()"</code> with <code>METHOD</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>foreign name</code> (getter)</td>
|
||||
<td><code>"name"</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>foreign name=(v)</code> (setter)</td>
|
||||
<td><code>"name=(_)"</code></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Complete Example</h2>
|
||||
|
||||
<p>A more realistic example parsing hexadecimal strings:</p>
|
||||
|
||||
<h3>hex.wren</h3>
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
class Hex {
|
||||
foreign static encode(bytes)
|
||||
foreign static decode(str)
|
||||
|
||||
static isValid(str) {
|
||||
for (c in str) {
|
||||
var code = c.bytes[0]
|
||||
var valid = (code >= 48 && code <= 57) ||
|
||||
(code >= 65 && code <= 70) ||
|
||||
(code >= 97 && code <= 102)
|
||||
if (!valid) return false
|
||||
}
|
||||
return str.count \% 2 == 0
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>hex.c</h3>
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "hex.h"
|
||||
#include "wren.h"
|
||||
|
||||
static const char HEX_CHARS[] = "0123456789abcdef";
|
||||
|
||||
void hexEncode(WrenVM* vm) {
|
||||
const char* input = wrenGetSlotString(vm, 1);
|
||||
size_t len = strlen(input);
|
||||
|
||||
char* output = (char*)malloc(len * 2 + 1);
|
||||
if (!output) {
|
||||
wrenSetSlotString(vm, 0, "Memory allocation failed.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
unsigned char c = (unsigned char)input[i];
|
||||
output[i * 2] = HEX_CHARS[(c >> 4) & 0xF];
|
||||
output[i * 2 + 1] = HEX_CHARS[c & 0xF];
|
||||
}
|
||||
output[len * 2] = '\0';
|
||||
|
||||
wrenSetSlotString(vm, 0, output);
|
||||
free(output);
|
||||
}
|
||||
|
||||
static int hexCharToInt(char c) {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
void hexDecode(WrenVM* vm) {
|
||||
const char* input = wrenGetSlotString(vm, 1);
|
||||
size_t len = strlen(input);
|
||||
|
||||
if (len \% 2 != 0) {
|
||||
wrenSetSlotString(vm, 0, "Hex string must have even length.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
char* output = (char*)malloc(len / 2 + 1);
|
||||
if (!output) {
|
||||
wrenSetSlotString(vm, 0, "Memory allocation failed.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < len; i += 2) {
|
||||
int high = hexCharToInt(input[i]);
|
||||
int low = hexCharToInt(input[i + 1]);
|
||||
|
||||
if (high < 0 || low < 0) {
|
||||
free(output);
|
||||
wrenSetSlotString(vm, 0, "Invalid hex character.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
output[i / 2] = (char)((high << 4) | low);
|
||||
}
|
||||
output[len / 2] = '\0';
|
||||
|
||||
wrenSetSlotString(vm, 0, output);
|
||||
free(output);
|
||||
}</code></pre>
|
||||
|
||||
<h3>hex.h</h3>
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
#ifndef hex_h
|
||||
#define hex_h
|
||||
|
||||
#include "wren.h"
|
||||
|
||||
void hexEncode(WrenVM* vm);
|
||||
void hexDecode(WrenVM* vm);
|
||||
|
||||
#endif</code></pre>
|
||||
|
||||
<h3>modules.c entries</h3>
|
||||
<pre><code>#include "hex.wren.inc"
|
||||
|
||||
extern void hexEncode(WrenVM* vm);
|
||||
extern void hexDecode(WrenVM* vm);
|
||||
|
||||
MODULE(hex)
|
||||
CLASS(Hex)
|
||||
STATIC_METHOD("encode(_)", hexEncode)
|
||||
STATIC_METHOD("decode(_)", hexDecode)
|
||||
END_CLASS
|
||||
END_MODULE</code></pre>
|
||||
|
||||
<h2>Common Pitfalls</h2>
|
||||
|
||||
<ul>
|
||||
<li><strong>Stale .wren.inc</strong>: Always regenerate after editing the <code>.wren</code> file</li>
|
||||
<li><strong>Signature mismatch</strong>: The string in <code>STATIC_METHOD("name(_)", fn)</code> must exactly match the Wren declaration's arity</li>
|
||||
<li><strong>Slot management</strong>: Always call <code>wrenEnsureSlots(vm, n)</code> before using high-numbered slots</li>
|
||||
<li><strong>Memory leaks</strong>: Free allocated memory before returning</li>
|
||||
<li><strong>String lifetime</strong>: Strings from <code>wrenGetSlotString</code> are valid only until the next Wren API call</li>
|
||||
<li><strong>make clean</strong>: Required after adding new object files</li>
|
||||
</ul>
|
||||
|
||||
<h2>Checklist</h2>
|
||||
|
||||
<ul>
|
||||
<li>Created <code>src/module/<name>.wren</code> with foreign declarations</li>
|
||||
<li>Generated <code>.wren.inc</code></li>
|
||||
<li>Created <code>src/module/<name>.c</code></li>
|
||||
<li>Created <code>src/module/<name>.h</code></li>
|
||||
<li>Added <code>#include</code> for <code>.wren.inc</code> in modules.c</li>
|
||||
<li>Added extern declarations in modules.c</li>
|
||||
<li>Added <code>MODULE</code>/<code>CLASS</code>/<code>METHOD</code> block in modules.c</li>
|
||||
<li>Added <code>OBJECTS</code> entry in Makefile</li>
|
||||
<li>Added compilation rule in Makefile</li>
|
||||
<li>Built with <code>make clean && make build</code></li>
|
||||
<li>Created tests and example</li>
|
||||
<li>Created documentation page</li>
|
||||
</ul>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<ul>
|
||||
<li><a href="foreign-classes.html">Foreign Classes</a> - for native resource management</li>
|
||||
<li><a href="async-patterns.html">Async Patterns</a> - for non-blocking I/O operations</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,370 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Documentation" %}
|
||||
{% set breadcrumb = [{"url": "contributing/index.html", "title": "Contributing"}, {"title": "Documentation"}] %}
|
||||
{% set prev_page = {"url": "contributing/testing.html", "title": "Writing Tests"} %}
|
||||
{% set next_page = {"url": "api/index.html", "title": "API Reference"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Documentation</h1>
|
||||
|
||||
<p>The Wren-CLI manual is hand-written HTML in <code>manual/</code>. There is no generation step. Every page is a standalone HTML file sharing common CSS and JavaScript.</p>
|
||||
|
||||
<h2>HTML Template</h2>
|
||||
|
||||
<p>Every page follows this structure:</p>
|
||||
|
||||
<pre><code><!DOCTYPE html>
|
||||
<!-- retoor <retoor@molodetz.nl> -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>[Page Title] - Wren-CLI Manual</title>
|
||||
<link rel="stylesheet" href="../css/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button class="mobile-menu-toggle">Menu</button>
|
||||
<div class="container">
|
||||
<aside class="sidebar">
|
||||
<div class="sidebar-header">
|
||||
<h1><a href="../index.html">Wren-CLI</a></h1>
|
||||
<div class="version">v0.4.0</div>
|
||||
</div>
|
||||
<nav class="sidebar-nav">
|
||||
<!-- Auto-generated by sync_sidebar.py -->
|
||||
</nav>
|
||||
</aside>
|
||||
<main class="content">
|
||||
<nav class="breadcrumb">
|
||||
<a href="../index.html">Home</a>
|
||||
<span class="separator">/</span>
|
||||
<a href="index.html">API Reference</a>
|
||||
<span class="separator">/</span>
|
||||
<span>[Current Page]</span>
|
||||
</nav>
|
||||
<article>
|
||||
<h1>[Page Title]</h1>
|
||||
<!-- Content -->
|
||||
</article>
|
||||
<footer class="page-footer">
|
||||
<a href="[prev].html" class="prev">[Previous]</a>
|
||||
<a href="[next].html" class="next">[Next]</a>
|
||||
</footer>
|
||||
</main>
|
||||
</div>
|
||||
<script src="../js/main.js"></script>
|
||||
</body>
|
||||
</html></code></pre>
|
||||
|
||||
<h2>Sidebar Navigation</h2>
|
||||
|
||||
<p>The sidebar is automatically synchronized across all pages by <code>util/sync_sidebar.py</code>. Never edit the sidebar manually.</p>
|
||||
|
||||
<h3>Adding a New Module to the Sidebar</h3>
|
||||
|
||||
<ol>
|
||||
<li>Create the module's HTML page in <code>manual/api/</code></li>
|
||||
<li>Run <code>make sync-manual</code></li>
|
||||
</ol>
|
||||
|
||||
<p>The sync script automatically discovers new API pages and adds them to the sidebar in alphabetical order.</p>
|
||||
|
||||
<h3>Adding a New Section</h3>
|
||||
|
||||
<p>To add a new top-level section (like "Contributing"), edit <code>util/sync_sidebar.py</code> and add an entry to the <code>SECTIONS</code> list:</p>
|
||||
|
||||
<pre><code>{
|
||||
"title": "New Section",
|
||||
"directory": "new-section",
|
||||
"pages": [
|
||||
("index.html", "Overview"),
|
||||
("page1.html", "Page One"),
|
||||
("page2.html", "Page Two"),
|
||||
]
|
||||
},</code></pre>
|
||||
|
||||
<h2>API Page Structure</h2>
|
||||
|
||||
<p>API documentation pages follow a consistent structure:</p>
|
||||
|
||||
<pre><code><h1>modulename</h1>
|
||||
<p>Description paragraph.</p>
|
||||
<pre><code>import "modulename" for ClassName</code></pre>
|
||||
|
||||
<div class="class-header"><h2>Class: ClassName</h2></div>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
<div class="method-signature">
|
||||
<span class="method-name">ClassName.methodName</span>(<span class="param">arg</span>)
|
||||
&rarr; <span class="type">ReturnType</span>
|
||||
</div>
|
||||
<p>Method description.</p>
|
||||
|
||||
<h3>Examples</h3>
|
||||
<pre><code>import "modulename" for ClassName
|
||||
var result = ClassName.methodName("hello")
|
||||
System.print(result)</code></pre></code></pre>
|
||||
|
||||
<h2>CSS Classes</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Class</th>
|
||||
<th>Usage</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>.method-signature</code></td>
|
||||
<td>Method signature box</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>.method-name</code></td>
|
||||
<td>Method name within signature</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>.param</code></td>
|
||||
<td>Parameter name</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>.type</code></td>
|
||||
<td>Return type</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>.class-header</code></td>
|
||||
<td>Class section header</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>.param-list</code></td>
|
||||
<td>Parameter description list</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>.toc</code></td>
|
||||
<td>Table of contents box</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>.admonition</code></td>
|
||||
<td>Note/warning/tip box</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>.example-output</code></td>
|
||||
<td>Expected output display</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Method Signature Format</h2>
|
||||
|
||||
<p>Static method:</p>
|
||||
<pre><code><div class="method-signature">
|
||||
<span class="method-name">ClassName.methodName</span>(<span class="param">arg1</span>, <span class="param">arg2</span>)
|
||||
&rarr; <span class="type">String</span>
|
||||
</div></code></pre>
|
||||
|
||||
<p>Instance method:</p>
|
||||
<pre><code><div class="method-signature">
|
||||
<span class="method-name">instance.methodName</span>(<span class="param">arg</span>)
|
||||
&rarr; <span class="type">Bool</span>
|
||||
</div></code></pre>
|
||||
|
||||
<p>Property (getter):</p>
|
||||
<pre><code><div class="method-signature">
|
||||
<span class="method-name">instance.propertyName</span>
|
||||
&rarr; <span class="type">Num</span>
|
||||
</div></code></pre>
|
||||
|
||||
<h2>Admonition Blocks</h2>
|
||||
|
||||
<p>Use admonitions for notes, warnings, and tips:</p>
|
||||
|
||||
<h3>Note</h3>
|
||||
<pre><code><div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Additional information.</p>
|
||||
</div></code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Additional information.</p>
|
||||
</div>
|
||||
|
||||
<h3>Warning</h3>
|
||||
<pre><code><div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Important caution.</p>
|
||||
</div></code></pre>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Important caution.</p>
|
||||
</div>
|
||||
|
||||
<h3>Tip</h3>
|
||||
<pre><code><div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Helpful suggestion.</p>
|
||||
</div></code></pre>
|
||||
|
||||
<h2>Parameter Lists</h2>
|
||||
|
||||
<p>For methods with complex parameters:</p>
|
||||
|
||||
<pre><code><div class="param-list">
|
||||
<div class="param-item">
|
||||
<span class="param-name">path</span>
|
||||
<span class="param-type">String</span>
|
||||
<p>The file path to read.</p>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">encoding</span>
|
||||
<span class="param-type">String</span>
|
||||
<p>The character encoding (default: "utf-8").</p>
|
||||
</div>
|
||||
</div></code></pre>
|
||||
|
||||
<h2>Tables</h2>
|
||||
|
||||
<p>Use tables for options, type mappings, or comparisons:</p>
|
||||
|
||||
<pre><code><table>
|
||||
<tr>
|
||||
<th>Option</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>"r"</code></td>
|
||||
<td>Read mode</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>"w"</code></td>
|
||||
<td>Write mode</td>
|
||||
</tr>
|
||||
</table></code></pre>
|
||||
|
||||
<h2>Footer Navigation</h2>
|
||||
|
||||
<p>Every page has previous/next navigation:</p>
|
||||
|
||||
<pre><code><footer class="page-footer">
|
||||
<a href="previous.html" class="prev">Previous Page</a>
|
||||
<a href="next.html" class="next">Next Page</a>
|
||||
</footer></code></pre>
|
||||
|
||||
<p>Update the footer on adjacent pages when adding new pages.</p>
|
||||
|
||||
<h2>Breadcrumb Navigation</h2>
|
||||
|
||||
<p>Shows the page hierarchy:</p>
|
||||
|
||||
<pre><code><nav class="breadcrumb">
|
||||
<a href="../index.html">Home</a>
|
||||
<span class="separator">/</span>
|
||||
<a href="index.html">API Reference</a>
|
||||
<span class="separator">/</span>
|
||||
<span>io</span>
|
||||
</nav></code></pre>
|
||||
|
||||
<h2>Syncing the Sidebar</h2>
|
||||
|
||||
<pre><code>make sync-manual</code></pre>
|
||||
|
||||
<p>This runs <code>util/sync_sidebar.py</code> which:</p>
|
||||
|
||||
<ol>
|
||||
<li>Discovers all API module pages</li>
|
||||
<li>Builds the complete sidebar HTML</li>
|
||||
<li>Updates the <code><nav class="sidebar-nav"></code> in every HTML file</li>
|
||||
<li>Sets the <code>active</code> class on the current page's link</li>
|
||||
</ol>
|
||||
|
||||
<p>The script is idempotent - running it twice produces the same result.</p>
|
||||
|
||||
<h2>Adding a New API Page</h2>
|
||||
|
||||
<ol>
|
||||
<li>Create <code>manual/api/<name>.html</code></li>
|
||||
<li>Use the template structure above</li>
|
||||
<li>Run <code>make sync-manual</code></li>
|
||||
<li>Update footer prev/next on adjacent pages</li>
|
||||
<li>Add entry to <code>manual/api/index.html</code></li>
|
||||
</ol>
|
||||
|
||||
<h2>Example: Minimal API Page</h2>
|
||||
|
||||
<pre><code><!DOCTYPE html>
|
||||
<!-- retoor <retoor@molodetz.nl> -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>mymodule - Wren-CLI Manual</title>
|
||||
<link rel="stylesheet" href="../css/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button class="mobile-menu-toggle">Menu</button>
|
||||
<div class="container">
|
||||
<aside class="sidebar">
|
||||
<div class="sidebar-header">
|
||||
<h1><a href="../index.html">Wren-CLI</a></h1>
|
||||
<div class="version">v0.4.0</div>
|
||||
</div>
|
||||
<nav class="sidebar-nav">
|
||||
</nav>
|
||||
</aside>
|
||||
<main class="content">
|
||||
<nav class="breadcrumb">
|
||||
<a href="../index.html">Home</a>
|
||||
<span class="separator">/</span>
|
||||
<a href="index.html">API Reference</a>
|
||||
<span class="separator">/</span>
|
||||
<span>mymodule</span>
|
||||
</nav>
|
||||
|
||||
<article>
|
||||
<h1>mymodule</h1>
|
||||
|
||||
<p>The <code>mymodule</code> module provides...</p>
|
||||
|
||||
<pre><code>import "mymodule" for MyClass</code></pre>
|
||||
|
||||
<h2>MyClass</h2>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
|
||||
<div class="method-signature">
|
||||
<span class="method-name">MyClass.process</span>(<span class="param">input</span>)
|
||||
&rarr; <span class="type">String</span>
|
||||
</div>
|
||||
<p>Processes the input and returns a result.</p>
|
||||
|
||||
<h3>Examples</h3>
|
||||
<pre><code>import "mymodule" for MyClass
|
||||
|
||||
var result = MyClass.process("hello")
|
||||
System.print(result)</code></pre>
|
||||
</article>
|
||||
|
||||
<footer class="page-footer">
|
||||
<a href="math.html" class="prev">math</a>
|
||||
<a href="net.html" class="next">net</a>
|
||||
</footer>
|
||||
</main>
|
||||
</div>
|
||||
<script src="../js/main.js"></script>
|
||||
</body>
|
||||
</html></code></pre>
|
||||
|
||||
<h2>Checklist for New Documentation</h2>
|
||||
|
||||
<ul>
|
||||
<li>Author comment on line 2</li>
|
||||
<li>Correct title in <code><title></code> and <code><h1></code></li>
|
||||
<li>Proper breadcrumb navigation</li>
|
||||
<li>Import statement example</li>
|
||||
<li>All methods documented with signatures</li>
|
||||
<li>Working code examples</li>
|
||||
<li>Footer with prev/next links</li>
|
||||
<li>Ran <code>make sync-manual</code></li>
|
||||
<li>Updated adjacent page footers</li>
|
||||
<li>Added to index page if applicable</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,383 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Foreign Classes" %}
|
||||
{% set breadcrumb = [{"url": "contributing/index.html", "title": "Contributing"}, {"title": "Foreign Classes"}] %}
|
||||
{% set prev_page = {"url": "contributing/c-backed-module.html", "title": "C-Backed Modules"} %}
|
||||
{% set next_page = {"url": "contributing/async-patterns.html", "title": "Async Patterns"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Foreign Classes</h1>
|
||||
|
||||
<p>Foreign classes allow Wren objects to hold native C data. This is used when a Wren object needs to manage resources like file handles, network sockets, database connections, or any native data structure.</p>
|
||||
|
||||
<h2>When to Use Foreign Classes</h2>
|
||||
|
||||
<ul>
|
||||
<li>Wrapping system resources (files, sockets, processes)</li>
|
||||
<li>Managing native library objects</li>
|
||||
<li>Storing data structures more complex than Wren's built-in types</li>
|
||||
<li>Resources requiring explicit cleanup</li>
|
||||
</ul>
|
||||
|
||||
<h2>Architecture</h2>
|
||||
|
||||
<p>A foreign class has three components:</p>
|
||||
|
||||
<ol>
|
||||
<li><strong>Allocate function</strong>: Called when an instance is created via <code>construct new()</code></li>
|
||||
<li><strong>Finalize function</strong>: Called when the garbage collector frees the instance</li>
|
||||
<li><strong>Instance methods</strong>: Operate on the foreign data</li>
|
||||
</ol>
|
||||
|
||||
<h2>Basic Pattern</h2>
|
||||
|
||||
<h3>Wren Interface</h3>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
class Buffer {
|
||||
foreign construct new(size)
|
||||
|
||||
foreign write(data)
|
||||
foreign read()
|
||||
foreign size
|
||||
foreign clear()
|
||||
}</code></pre>
|
||||
|
||||
<p>The constructor uses <code>foreign construct</code> to trigger allocation.</p>
|
||||
|
||||
<h3>C Implementation</h3>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "buffer.h"
|
||||
#include "wren.h"
|
||||
|
||||
typedef struct {
|
||||
char* data;
|
||||
size_t size;
|
||||
size_t capacity;
|
||||
} Buffer;
|
||||
|
||||
void bufferAllocate(WrenVM* vm) {
|
||||
Buffer* buffer = (Buffer*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(Buffer));
|
||||
|
||||
double capacity = wrenGetSlotDouble(vm, 1);
|
||||
buffer->capacity = (size_t)capacity;
|
||||
buffer->size = 0;
|
||||
buffer->data = (char*)malloc(buffer->capacity);
|
||||
|
||||
if (!buffer->data) {
|
||||
buffer->capacity = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void bufferFinalize(void* data) {
|
||||
Buffer* buffer = (Buffer*)data;
|
||||
if (buffer->data) {
|
||||
free(buffer->data);
|
||||
buffer->data = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void bufferWrite(WrenVM* vm) {
|
||||
Buffer* buffer = (Buffer*)wrenGetSlotForeign(vm, 0);
|
||||
const char* str = wrenGetSlotString(vm, 1);
|
||||
size_t len = strlen(str);
|
||||
|
||||
if (buffer->size + len > buffer->capacity) {
|
||||
wrenSetSlotString(vm, 0, "Buffer overflow.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
memcpy(buffer->data + buffer->size, str, len);
|
||||
buffer->size += len;
|
||||
}
|
||||
|
||||
void bufferRead(WrenVM* vm) {
|
||||
Buffer* buffer = (Buffer*)wrenGetSlotForeign(vm, 0);
|
||||
|
||||
char* copy = (char*)malloc(buffer->size + 1);
|
||||
if (!copy) {
|
||||
wrenSetSlotNull(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
memcpy(copy, buffer->data, buffer->size);
|
||||
copy[buffer->size] = '\0';
|
||||
|
||||
wrenSetSlotString(vm, 0, copy);
|
||||
free(copy);
|
||||
}
|
||||
|
||||
void bufferSize(WrenVM* vm) {
|
||||
Buffer* buffer = (Buffer*)wrenGetSlotForeign(vm, 0);
|
||||
wrenSetSlotDouble(vm, 0, (double)buffer->size);
|
||||
}
|
||||
|
||||
void bufferClear(WrenVM* vm) {
|
||||
Buffer* buffer = (Buffer*)wrenGetSlotForeign(vm, 0);
|
||||
buffer->size = 0;
|
||||
}</code></pre>
|
||||
|
||||
<h3>Registration</h3>
|
||||
|
||||
<pre><code>MODULE(buffer)
|
||||
CLASS(Buffer)
|
||||
ALLOCATE(bufferAllocate)
|
||||
FINALIZE(bufferFinalize)
|
||||
METHOD("write(_)", bufferWrite)
|
||||
METHOD("read()", bufferRead)
|
||||
METHOD("size", bufferSize)
|
||||
METHOD("clear()", bufferClear)
|
||||
END_CLASS
|
||||
END_MODULE</code></pre>
|
||||
|
||||
<h2>Memory Management</h2>
|
||||
|
||||
<h3>wrenSetSlotNewForeign</h3>
|
||||
|
||||
<pre><code>void* wrenSetSlotNewForeign(WrenVM* vm, int slot, int classSlot, size_t size);</code></pre>
|
||||
|
||||
<ul>
|
||||
<li><code>slot</code>: Where to place the new instance (usually 0)</li>
|
||||
<li><code>classSlot</code>: Slot containing the class (usually 0 for the current class)</li>
|
||||
<li><code>size</code>: Size of the native data structure</li>
|
||||
</ul>
|
||||
|
||||
<p>Returns a pointer to the allocated memory. This memory is managed by Wren's garbage collector.</p>
|
||||
|
||||
<h3>Finalize Function Signature</h3>
|
||||
|
||||
<pre><code>void myFinalize(void* data);</code></pre>
|
||||
|
||||
<p>The finalize function receives only a pointer to the foreign data, not the VM. This means:</p>
|
||||
|
||||
<ul>
|
||||
<li>No Wren API calls in finalize</li>
|
||||
<li>Cannot throw errors</li>
|
||||
<li>Must be fast (GC is running)</li>
|
||||
<li>Free any resources allocated in allocate or methods</li>
|
||||
</ul>
|
||||
|
||||
<h3>Accessing Foreign Data</h3>
|
||||
|
||||
<p>In instance methods, use <code>wrenGetSlotForeign</code> on slot 0:</p>
|
||||
|
||||
<pre><code>void bufferMethod(WrenVM* vm) {
|
||||
Buffer* buffer = (Buffer*)wrenGetSlotForeign(vm, 0);
|
||||
// buffer points to the struct created in bufferAllocate
|
||||
}</code></pre>
|
||||
|
||||
<h2>File Handle Example</h2>
|
||||
|
||||
<p>A practical example wrapping a file handle:</p>
|
||||
|
||||
<h3>filehandle.wren</h3>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
class FileHandle {
|
||||
foreign construct open(path, mode)
|
||||
|
||||
foreign read()
|
||||
foreign write(data)
|
||||
foreign close()
|
||||
foreign isOpen
|
||||
}</code></pre>
|
||||
|
||||
<h3>filehandle.c</h3>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "filehandle.h"
|
||||
#include "wren.h"
|
||||
|
||||
typedef struct {
|
||||
FILE* file;
|
||||
char* path;
|
||||
} FileHandle;
|
||||
|
||||
void fileHandleAllocate(WrenVM* vm) {
|
||||
FileHandle* handle = (FileHandle*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(FileHandle));
|
||||
|
||||
const char* path = wrenGetSlotString(vm, 1);
|
||||
const char* mode = wrenGetSlotString(vm, 2);
|
||||
|
||||
handle->path = strdup(path);
|
||||
handle->file = fopen(path, mode);
|
||||
|
||||
if (!handle->file) {
|
||||
wrenSetSlotString(vm, 0, "Failed to open file.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void fileHandleFinalize(void* data) {
|
||||
FileHandle* handle = (FileHandle*)data;
|
||||
|
||||
if (handle->file) {
|
||||
fclose(handle->file);
|
||||
handle->file = NULL;
|
||||
}
|
||||
|
||||
if (handle->path) {
|
||||
free(handle->path);
|
||||
handle->path = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void fileHandleRead(WrenVM* vm) {
|
||||
FileHandle* handle = (FileHandle*)wrenGetSlotForeign(vm, 0);
|
||||
|
||||
if (!handle->file) {
|
||||
wrenSetSlotString(vm, 0, "File not open.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
fseek(handle->file, 0, SEEK_END);
|
||||
long size = ftell(handle->file);
|
||||
fseek(handle->file, 0, SEEK_SET);
|
||||
|
||||
char* content = (char*)malloc(size + 1);
|
||||
if (!content) {
|
||||
wrenSetSlotString(vm, 0, "Memory allocation failed.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
fread(content, 1, size, handle->file);
|
||||
content[size] = '\0';
|
||||
|
||||
wrenSetSlotString(vm, 0, content);
|
||||
free(content);
|
||||
}
|
||||
|
||||
void fileHandleWrite(WrenVM* vm) {
|
||||
FileHandle* handle = (FileHandle*)wrenGetSlotForeign(vm, 0);
|
||||
const char* data = wrenGetSlotString(vm, 1);
|
||||
|
||||
if (!handle->file) {
|
||||
wrenSetSlotString(vm, 0, "File not open.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
size_t written = fwrite(data, 1, strlen(data), handle->file);
|
||||
wrenSetSlotDouble(vm, 0, (double)written);
|
||||
}
|
||||
|
||||
void fileHandleClose(WrenVM* vm) {
|
||||
FileHandle* handle = (FileHandle*)wrenGetSlotForeign(vm, 0);
|
||||
|
||||
if (handle->file) {
|
||||
fclose(handle->file);
|
||||
handle->file = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void fileHandleIsOpen(WrenVM* vm) {
|
||||
FileHandle* handle = (FileHandle*)wrenGetSlotForeign(vm, 0);
|
||||
wrenSetSlotBool(vm, 0, handle->file != NULL);
|
||||
}</code></pre>
|
||||
|
||||
<h3>Usage</h3>
|
||||
|
||||
<pre><code>import "filehandle" for FileHandle
|
||||
|
||||
var file = FileHandle.open("test.txt", "w")
|
||||
file.write("Hello, World!")
|
||||
file.close()
|
||||
|
||||
file = FileHandle.open("test.txt", "r")
|
||||
System.print(file.read())
|
||||
file.close()</code></pre>
|
||||
|
||||
<h2>Multiple Foreign Classes</h2>
|
||||
|
||||
<p>A module can have multiple foreign classes:</p>
|
||||
|
||||
<pre><code>MODULE(database)
|
||||
CLASS(Connection)
|
||||
ALLOCATE(connectionAllocate)
|
||||
FINALIZE(connectionFinalize)
|
||||
METHOD("query(_)", connectionQuery)
|
||||
METHOD("close()", connectionClose)
|
||||
END_CLASS
|
||||
CLASS(Statement)
|
||||
ALLOCATE(statementAllocate)
|
||||
FINALIZE(statementFinalize)
|
||||
METHOD("bind(_,_)", statementBind)
|
||||
METHOD("execute()", statementExecute)
|
||||
END_CLASS
|
||||
END_MODULE</code></pre>
|
||||
|
||||
<h2>Resource Safety Patterns</h2>
|
||||
|
||||
<h3>Early Close</h3>
|
||||
<p>Always check if resource is still valid:</p>
|
||||
<pre><code>void handleMethod(WrenVM* vm) {
|
||||
Handle* h = (Handle*)wrenGetSlotForeign(vm, 0);
|
||||
if (!h->resource) {
|
||||
wrenSetSlotString(vm, 0, "Handle already closed.");
|
||||
wrenAbortFiber(vm, 0);
|
||||
return;
|
||||
}
|
||||
// ...
|
||||
}</code></pre>
|
||||
|
||||
<h3>Double-Free Prevention</h3>
|
||||
<p>Set pointers to NULL after freeing:</p>
|
||||
<pre><code>void handleClose(WrenVM* vm) {
|
||||
Handle* h = (Handle*)wrenGetSlotForeign(vm, 0);
|
||||
if (h->resource) {
|
||||
resource_free(h->resource);
|
||||
h->resource = NULL;
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Defensive Finalize</h3>
|
||||
<p>Always handle partially constructed objects:</p>
|
||||
<pre><code>void handleFinalize(void* data) {
|
||||
Handle* h = (Handle*)data;
|
||||
if (h->resource) {
|
||||
resource_free(h->resource);
|
||||
}
|
||||
if (h->name) {
|
||||
free(h->name);
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h2>Common Pitfalls</h2>
|
||||
|
||||
<ul>
|
||||
<li><strong>Forgetting FINALIZE</strong>: Memory leaks for any allocated resources</li>
|
||||
<li><strong>Using VM in finalize</strong>: Causes undefined behavior</li>
|
||||
<li><strong>Wrong slot for foreign data</strong>: Instance methods get <code>this</code> in slot 0</li>
|
||||
<li><strong>Static methods on foreign class</strong>: Use <code>STATIC_METHOD</code> macro, but note that <code>wrenGetSlotForeign</code> is not available (no instance)</li>
|
||||
</ul>
|
||||
|
||||
<h2>Checklist</h2>
|
||||
|
||||
<ul>
|
||||
<li><code>foreign construct</code> in Wren class</li>
|
||||
<li>Allocate function uses <code>wrenSetSlotNewForeign</code></li>
|
||||
<li>Finalize function frees all resources</li>
|
||||
<li><code>ALLOCATE</code> and <code>FINALIZE</code> in registration</li>
|
||||
<li>Instance methods use <code>METHOD</code> (not <code>STATIC_METHOD</code>)</li>
|
||||
<li>Methods access foreign data via slot 0</li>
|
||||
<li>All methods check resource validity</li>
|
||||
</ul>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<p>For I/O-bound foreign classes, see <a href="async-patterns.html">Async Patterns</a> to integrate with the libuv event loop.</p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,128 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Contributing" %}
|
||||
{% set breadcrumb = [{"title": "Contributing"}] %}
|
||||
{% set prev_page = {"url": "howto/error-handling.html", "title": "Error Handling"} %}
|
||||
{% set next_page = {"url": "contributing/module-overview.html", "title": "Module Architecture"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Contributing</h1>
|
||||
|
||||
<p>This guide explains how to contribute new modules to Wren-CLI, write tests, and add documentation. Whether you are adding a pure-Wren module or implementing C-backed foreign methods, this section provides step-by-step instructions.</p>
|
||||
|
||||
<div class="toc">
|
||||
<h4>In This Section</h4>
|
||||
<ul>
|
||||
<li><a href="module-overview.html">Module Architecture</a> - Project structure and artifact matrix</li>
|
||||
<li><a href="pure-wren-module.html">Pure-Wren Modules</a> - Step-by-step for Wren-only modules</li>
|
||||
<li><a href="c-backed-module.html">C-Backed Modules</a> - Implementing foreign methods in C</li>
|
||||
<li><a href="foreign-classes.html">Foreign Classes</a> - Native resource management</li>
|
||||
<li><a href="async-patterns.html">Async Patterns</a> - Scheduler/Fiber and libuv integration</li>
|
||||
<li><a href="testing.html">Writing Tests</a> - Test structure and annotations</li>
|
||||
<li><a href="documentation.html">Documentation</a> - Writing manual pages</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>Prerequisites</h2>
|
||||
|
||||
<p>Before contributing, ensure you have:</p>
|
||||
|
||||
<ul>
|
||||
<li>A working build environment (see <a href="../getting-started/installation.html">Installation</a>)</li>
|
||||
<li>Python 3 (for utility scripts)</li>
|
||||
<li>Basic understanding of <a href="../language/index.html">Wren syntax</a></li>
|
||||
<li>For C-backed modules: familiarity with C and the Wren embedding API</li>
|
||||
</ul>
|
||||
|
||||
<h2>Module Types</h2>
|
||||
|
||||
<p>Wren-CLI supports two types of modules:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
<th>Files Required</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Pure-Wren</td>
|
||||
<td>Modules written entirely in Wren. Examples: argparse, html, jinja, http, markdown, dataset, web, websocket, wdantic, uuid, tempfile</td>
|
||||
<td><code>.wren</code>, <code>.wren.inc</code>, modules.c entry</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>C-Backed</td>
|
||||
<td>Modules with foreign methods implemented in C. Examples: json, io, net, crypto, tls, sqlite, base64</td>
|
||||
<td><code>.wren</code>, <code>.wren.inc</code>, <code>.c</code>, <code>.h</code>, modules.c entry, Makefile entry</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Workflow Checklist</h2>
|
||||
|
||||
<h3>Pure-Wren Module</h3>
|
||||
<ol>
|
||||
<li>Create <code>src/module/<name>.wren</code></li>
|
||||
<li>Generate <code>.wren.inc</code> with <code>python3 util/wren_to_c_string.py</code></li>
|
||||
<li>Add <code>#include</code> and <code>MODULE</code> block in <code>src/cli/modules.c</code></li>
|
||||
<li>Build with <code>make clean && make build</code></li>
|
||||
<li>Create tests in <code>test/<name>/</code></li>
|
||||
<li>Create example in <code>example/<name>_demo.wren</code></li>
|
||||
<li>Create <code>manual/api/<name>.html</code></li>
|
||||
<li>Run <code>make sync-manual</code></li>
|
||||
<li>Verify with <code>python3 util/test.py <name></code></li>
|
||||
</ol>
|
||||
|
||||
<h3>C-Backed Module</h3>
|
||||
<ol>
|
||||
<li>All pure-Wren steps, plus:</li>
|
||||
<li>Create <code>src/module/<name>.c</code> with foreign method implementations</li>
|
||||
<li>Create <code>src/module/<name>.h</code> with function declarations</li>
|
||||
<li>Add extern declarations in <code>modules.c</code></li>
|
||||
<li>Add <code>CLASS</code>/<code>METHOD</code> registrations with correct signatures</li>
|
||||
<li>Add <code>OBJECTS</code> and compilation rule to <code>projects/make/wren_cli.make</code></li>
|
||||
</ol>
|
||||
|
||||
<h2>Build Commands</h2>
|
||||
|
||||
<pre><code>make build # Release build
|
||||
make debug # Debug build
|
||||
make clean # Clean artifacts
|
||||
make tests # Build and run all tests
|
||||
make sync-manual # Sync sidebar across manual pages</code></pre>
|
||||
|
||||
<h2>Directory Structure</h2>
|
||||
|
||||
<pre><code>src/
|
||||
cli/
|
||||
modules.c # Foreign function registry
|
||||
vm.c # VM and module loading
|
||||
module/
|
||||
<name>.wren # Wren interface source
|
||||
<name>.wren.inc # Generated C string literal
|
||||
<name>.c # C implementation (if foreign methods)
|
||||
<name>.h # C header (if foreign methods)
|
||||
|
||||
test/
|
||||
<name>/
|
||||
<feature>.wren # Test files with annotations
|
||||
|
||||
example/
|
||||
<name>_demo.wren # Usage demonstrations
|
||||
|
||||
manual/
|
||||
api/<name>.html # API documentation</code></pre>
|
||||
|
||||
<h2>Getting Help</h2>
|
||||
|
||||
<p>If you encounter issues while contributing:</p>
|
||||
|
||||
<ul>
|
||||
<li>Review existing modules as reference implementations</li>
|
||||
<li>Check the test files for expected behavior patterns</li>
|
||||
<li>Consult the <a href="module-overview.html">Module Architecture</a> section for detailed artifact requirements</li>
|
||||
</ul>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<p>Start with the <a href="module-overview.html">Module Architecture</a> section to understand the project structure, then proceed to the appropriate module guide based on your needs.</p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,221 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Module Architecture" %}
|
||||
{% set breadcrumb = [{"url": "contributing/index.html", "title": "Contributing"}, {"title": "Module Architecture"}] %}
|
||||
{% set prev_page = {"url": "contributing/index.html", "title": "Overview"} %}
|
||||
{% set next_page = {"url": "contributing/pure-wren-module.html", "title": "Pure-Wren Modules"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Module Architecture</h1>
|
||||
|
||||
<p>This section explains how Wren-CLI modules are structured, what files each module type requires, and how the build system processes them.</p>
|
||||
|
||||
<h2>Project Structure</h2>
|
||||
|
||||
<pre><code>src/
|
||||
cli/
|
||||
main.c # Entry point
|
||||
vm.c # VM initialization, libuv event loop, module loading
|
||||
modules.c # Foreign function registry, module registration
|
||||
modules.h # Public interface for module loading/binding
|
||||
path.c # Cross-platform path manipulation
|
||||
module/
|
||||
<name>.wren # Wren interface source
|
||||
<name>.wren.inc # Generated C string literal (do not edit)
|
||||
<name>.c # C implementation (only for foreign methods)
|
||||
<name>.h # C header (only for foreign methods)
|
||||
|
||||
test/
|
||||
<modulename>/
|
||||
<testname>.wren # Test files with inline annotations
|
||||
|
||||
example/
|
||||
<modulename>_demo.wren # Comprehensive usage demonstrations
|
||||
|
||||
manual/
|
||||
api/ # One HTML file per module
|
||||
|
||||
deps/
|
||||
wren/ # Wren language VM
|
||||
libuv/ # Async I/O library
|
||||
cjson/ # JSON parsing library
|
||||
sqlite/ # SQLite database library</code></pre>
|
||||
|
||||
<h2>Module Artifact Matrix</h2>
|
||||
|
||||
<p>Every built-in module has up to six artifacts:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Artifact</th>
|
||||
<th>Path</th>
|
||||
<th>Required?</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Wren source</td>
|
||||
<td><code>src/module/<name>.wren</code></td>
|
||||
<td>Always</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Generated C string</td>
|
||||
<td><code>src/module/<name>.wren.inc</code></td>
|
||||
<td>Always</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>C implementation</td>
|
||||
<td><code>src/module/<name>.c</code></td>
|
||||
<td>Only if foreign methods</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>C header</td>
|
||||
<td><code>src/module/<name>.h</code></td>
|
||||
<td>Only if .c exists</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Registration in modules.c</td>
|
||||
<td><code>src/cli/modules.c</code></td>
|
||||
<td>Always</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Makefile object entry</td>
|
||||
<td><code>projects/make/wren_cli.make</code></td>
|
||||
<td>Only if .c exists</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Pure-Wren modules (argparse, html, jinja, http, markdown, dataset, web, websocket, wdantic, uuid, tempfile, repl) skip the C files and Makefile entry. C-backed modules (json, io, net, crypto, tls, sqlite, base64, etc.) need all six.</p>
|
||||
</div>
|
||||
|
||||
<h2>The .wren to .wren.inc Pipeline</h2>
|
||||
|
||||
<p>Module source code is embedded directly into the compiled binary as C string literals. The script <code>util/wren_to_c_string.py</code> performs this conversion.</p>
|
||||
|
||||
<h3>What It Does</h3>
|
||||
<ol>
|
||||
<li>Reads the <code>.wren</code> file line by line</li>
|
||||
<li>Escapes <code>\</code> to <code>\\</code> and <code>"</code> to <code>\"</code></li>
|
||||
<li>Wraps each line in C string literal quotes with <code>\n</code> appended</li>
|
||||
<li>Outputs a <code>.wren.inc</code> file with a <code>static const char*</code> variable</li>
|
||||
</ol>
|
||||
|
||||
<h3>Variable Naming</h3>
|
||||
<p>The variable name is derived from the filename: <code>foo.wren</code> becomes <code>fooModuleSource</code>. Prefixes <code>opt_</code> and <code>wren_</code> are stripped automatically.</p>
|
||||
|
||||
<h3>Usage</h3>
|
||||
<pre><code>python3 util/wren_to_c_string.py src/module/foo.wren.inc src/module/foo.wren</code></pre>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Every time a <code>.wren</code> file is edited, its <code>.wren.inc</code> must be regenerated. If forgotten, the binary will contain stale module source.</p>
|
||||
</div>
|
||||
|
||||
<h2>Module Registration in modules.c</h2>
|
||||
|
||||
<p><code>src/cli/modules.c</code> has three sections to update:</p>
|
||||
|
||||
<h3>Section 1: Include the .wren.inc</h3>
|
||||
<p>Add at the top of the file with other includes:</p>
|
||||
<pre><code>#include "mymodule.wren.inc"</code></pre>
|
||||
|
||||
<h3>Section 2: Extern Declarations</h3>
|
||||
<p>Only required for C-backed modules:</p>
|
||||
<pre><code>extern void mymoduleDoSomething(WrenVM* vm);
|
||||
extern void mymoduleComplexOp(WrenVM* vm);</code></pre>
|
||||
|
||||
<h3>Section 3: Module Array Entry</h3>
|
||||
|
||||
<p>For pure-Wren modules:</p>
|
||||
<pre><code>MODULE(mymodule)
|
||||
END_MODULE</code></pre>
|
||||
|
||||
<p>For C-backed modules with static methods:</p>
|
||||
<pre><code>MODULE(mymodule)
|
||||
CLASS(MyClass)
|
||||
STATIC_METHOD("doSomething(_)", mymoduleDoSomething)
|
||||
STATIC_METHOD("complexOp_(_,_,_)", mymoduleComplexOp)
|
||||
END_CLASS
|
||||
END_MODULE</code></pre>
|
||||
|
||||
<p>For foreign classes with allocation/finalization:</p>
|
||||
<pre><code>MODULE(mymodule)
|
||||
CLASS(MyForeignClass)
|
||||
ALLOCATE(myClassAllocate)
|
||||
FINALIZE(myClassFinalize)
|
||||
METHOD("doThing(_)", myClassDoThing)
|
||||
END_CLASS
|
||||
END_MODULE</code></pre>
|
||||
|
||||
<h3>Registration Macros Reference</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Macro</th>
|
||||
<th>Usage</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>MODULE(name)</code> / <code>END_MODULE</code></td>
|
||||
<td>Module boundary, name must match import string</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>CLASS(name)</code> / <code>END_CLASS</code></td>
|
||||
<td>Class boundary, name must match Wren class name</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>STATIC_METHOD("sig", fn)</code></td>
|
||||
<td>Bind static foreign method</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>METHOD("sig", fn)</code></td>
|
||||
<td>Bind instance foreign method</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>ALLOCATE(fn)</code></td>
|
||||
<td>Foreign class constructor</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>FINALIZE(fn)</code></td>
|
||||
<td>Foreign class destructor</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Method Signature Format</h3>
|
||||
|
||||
<p>The signature string must exactly match what Wren expects:</p>
|
||||
|
||||
<ul>
|
||||
<li><code>"methodName(_)"</code> - one argument</li>
|
||||
<li><code>"methodName(_,_)"</code> - two arguments</li>
|
||||
<li><code>"propertyName"</code> - getter (no parentheses)</li>
|
||||
<li><code>"propertyName=(_)"</code> - setter</li>
|
||||
</ul>
|
||||
|
||||
<h2>Core Components</h2>
|
||||
|
||||
<h3>vm.c</h3>
|
||||
<p>VM initialization, libuv event loop integration, module resolution. The <code>loadModule()</code> function first checks <code>wren_modules/</code> on disk, then falls back to <code>loadBuiltInModule()</code> which serves embedded <code>.wren.inc</code> strings. The <code>resolveModule()</code> function handles simple imports (bare names to built-in) and relative imports (<code>./</code>, <code>../</code> to file path resolution).</p>
|
||||
|
||||
<h3>modules.c</h3>
|
||||
<p>Central registry of all built-in modules. Contains the <code>modules[]</code> array with module/class/method metadata, the <code>.wren.inc</code> includes, extern declarations for C functions, and lookup functions (<code>findModule</code>, <code>findClass</code>, <code>findMethod</code>).</p>
|
||||
|
||||
<h2>Event Loop</h2>
|
||||
|
||||
<p>All I/O is async via libuv. Wren fibers suspend during I/O operations and resume when complete. The event loop runs after script interpretation via <code>uv_run(loop, UV_RUN_DEFAULT)</code>.</p>
|
||||
|
||||
<h2>System Dependencies</h2>
|
||||
|
||||
<ul>
|
||||
<li>OpenSSL (<code>libssl</code>, <code>libcrypto</code>) - required for TLS/HTTPS support</li>
|
||||
<li>pthreads, dl, m - linked automatically</li>
|
||||
</ul>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<p>Now that you understand the architecture, proceed to:</p>
|
||||
<ul>
|
||||
<li><a href="pure-wren-module.html">Pure-Wren Modules</a> - for modules without C code</li>
|
||||
<li><a href="c-backed-module.html">C-Backed Modules</a> - for modules with foreign methods</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,247 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Pure-Wren Modules" %}
|
||||
{% set breadcrumb = [{"url": "contributing/index.html", "title": "Contributing"}, {"title": "Pure-Wren Modules"}] %}
|
||||
{% set prev_page = {"url": "contributing/module-overview.html", "title": "Module Architecture"} %}
|
||||
{% set next_page = {"url": "contributing/c-backed-module.html", "title": "C-Backed Modules"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Pure-Wren Modules</h1>
|
||||
|
||||
<p>Pure-Wren modules are written entirely in Wren, with no C code required. They may depend on other modules (both pure-Wren and C-backed) but do not implement any foreign methods themselves.</p>
|
||||
|
||||
<p>Examples of pure-Wren modules: argparse, html, jinja, http, markdown, dataset, web, websocket, wdantic, uuid, tempfile.</p>
|
||||
|
||||
<h2>Step 1: Create the Wren Source</h2>
|
||||
|
||||
<p>Create <code>src/module/<name>.wren</code> with your module implementation:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
class Utils {
|
||||
static capitalize(str) {
|
||||
if (str.count == 0) return str
|
||||
return str[0].upcase + str[1..-1]
|
||||
}
|
||||
|
||||
static reverse(str) {
|
||||
var result = ""
|
||||
for (i in (str.count - 1)..0) {
|
||||
result = result + str[i]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
static repeat(str, times) {
|
||||
var result = ""
|
||||
for (i in 0...times) {
|
||||
result = result + str
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
static words(str) {
|
||||
return str.split(" ").where {|w| w.count > 0 }.toList
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Always include the author comment on the first line. Class names should be capitalized and descriptive.</p>
|
||||
</div>
|
||||
|
||||
<h2>Step 2: Generate the .wren.inc</h2>
|
||||
|
||||
<p>Convert the Wren source to a C string literal:</p>
|
||||
|
||||
<pre><code>python3 util/wren_to_c_string.py src/module/utils.wren.inc src/module/utils.wren</code></pre>
|
||||
|
||||
<p>This creates <code>src/module/utils.wren.inc</code> containing:</p>
|
||||
|
||||
<pre><code>static const char* utilsModuleSource =
|
||||
"// retoor <retoor@molodetz.nl>\n"
|
||||
"\n"
|
||||
"class Utils {\n"
|
||||
" static capitalize(str) {\n"
|
||||
// ... rest of the source
|
||||
;</code></pre>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Never edit <code>.wren.inc</code> files directly. Always edit the <code>.wren</code> source and regenerate.</p>
|
||||
</div>
|
||||
|
||||
<h2>Step 3: Register in modules.c</h2>
|
||||
|
||||
<p>Edit <code>src/cli/modules.c</code> to register the new module.</p>
|
||||
|
||||
<h3>Add the Include</h3>
|
||||
<p>Near the top of the file with other includes:</p>
|
||||
<pre><code>#include "utils.wren.inc"</code></pre>
|
||||
|
||||
<h3>Add the Module Entry</h3>
|
||||
<p>In the <code>modules[]</code> array:</p>
|
||||
<pre><code>MODULE(utils)
|
||||
END_MODULE</code></pre>
|
||||
|
||||
<p>For pure-Wren modules, the block is empty. No class or method registrations are needed because there are no foreign bindings.</p>
|
||||
|
||||
<h2>Step 4: Build</h2>
|
||||
|
||||
<pre><code>make clean && make build</code></pre>
|
||||
|
||||
<p>The clean build ensures the new module is properly included.</p>
|
||||
|
||||
<h2>Step 5: Test</h2>
|
||||
|
||||
<p>Create the test directory:</p>
|
||||
<pre><code>mkdir -p test/utils</code></pre>
|
||||
|
||||
<p>Create test files with inline annotations. For example, <code>test/utils/capitalize.wren</code>:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "utils" for Utils
|
||||
|
||||
System.print(Utils.capitalize("hello")) // expect: Hello
|
||||
System.print(Utils.capitalize("WORLD")) // expect: WORLD
|
||||
System.print(Utils.capitalize("")) // expect:</code></pre>
|
||||
|
||||
<p>Run the tests:</p>
|
||||
<pre><code>python3 util/test.py utils</code></pre>
|
||||
|
||||
<h2>Step 6: Create Example</h2>
|
||||
|
||||
<p>Create <code>example/utils_demo.wren</code>:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "utils" for Utils
|
||||
|
||||
System.print("=== Utils Demo ===\n")
|
||||
|
||||
System.print("--- Capitalize ---")
|
||||
System.print(Utils.capitalize("hello"))
|
||||
System.print(Utils.capitalize("wren"))
|
||||
|
||||
System.print("\n--- Reverse ---")
|
||||
System.print(Utils.reverse("hello"))
|
||||
System.print(Utils.reverse("12345"))
|
||||
|
||||
System.print("\n--- Repeat ---")
|
||||
System.print(Utils.repeat("ab", 3))
|
||||
System.print(Utils.repeat("-", 10))
|
||||
|
||||
System.print("\n--- Words ---")
|
||||
var sentence = "The quick brown fox"
|
||||
var wordList = Utils.words(sentence)
|
||||
for (word in wordList) {
|
||||
System.print(" - %(word)")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Step 7: Add Documentation</h2>
|
||||
|
||||
<p>Create <code>manual/api/utils.html</code> following the API page template. See the <a href="documentation.html">Documentation</a> section for details.</p>
|
||||
|
||||
<h2>Step 8: Sync the Sidebar</h2>
|
||||
|
||||
<pre><code>make sync-manual</code></pre>
|
||||
|
||||
<p>This updates the sidebar navigation across all manual pages to include the new module.</p>
|
||||
|
||||
<h2>Step 9: Verify</h2>
|
||||
|
||||
<pre><code>python3 util/test.py utils
|
||||
bin/wren_cli example/utils_demo.wren</code></pre>
|
||||
|
||||
<h2>Complete Example</h2>
|
||||
|
||||
<p>Here is a more realistic pure-Wren module that builds on existing modules:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "json" for Json
|
||||
import "io" for File
|
||||
|
||||
class Config {
|
||||
static load(path) {
|
||||
var content = File.read(path)
|
||||
return Json.parse(content)
|
||||
}
|
||||
|
||||
static save(path, data) {
|
||||
var content = Json.stringify(data, 2)
|
||||
File.write(path, content)
|
||||
}
|
||||
|
||||
static get(path, key) {
|
||||
var config = Config.load(path)
|
||||
return config[key]
|
||||
}
|
||||
|
||||
static set(path, key, value) {
|
||||
var config = {}
|
||||
if (File.exists(path)) {
|
||||
config = Config.load(path)
|
||||
}
|
||||
config[key] = value
|
||||
Config.save(path, config)
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<p>This module depends on <code>json</code> and <code>io</code>, demonstrating how pure-Wren modules compose functionality from other modules.</p>
|
||||
|
||||
<h2>Common Patterns</h2>
|
||||
|
||||
<h3>Static Utility Classes</h3>
|
||||
<p>Most pure-Wren modules use static methods for stateless utilities:</p>
|
||||
<pre><code>class StringUtils {
|
||||
static trim(s) { ... }
|
||||
static pad(s, width) { ... }
|
||||
}</code></pre>
|
||||
|
||||
<h3>Factory Classes</h3>
|
||||
<p>For stateful objects, use instance methods:</p>
|
||||
<pre><code>class Builder {
|
||||
construct new() {
|
||||
_parts = []
|
||||
}
|
||||
|
||||
add(part) {
|
||||
_parts.add(part)
|
||||
return this
|
||||
}
|
||||
|
||||
build() { _parts.join("") }
|
||||
}</code></pre>
|
||||
|
||||
<h3>Wrapping Async Operations</h3>
|
||||
<p>Pure-Wren modules can wrap async operations from C-backed modules:</p>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
class Api {
|
||||
static get(endpoint) {
|
||||
return Http.get("https://api.example.com" + endpoint)
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h2>Checklist</h2>
|
||||
|
||||
<ul>
|
||||
<li>Created <code>src/module/<name>.wren</code> with author comment</li>
|
||||
<li>Generated <code>.wren.inc</code> with util script</li>
|
||||
<li>Added <code>#include</code> in modules.c</li>
|
||||
<li>Added <code>MODULE</code>/<code>END_MODULE</code> block in modules.c</li>
|
||||
<li>Built with <code>make clean && make build</code></li>
|
||||
<li>Created tests in <code>test/<name>/</code></li>
|
||||
<li>Created example in <code>example/<name>_demo.wren</code></li>
|
||||
<li>Created documentation page</li>
|
||||
<li>Ran <code>make sync-manual</code></li>
|
||||
<li>All tests pass</li>
|
||||
</ul>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<p>If your module requires native functionality not available through existing modules, see <a href="c-backed-module.html">C-Backed Modules</a>.</p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,314 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Writing Tests" %}
|
||||
{% set breadcrumb = [{"url": "contributing/index.html", "title": "Contributing"}, {"title": "Writing Tests"}] %}
|
||||
{% set prev_page = {"url": "contributing/async-patterns.html", "title": "Async Patterns"} %}
|
||||
{% set next_page = {"url": "contributing/documentation.html", "title": "Documentation"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Writing Tests</h1>
|
||||
|
||||
<p>Wren-CLI uses inline annotations in test files to specify expected behavior. The test runner <code>util/test.py</code> parses these annotations and verifies the output.</p>
|
||||
|
||||
<h2>Test Directory Structure</h2>
|
||||
|
||||
<pre><code>test/
|
||||
<modulename>/
|
||||
<feature>.wren # Functional tests
|
||||
error_<scenario>.wren # Error case tests (one runtime error each)</code></pre>
|
||||
|
||||
<p>Each module has its own directory under <code>test/</code>. Test files are named descriptively based on what they test.</p>
|
||||
|
||||
<h2>Running Tests</h2>
|
||||
|
||||
<pre><code># Build and run all tests
|
||||
make tests
|
||||
|
||||
# Run tests for a specific module
|
||||
python3 util/test.py json
|
||||
|
||||
# Run a specific test file (prefix match)
|
||||
python3 util/test.py json/parse
|
||||
|
||||
# Run with debug binary
|
||||
python3 util/test.py --suffix=_d</code></pre>
|
||||
|
||||
<h2>Test Annotations</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Annotation</th>
|
||||
<th>Purpose</th>
|
||||
<th>Expected Exit Code</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>// expect: output</code></td>
|
||||
<td>Assert stdout line (matched in order)</td>
|
||||
<td>0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>// expect error</code></td>
|
||||
<td>Assert compile error on this line</td>
|
||||
<td>65</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>// expect error line N</code></td>
|
||||
<td>Assert compile error on line N</td>
|
||||
<td>65</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>// expect runtime error: msg</code></td>
|
||||
<td>Assert runtime error with exact message</td>
|
||||
<td>70</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>// expect handled runtime error: msg</code></td>
|
||||
<td>Assert caught runtime error</td>
|
||||
<td>0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>// stdin: text</code></td>
|
||||
<td>Feed text to stdin (repeatable)</td>
|
||||
<td>-</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>// skip: reason</code></td>
|
||||
<td>Skip this test file</td>
|
||||
<td>-</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>// nontest</code></td>
|
||||
<td>Ignore this file</td>
|
||||
<td>-</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Basic Test Example</h2>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "json" for Json
|
||||
|
||||
var obj = {"name": "test", "value": 42}
|
||||
var str = Json.stringify(obj)
|
||||
var parsed = Json.parse(str)
|
||||
|
||||
System.print(parsed["name"]) // expect: test
|
||||
System.print(parsed["value"]) // expect: 42</code></pre>
|
||||
|
||||
<p>Each <code>// expect:</code> annotation asserts that the corresponding line of output matches exactly.</p>
|
||||
|
||||
<h2>Multiple Expect Annotations</h2>
|
||||
|
||||
<p>Multiple expectations are matched in order:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "utils" for Utils
|
||||
|
||||
System.print(Utils.capitalize("hello")) // expect: Hello
|
||||
System.print(Utils.capitalize("world")) // expect: World
|
||||
System.print(Utils.capitalize("UPPER")) // expect: UPPER
|
||||
System.print(Utils.capitalize("")) // expect:</code></pre>
|
||||
|
||||
<p>The empty <code>// expect:</code> matches an empty line.</p>
|
||||
|
||||
<h2>Runtime Error Tests</h2>
|
||||
|
||||
<p>For testing error conditions, create a separate file per error case:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "json" for Json
|
||||
|
||||
Json.parse("invalid json") // expect runtime error: Invalid JSON.</code></pre>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Only one runtime error per test file. The test runner tracks a single expected error. Split multiple error cases into separate files.</p>
|
||||
</div>
|
||||
|
||||
<h3>Error Line Matching</h3>
|
||||
|
||||
<p>The runtime error annotation must be on the line that calls the aborting code. The runner checks the stack trace for a <code>test/...</code> path and matches the line number.</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "io" for File
|
||||
|
||||
var content = File.read("/nonexistent/path") // expect runtime error: Cannot open file.</code></pre>
|
||||
|
||||
<h2>Compile Error Tests</h2>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
class Test {
|
||||
foo( // expect error
|
||||
}</code></pre>
|
||||
|
||||
<p>Or specify a different line number:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
// This is valid
|
||||
var x = 1
|
||||
|
||||
class Broken {
|
||||
// expect error line 7
|
||||
foo(</code></pre>
|
||||
|
||||
<h2>Stdin Input</h2>
|
||||
|
||||
<p>Use <code>// stdin:</code> to provide input:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "io" for Stdin
|
||||
|
||||
// stdin: hello
|
||||
// stdin: world
|
||||
|
||||
var line1 = Stdin.readLine()
|
||||
var line2 = Stdin.readLine()
|
||||
|
||||
System.print(line1) // expect: hello
|
||||
System.print(line2) // expect: world</code></pre>
|
||||
|
||||
<p>Multiple <code>// stdin:</code> lines are concatenated with newlines.</p>
|
||||
|
||||
<h2>Skipping Tests</h2>
|
||||
|
||||
<p>Use <code>// skip:</code> for tests that cannot run in all environments:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
// skip: Requires network access
|
||||
|
||||
import "http" for Http
|
||||
|
||||
var response = Http.get("https://example.com")
|
||||
System.print(response.status) // expect: 200</code></pre>
|
||||
|
||||
<h2>Non-Test Files</h2>
|
||||
|
||||
<p>Use <code>// nontest</code> for helper files that should not be run as tests:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
// nontest
|
||||
|
||||
class TestHelper {
|
||||
static setup() { ... }
|
||||
}</code></pre>
|
||||
|
||||
<h2>Test File Organization</h2>
|
||||
|
||||
<h3>Feature Tests</h3>
|
||||
|
||||
<p>Test each feature in a dedicated file:</p>
|
||||
|
||||
<pre><code>test/json/
|
||||
parse.wren # Basic parsing
|
||||
parse_nested.wren # Nested objects/arrays
|
||||
stringify.wren # JSON serialization
|
||||
stringify_pretty.wren # Pretty printing
|
||||
types.wren # Type handling</code></pre>
|
||||
|
||||
<h3>Error Tests</h3>
|
||||
|
||||
<p>One error per file, named with <code>error_</code> prefix:</p>
|
||||
|
||||
<pre><code>test/json/
|
||||
error_invalid_syntax.wren
|
||||
error_unexpected_eof.wren
|
||||
error_invalid_escape.wren</code></pre>
|
||||
|
||||
<h2>Handled Runtime Error</h2>
|
||||
|
||||
<p>For testing error handling where errors are caught:</p>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "json" for Json
|
||||
|
||||
var result = Fiber.new {
|
||||
Json.parse("bad")
|
||||
}.try()
|
||||
|
||||
if (result.error) {
|
||||
System.print("Caught error") // expect: Caught error
|
||||
} // expect handled runtime error: Invalid JSON.</code></pre>
|
||||
|
||||
<h2>Test Timeout</h2>
|
||||
|
||||
<p>Each test file has a 15-second timeout. If a test hangs (e.g., waiting for input that never comes), it will be killed.</p>
|
||||
|
||||
<h2>Test Discovery</h2>
|
||||
|
||||
<p>The test runner discovers tests by:</p>
|
||||
|
||||
<ol>
|
||||
<li>Walking the <code>test/</code> directory recursively</li>
|
||||
<li>Filtering by <code>.wren</code> extension</li>
|
||||
<li>Converting paths to relative paths from <code>test/</code></li>
|
||||
<li>Checking if path starts with the filter argument</li>
|
||||
</ol>
|
||||
|
||||
<p>This means:</p>
|
||||
<ul>
|
||||
<li><code>python3 util/test.py json</code> runs everything in <code>test/json/</code></li>
|
||||
<li><code>python3 util/test.py io/file</code> runs everything in <code>test/io/file/</code></li>
|
||||
<li>Subdirectories are supported for organizing large test suites</li>
|
||||
</ul>
|
||||
|
||||
<h2>Example Test Suite</h2>
|
||||
|
||||
<pre><code>test/mymodule/
|
||||
basic.wren
|
||||
advanced.wren
|
||||
edge_cases.wren
|
||||
error_null_input.wren
|
||||
error_invalid_type.wren
|
||||
error_overflow.wren</code></pre>
|
||||
|
||||
<h3>basic.wren</h3>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "mymodule" for MyClass
|
||||
|
||||
System.print(MyClass.process("hello")) // expect: HELLO
|
||||
System.print(MyClass.process("world")) // expect: WORLD
|
||||
System.print(MyClass.length("test")) // expect: 4</code></pre>
|
||||
|
||||
<h3>error_null_input.wren</h3>
|
||||
|
||||
<pre><code>// retoor <retoor@molodetz.nl>
|
||||
|
||||
import "mymodule" for MyClass
|
||||
|
||||
MyClass.process(null) // expect runtime error: Input cannot be null.</code></pre>
|
||||
|
||||
<h2>Debugging Failing Tests</h2>
|
||||
|
||||
<ol>
|
||||
<li>Run the test manually: <code>bin/wren_cli test/mymodule/failing.wren</code></li>
|
||||
<li>Check the actual output versus expected</li>
|
||||
<li>Verify annotations are on correct lines</li>
|
||||
<li>For runtime errors, ensure annotation is on the calling line</li>
|
||||
</ol>
|
||||
|
||||
<h2>Best Practices</h2>
|
||||
|
||||
<ul>
|
||||
<li>Test one concept per file when possible</li>
|
||||
<li>Use descriptive file names</li>
|
||||
<li>Always include the author comment</li>
|
||||
<li>Test edge cases (empty strings, null, large values)</li>
|
||||
<li>Test error conditions in separate files</li>
|
||||
<li>Keep tests simple and focused</li>
|
||||
</ul>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<p>After writing tests, add documentation in <a href="documentation.html">Documentation</a>.</p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,203 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "First Script" %}
|
||||
{% set breadcrumb = [{"url": "getting-started/index.html", "title": "Getting Started"}, {"title": "First Script"}] %}
|
||||
{% set prev_page = {"url": "getting-started/installation.html", "title": "Installation"} %}
|
||||
{% set next_page = {"url": "getting-started/repl.html", "title": "Using the REPL"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>First Script</h1>
|
||||
|
||||
<p>This guide walks you through creating and running your first Wren script. You will learn the basics of printing output, using variables, and importing modules.</p>
|
||||
|
||||
<h2>Hello World</h2>
|
||||
<p>Create a file named <code>hello.wren</code> with the following content:</p>
|
||||
<pre><code>System.print("Hello, World!")</code></pre>
|
||||
|
||||
<p>Run it:</p>
|
||||
<pre><code>bin/wren_cli hello.wren</code></pre>
|
||||
|
||||
<div class="example-output">Hello, World!</div>
|
||||
|
||||
<p>The <code>System.print</code> method outputs text to the console followed by a newline.</p>
|
||||
|
||||
<h2>Variables and Types</h2>
|
||||
<p>Wren is dynamically typed. Use <code>var</code> to declare variables:</p>
|
||||
<pre><code>var name = "Wren"
|
||||
var version = 0.4
|
||||
var features = ["fast", "small", "class-based"]
|
||||
var active = true
|
||||
|
||||
System.print("Language: %(name)")
|
||||
System.print("Version: %(version)")
|
||||
System.print("Features: %(features)")
|
||||
System.print("Active: %(active)")</code></pre>
|
||||
|
||||
<div class="example-output">Language: Wren
|
||||
Version: 0.4
|
||||
Features: [fast, small, class-based]
|
||||
Active: true</div>
|
||||
|
||||
<p>The <code>%(expression)</code> syntax is string interpolation. It evaluates the expression and inserts the result into the string.</p>
|
||||
|
||||
<h2>Working with Lists and Maps</h2>
|
||||
<pre><code>var numbers = [1, 2, 3, 4, 5]
|
||||
System.print("Count: %(numbers.count)")
|
||||
System.print("First: %(numbers[0])")
|
||||
System.print("Last: %(numbers[-1])")
|
||||
|
||||
var person = {
|
||||
"name": "Alice",
|
||||
"age": 30,
|
||||
"city": "Amsterdam"
|
||||
}
|
||||
System.print("Name: %(person["name"])")</code></pre>
|
||||
|
||||
<div class="example-output">Count: 5
|
||||
First: 1
|
||||
Last: 5
|
||||
Name: Alice</div>
|
||||
|
||||
<h2>Control Flow</h2>
|
||||
<pre><code>var score = 85
|
||||
|
||||
if (score >= 90) {
|
||||
System.print("Grade: A")
|
||||
} else if (score >= 80) {
|
||||
System.print("Grade: B")
|
||||
} else {
|
||||
System.print("Grade: C")
|
||||
}
|
||||
|
||||
for (i in 1..5) {
|
||||
System.print("Count: %(i)")
|
||||
}</code></pre>
|
||||
|
||||
<div class="example-output">Grade: B
|
||||
Count: 1
|
||||
Count: 2
|
||||
Count: 3
|
||||
Count: 4
|
||||
Count: 5</div>
|
||||
|
||||
<h2>Functions</h2>
|
||||
<p>Functions in Wren are created using block syntax:</p>
|
||||
<pre><code>var greet = Fn.new { |name|
|
||||
return "Hello, %(name)!"
|
||||
}
|
||||
|
||||
System.print(greet.call("World"))
|
||||
|
||||
var add = Fn.new { |a, b| a + b }
|
||||
System.print(add.call(3, 4))</code></pre>
|
||||
|
||||
<div class="example-output">Hello, World!
|
||||
7</div>
|
||||
|
||||
<h2>Classes</h2>
|
||||
<pre><code>class Person {
|
||||
construct new(name, age) {
|
||||
_name = name
|
||||
_age = age
|
||||
}
|
||||
|
||||
name { _name }
|
||||
age { _age }
|
||||
|
||||
greet() {
|
||||
System.print("Hello, I'm %(_name)")
|
||||
}
|
||||
}
|
||||
|
||||
var alice = Person.new("Alice", 30)
|
||||
alice.greet()
|
||||
System.print("Age: %(alice.age)")</code></pre>
|
||||
|
||||
<div class="example-output">Hello, I'm Alice
|
||||
Age: 30</div>
|
||||
|
||||
<h2>Using Modules</h2>
|
||||
<p>Wren-CLI provides many built-in modules. Import them to use their functionality:</p>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
var content = File.read("hello.wren")
|
||||
System.print("File contents:")
|
||||
System.print(content)</code></pre>
|
||||
|
||||
<h3>Making HTTP Requests</h3>
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
var response = Http.get("https://httpbin.org/get")
|
||||
System.print("Status: %(response.status)")
|
||||
|
||||
var data = Json.parse(response.body)
|
||||
System.print("Origin: %(data["origin"])")</code></pre>
|
||||
|
||||
<h3>Working with JSON</h3>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var data = {
|
||||
"name": "Wren",
|
||||
"version": 0.4,
|
||||
"features": ["fast", "small"]
|
||||
}
|
||||
|
||||
var jsonString = Json.stringify(data)
|
||||
System.print(jsonString)
|
||||
|
||||
var parsed = Json.parse(jsonString)
|
||||
System.print("Name: %(parsed["name"])")</code></pre>
|
||||
|
||||
<h2>Error Handling</h2>
|
||||
<p>Use <code>Fiber.try</code> to catch runtime errors:</p>
|
||||
<pre><code>var fiber = Fiber.new {
|
||||
var x = 1 / 0
|
||||
}
|
||||
|
||||
var error = fiber.try()
|
||||
if (error) {
|
||||
System.print("Error: %(error)")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Script Arguments</h2>
|
||||
<p>Access command-line arguments via <code>Process.arguments</code>:</p>
|
||||
<pre><code>import "os" for Process
|
||||
|
||||
System.print("Script arguments:")
|
||||
for (arg in Process.arguments) {
|
||||
System.print(" %(arg)")
|
||||
}</code></pre>
|
||||
|
||||
<p>Run with arguments:</p>
|
||||
<pre><code>bin/wren_cli script.wren arg1 arg2 arg3</code></pre>
|
||||
|
||||
<h2>Exit Codes</h2>
|
||||
<p>Wren-CLI uses these exit codes:</p>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Code</th>
|
||||
<th>Meaning</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>0</td>
|
||||
<td>Success</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>65</td>
|
||||
<td>Compile error (syntax error)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>70</td>
|
||||
<td>Runtime error</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
<ul>
|
||||
<li><a href="repl.html">Using the REPL</a> - Interactive experimentation</li>
|
||||
<li><a href="../language/index.html">Language Reference</a> - Deep dive into Wren syntax</li>
|
||||
<li><a href="../tutorials/index.html">Tutorials</a> - Build real applications</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,104 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Getting Started" %}
|
||||
{% set breadcrumb = [{"title": "Getting Started"}] %}
|
||||
{% set prev_page = {"url": "index.html", "title": "Home"} %}
|
||||
{% set next_page = {"url": "getting-started/installation.html", "title": "Installation"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Getting Started</h1>
|
||||
|
||||
<p>Welcome to Wren-CLI, a command-line interface for the Wren programming language extended with powerful modules for networking, file I/O, databases, and more.</p>
|
||||
|
||||
<div class="toc">
|
||||
<h4>In This Section</h4>
|
||||
<ul>
|
||||
<li><a href="installation.html">Installation</a> - Build from source on Linux, macOS, or FreeBSD</li>
|
||||
<li><a href="first-script.html">First Script</a> - Write and run your first Wren program</li>
|
||||
<li><a href="repl.html">Using the REPL</a> - Interactive experimentation</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>What is Wren?</h2>
|
||||
<p>Wren is a small, fast, class-based scripting language. It has a familiar syntax, first-class functions, and a fiber-based concurrency model. Wren-CLI extends the core language with modules for:</p>
|
||||
<ul>
|
||||
<li>HTTP and WebSocket networking</li>
|
||||
<li>File and directory operations</li>
|
||||
<li>SQLite database access</li>
|
||||
<li>JSON and regex processing</li>
|
||||
<li>Template rendering (Jinja2-compatible)</li>
|
||||
<li>Cryptographic operations</li>
|
||||
<li>Process and signal handling</li>
|
||||
</ul>
|
||||
|
||||
<h2>Quick Start</h2>
|
||||
<p>If you want to dive right in, here is the fastest path to running your first script:</p>
|
||||
|
||||
<h3>1. Build</h3>
|
||||
<pre><code>git clone https://github.com/wren-lang/wren-cli.git
|
||||
cd wren-cli
|
||||
cd projects/make && make</code></pre>
|
||||
|
||||
<h3>2. Create a Script</h3>
|
||||
<p>Create a file named <code>hello.wren</code>:</p>
|
||||
<pre><code>System.print("Hello, Wren!")</code></pre>
|
||||
|
||||
<h3>3. Run</h3>
|
||||
<pre><code>bin/wren_cli hello.wren</code></pre>
|
||||
|
||||
<div class="example-output">Hello, Wren!</div>
|
||||
|
||||
<h2>Key Concepts</h2>
|
||||
<p>Before diving deeper, understand these fundamental Wren concepts:</p>
|
||||
|
||||
<h3>Everything is an Object</h3>
|
||||
<p>In Wren, everything is an object, including numbers, strings, and functions. Every object is an instance of a class.</p>
|
||||
<pre><code>var name = "Wren"
|
||||
System.print(name.count) // 4
|
||||
System.print(name.bytes[0]) // 87 (ASCII for 'W')</code></pre>
|
||||
|
||||
<h3>Fibers for Concurrency</h3>
|
||||
<p>Wren uses fibers (cooperative threads) for concurrency. The scheduler module manages async operations.</p>
|
||||
<pre><code>import "timer" for Timer
|
||||
|
||||
Timer.sleep(1000) // Pauses for 1 second
|
||||
System.print("Done waiting")</code></pre>
|
||||
|
||||
<h3>Module System</h3>
|
||||
<p>Functionality is organized into modules that you import as needed:</p>
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
var response = Http.get("https://api.example.com/data")
|
||||
var data = Json.parse(response.body)</code></pre>
|
||||
|
||||
<h2>System Requirements</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Platform</th>
|
||||
<th>Requirements</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Linux</td>
|
||||
<td>GCC, Make, OpenSSL development libraries</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>macOS</td>
|
||||
<td>Xcode Command Line Tools, OpenSSL (via Homebrew)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>FreeBSD</td>
|
||||
<td>GCC or Clang, gmake, OpenSSL</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
<p>Continue with the following sections to learn more:</p>
|
||||
<ul>
|
||||
<li><a href="installation.html">Installation</a> - Detailed build instructions for all platforms</li>
|
||||
<li><a href="first-script.html">First Script</a> - A more detailed walkthrough of your first program</li>
|
||||
<li><a href="../language/index.html">Language Reference</a> - Learn the Wren language syntax</li>
|
||||
<li><a href="../api/index.html">API Reference</a> - Explore all available modules</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,160 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Installation" %}
|
||||
{% set breadcrumb = [{"url": "getting-started/index.html", "title": "Getting Started"}, {"title": "Installation"}] %}
|
||||
{% set prev_page = {"url": "getting-started/index.html", "title": "Overview"} %}
|
||||
{% set next_page = {"url": "getting-started/first-script.html", "title": "First Script"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Installation</h1>
|
||||
|
||||
<p>Wren-CLI must be built from source. This page covers the build process for Linux, macOS, and FreeBSD.</p>
|
||||
|
||||
<div class="toc">
|
||||
<h4>On This Page</h4>
|
||||
<ul>
|
||||
<li><a href="#prerequisites">Prerequisites</a></li>
|
||||
<li><a href="#linux">Building on Linux</a></li>
|
||||
<li><a href="#macos">Building on macOS</a></li>
|
||||
<li><a href="#freebsd">Building on FreeBSD</a></li>
|
||||
<li><a href="#configurations">Build Configurations</a></li>
|
||||
<li><a href="#verification">Verifying Installation</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2 id="prerequisites">Prerequisites</h2>
|
||||
<p>All platforms require:</p>
|
||||
<ul>
|
||||
<li>Git</li>
|
||||
<li>C compiler (GCC or Clang)</li>
|
||||
<li>Make</li>
|
||||
<li>OpenSSL development libraries (for TLS/HTTPS support)</li>
|
||||
<li>Python 3 (for running tests)</li>
|
||||
</ul>
|
||||
|
||||
<h2 id="linux">Building on Linux</h2>
|
||||
|
||||
<h3>Install Dependencies</h3>
|
||||
<p>On Debian/Ubuntu:</p>
|
||||
<pre><code>sudo apt-get update
|
||||
sudo apt-get install build-essential libssl-dev git python3</code></pre>
|
||||
|
||||
<p>On Fedora/RHEL:</p>
|
||||
<pre><code>sudo dnf install gcc make openssl-devel git python3</code></pre>
|
||||
|
||||
<p>On Arch Linux:</p>
|
||||
<pre><code>sudo pacman -S base-devel openssl git python</code></pre>
|
||||
|
||||
<h3>Build</h3>
|
||||
<pre><code>git clone https://github.com/wren-lang/wren-cli.git
|
||||
cd wren-cli
|
||||
make build</code></pre>
|
||||
|
||||
<p>The binary will be created at <code>bin/wren_cli</code>.</p>
|
||||
|
||||
<h3>Install System-Wide (Optional)</h3>
|
||||
<pre><code>sudo cp bin/wren_cli /usr/local/bin/wren</code></pre>
|
||||
|
||||
<h2 id="macos">Building on macOS</h2>
|
||||
|
||||
<h3>Install Dependencies</h3>
|
||||
<p>Install Xcode Command Line Tools:</p>
|
||||
<pre><code>xcode-select --install</code></pre>
|
||||
|
||||
<p>Install OpenSSL via Homebrew:</p>
|
||||
<pre><code>brew install openssl</code></pre>
|
||||
|
||||
<h3>Build</h3>
|
||||
<pre><code>git clone https://github.com/wren-lang/wren-cli.git
|
||||
cd wren-cli
|
||||
cd projects/make.mac && make</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>If OpenSSL is not found, you may need to set the library path:</p>
|
||||
<pre><code>export LDFLAGS="-L/opt/homebrew/opt/openssl/lib"
|
||||
export CPPFLAGS="-I/opt/homebrew/opt/openssl/include"</code></pre>
|
||||
</div>
|
||||
|
||||
<h2 id="freebsd">Building on FreeBSD</h2>
|
||||
|
||||
<h3>Install Dependencies</h3>
|
||||
<pre><code>sudo pkg install gmake git python3</code></pre>
|
||||
|
||||
<h3>Build</h3>
|
||||
<pre><code>git clone https://github.com/wren-lang/wren-cli.git
|
||||
cd wren-cli
|
||||
cd projects/make.bsd && gmake</code></pre>
|
||||
|
||||
<h2 id="configurations">Build Configurations</h2>
|
||||
<p>Several build configurations are available:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Configuration</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>release_64bit</code></td>
|
||||
<td>Default optimized 64-bit build</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>release_32bit</code></td>
|
||||
<td>Optimized 32-bit build</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>debug_64bit</code></td>
|
||||
<td>Debug build with symbols</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>debug_32bit</code></td>
|
||||
<td>32-bit debug build</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>release_64bit-no-nan-tagging</code></td>
|
||||
<td>Without NaN tagging optimization</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>debug_64bit-no-nan-tagging</code></td>
|
||||
<td>Debug without NaN tagging</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p>To use a specific configuration:</p>
|
||||
<pre><code>make config=debug_64bit</code></pre>
|
||||
|
||||
<p>Debug builds output to <code>bin/wren_cli_d</code>.</p>
|
||||
|
||||
<h2 id="verification">Verifying Installation</h2>
|
||||
<p>Verify the build was successful:</p>
|
||||
<pre><code>bin/wren_cli --version</code></pre>
|
||||
|
||||
<p>Run the test suite:</p>
|
||||
<pre><code>make tests</code></pre>
|
||||
|
||||
<p>Start the REPL:</p>
|
||||
<pre><code>bin/wren_cli</code></pre>
|
||||
|
||||
<div class="example-output">> </div>
|
||||
|
||||
<p>Type <code>System.print("Hello")</code> and press Enter to verify the REPL works.</p>
|
||||
|
||||
<h2>Troubleshooting</h2>
|
||||
|
||||
<h3>OpenSSL Not Found</h3>
|
||||
<p>If you see errors about missing OpenSSL headers:</p>
|
||||
<ul>
|
||||
<li>Verify OpenSSL development packages are installed</li>
|
||||
<li>On macOS, ensure Homebrew OpenSSL path is in your environment</li>
|
||||
</ul>
|
||||
|
||||
<h3>Build Errors</h3>
|
||||
<p>Try cleaning and rebuilding:</p>
|
||||
<pre><code>make clean
|
||||
make build</code></pre>
|
||||
|
||||
<h3>Test Failures</h3>
|
||||
<p>Run a specific test module to isolate issues:</p>
|
||||
<pre><code>python3 util/test.py json</code></pre>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,151 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Using the REPL" %}
|
||||
{% set breadcrumb = [{"url": "getting-started/index.html", "title": "Getting Started"}, {"title": "Using the REPL"}] %}
|
||||
{% set prev_page = {"url": "getting-started/first-script.html", "title": "First Script"} %}
|
||||
{% set next_page = {"url": "language/index.html", "title": "Language Reference"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Using the REPL</h1>
|
||||
|
||||
<p>The REPL (Read-Eval-Print Loop) is an interactive environment for experimenting with Wren code. It is useful for testing ideas, exploring APIs, and learning the language.</p>
|
||||
|
||||
<h2>Starting the REPL</h2>
|
||||
<p>Run <code>wren_cli</code> without arguments to start the REPL:</p>
|
||||
<pre><code>bin/wren_cli</code></pre>
|
||||
|
||||
<p>You will see a prompt:</p>
|
||||
<div class="example-output">> </div>
|
||||
|
||||
<h2>Basic Usage</h2>
|
||||
<p>Type expressions and press Enter to evaluate them:</p>
|
||||
<pre><code>> 1 + 2
|
||||
3
|
||||
> "hello".count
|
||||
5
|
||||
> [1, 2, 3].map { |x| x * 2 }
|
||||
[2, 4, 6]</code></pre>
|
||||
|
||||
<h2>Multi-line Input</h2>
|
||||
<p>The REPL automatically detects incomplete expressions and waits for more input:</p>
|
||||
<pre><code>> class Person {
|
||||
| construct new(name) {
|
||||
| _name = name
|
||||
| }
|
||||
| name { _name }
|
||||
| }
|
||||
null
|
||||
> var p = Person.new("Alice")
|
||||
null
|
||||
> p.name
|
||||
Alice</code></pre>
|
||||
|
||||
<p>The <code>|</code> prompt indicates the REPL is waiting for more input.</p>
|
||||
|
||||
<h2>Importing Modules</h2>
|
||||
<p>Modules can be imported in the REPL just like in scripts:</p>
|
||||
<pre><code>> import "json" for Json
|
||||
null
|
||||
> Json.stringify({"name": "Wren"})
|
||||
{"name":"Wren"}
|
||||
> import "math" for Math
|
||||
null
|
||||
> Math.sqrt(16)
|
||||
4</code></pre>
|
||||
|
||||
<h2>Variables Persist</h2>
|
||||
<p>Variables defined in the REPL persist across lines:</p>
|
||||
<pre><code>> var x = 10
|
||||
null
|
||||
> var y = 20
|
||||
null
|
||||
> x + y
|
||||
30</code></pre>
|
||||
|
||||
<h2>Examining Values</h2>
|
||||
<p>Use <code>System.print</code> for formatted output:</p>
|
||||
<pre><code>> var data = {"name": "Wren", "version": 0.4}
|
||||
null
|
||||
> System.print(data)
|
||||
{name: Wren, version: 0.4}</code></pre>
|
||||
|
||||
<p>Check the type of a value:</p>
|
||||
<pre><code>> 42.type
|
||||
Num
|
||||
> "hello".type
|
||||
String
|
||||
> [1, 2, 3].type
|
||||
List</code></pre>
|
||||
|
||||
<h2>Exploring Classes</h2>
|
||||
<p>Examine what methods a class provides:</p>
|
||||
<pre><code>> String
|
||||
String
|
||||
> "test".bytes
|
||||
[116, 101, 115, 116]
|
||||
> "test".codePoints.toList
|
||||
[116, 101, 115, 116]</code></pre>
|
||||
|
||||
<h2>Error Handling</h2>
|
||||
<p>Errors are displayed but do not crash the REPL:</p>
|
||||
<pre><code>> 1 / 0
|
||||
infinity
|
||||
> "test"[10]
|
||||
Subscript out of bounds.
|
||||
> undefined_variable
|
||||
[repl line 1] Error at 'undefined_variable': Variable is used but not defined.</code></pre>
|
||||
|
||||
<p>You can continue using the REPL after errors.</p>
|
||||
|
||||
<h2>REPL Tips</h2>
|
||||
|
||||
<h3>Quick Testing</h3>
|
||||
<p>Use the REPL to quickly test regular expressions:</p>
|
||||
<pre><code>> import "regex" for Regex
|
||||
null
|
||||
> Regex.new("\\d+").test("abc123")
|
||||
true
|
||||
> Regex.new("\\d+").match("abc123def").text
|
||||
123</code></pre>
|
||||
|
||||
<h3>Exploring APIs</h3>
|
||||
<p>Test module functionality before using it in scripts:</p>
|
||||
<pre><code>> import "base64" for Base64
|
||||
null
|
||||
> Base64.encode("Hello, World!")
|
||||
SGVsbG8sIFdvcmxkIQ==
|
||||
> Base64.decode("SGVsbG8sIFdvcmxkIQ==")
|
||||
Hello, World!</code></pre>
|
||||
|
||||
<h3>Date and Time</h3>
|
||||
<pre><code>> import "datetime" for DateTime
|
||||
null
|
||||
> DateTime.now
|
||||
2024-01-15T10:30:45
|
||||
> DateTime.now.year
|
||||
2024</code></pre>
|
||||
|
||||
<h2>Exiting the REPL</h2>
|
||||
<p>Exit the REPL by pressing <code>Ctrl+D</code> (Unix) or <code>Ctrl+Z</code> followed by Enter (Windows).</p>
|
||||
|
||||
<h2>Limitations</h2>
|
||||
<ul>
|
||||
<li>No command history navigation (arrow keys)</li>
|
||||
<li>No tab completion</li>
|
||||
<li>No line editing beyond basic backspace</li>
|
||||
<li>Cannot redefine classes once defined</li>
|
||||
</ul>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>For complex experimentation, write code in a file and run it with <code>wren_cli script.wren</code>. The REPL is best for quick tests and exploration.</p>
|
||||
</div>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
<ul>
|
||||
<li><a href="../language/index.html">Language Reference</a> - Learn Wren syntax in detail</li>
|
||||
<li><a href="../api/index.html">API Reference</a> - Explore available modules</li>
|
||||
<li><a href="../tutorials/index.html">Tutorials</a> - Build real applications</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,312 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Async Programming" %}
|
||||
{% set breadcrumb = [{"url": "howto/index.html", "title": "How-To Guides"}, {"title": "Async Operations"}] %}
|
||||
{% set prev_page = {"url": "howto/file-operations.html", "title": "File Operations"} %}
|
||||
{% set next_page = {"url": "howto/error-handling.html", "title": "Error Handling"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Async Programming</h1>
|
||||
|
||||
<p>Wren-CLI provides <code>async</code> and <code>await</code> keywords for writing concurrent code. This guide covers the essential patterns for async programming.</p>
|
||||
|
||||
<h2>Create an Async Function</h2>
|
||||
<pre><code>import "scheduler" for Scheduler, Future
|
||||
|
||||
var getValue = async { 42 }
|
||||
var result = await getValue()
|
||||
System.print(result) // 42</code></pre>
|
||||
|
||||
<h2>Async Functions with Parameters</h2>
|
||||
<pre><code>import "scheduler" for Scheduler, Future
|
||||
|
||||
var double = async { |x| x * 2 }
|
||||
var add = async { |a, b| a + b }
|
||||
|
||||
System.print(await double(21)) // 42
|
||||
System.print(await add(3, 4)) // 7</code></pre>
|
||||
|
||||
<h2>Direct Calling vs .call()</h2>
|
||||
<p>There are two ways to invoke async functions:</p>
|
||||
<ul>
|
||||
<li><code>await fn(args)</code> — Direct call, waits immediately (sequential)</li>
|
||||
<li><code>fn.call(args)</code> — Returns Future, starts without waiting (concurrent)</li>
|
||||
</ul>
|
||||
<pre><code>import "scheduler" for Scheduler, Future
|
||||
|
||||
var slow = async { |n|
|
||||
Timer.sleep(100)
|
||||
return n
|
||||
}
|
||||
|
||||
// SEQUENTIAL: Each call waits before the next starts
|
||||
var a = await slow(1)
|
||||
var b = await slow(2)
|
||||
var c = await slow(3) // Total: ~300ms
|
||||
|
||||
// CONCURRENT: All calls start at once, then wait for results
|
||||
var f1 = slow.call(1)
|
||||
var f2 = slow.call(2)
|
||||
var f3 = slow.call(3)
|
||||
var r1 = await f1
|
||||
var r2 = await f2
|
||||
var r3 = await f3 // Total: ~100ms</code></pre>
|
||||
|
||||
<h2>Sequential HTTP Requests</h2>
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "json" for Json
|
||||
|
||||
var fetchJson = async { |url|
|
||||
var response = Client.get(url)
|
||||
return Json.parse(response["body"])
|
||||
}
|
||||
|
||||
// Each request waits for the previous one
|
||||
var user = await fetchJson("https://api.example.com/user/1")
|
||||
var posts = await fetchJson("https://api.example.com/posts")
|
||||
var comments = await fetchJson("https://api.example.com/comments")
|
||||
|
||||
System.print(user["name"])
|
||||
System.print(posts.count)
|
||||
System.print(comments.count)</code></pre>
|
||||
|
||||
<h2>Concurrent HTTP Requests</h2>
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "json" for Json
|
||||
|
||||
var fetchJson = async { |url|
|
||||
var response = Client.get(url)
|
||||
return Json.parse(response["body"])
|
||||
}
|
||||
|
||||
// Start all requests at once
|
||||
var f1 = fetchJson.call("https://api.example.com/user/1")
|
||||
var f2 = fetchJson.call("https://api.example.com/posts")
|
||||
var f3 = fetchJson.call("https://api.example.com/comments")
|
||||
|
||||
// Wait for results (requests run in parallel)
|
||||
var user = await f1
|
||||
var posts = await f2
|
||||
var comments = await f3
|
||||
|
||||
System.print(user["name"])
|
||||
System.print(posts.count)
|
||||
System.print(comments.count)</code></pre>
|
||||
|
||||
<h2>Batch Processing</h2>
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
|
||||
var urls = [
|
||||
"https://api.example.com/1",
|
||||
"https://api.example.com/2",
|
||||
"https://api.example.com/3",
|
||||
"https://api.example.com/4",
|
||||
"https://api.example.com/5"
|
||||
]
|
||||
|
||||
// Start all requests concurrently
|
||||
var futures = []
|
||||
for (url in urls) {
|
||||
futures.add(async { Client.get(url) })
|
||||
}
|
||||
|
||||
// Collect results
|
||||
var responses = []
|
||||
for (f in futures) {
|
||||
responses.add(await f)
|
||||
}
|
||||
|
||||
for (i in 0...urls.count) {
|
||||
System.print("%(urls[i]): %(responses[i]["status"])")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Reusable Batch Fetcher</h2>
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "json" for Json
|
||||
|
||||
var fetchJson = async { |url|
|
||||
var response = Client.get(url)
|
||||
return Json.parse(response["body"])
|
||||
}
|
||||
|
||||
class BatchFetcher {
|
||||
static getAll(urls) {
|
||||
var futures = []
|
||||
for (url in urls) {
|
||||
futures.add(fetchJson.call(url))
|
||||
}
|
||||
|
||||
var results = []
|
||||
for (f in futures) {
|
||||
results.add(await f)
|
||||
}
|
||||
return results
|
||||
}
|
||||
}
|
||||
|
||||
var urls = [
|
||||
"https://api.example.com/users",
|
||||
"https://api.example.com/posts",
|
||||
"https://api.example.com/comments"
|
||||
]
|
||||
|
||||
var results = BatchFetcher.getAll(urls)
|
||||
for (result in results) {
|
||||
System.print(result)</code></pre>
|
||||
|
||||
<h2>Sleep/Delay</h2>
|
||||
<pre><code>import "timer" for Timer
|
||||
|
||||
System.print("Starting...")
|
||||
Timer.sleep(1000) // Wait 1 second
|
||||
System.print("Done!")</code></pre>
|
||||
|
||||
<h2>Async with Error Handling</h2>
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "json" for Json
|
||||
|
||||
var safeFetch = async { |url|
|
||||
var fiber = Fiber.new {
|
||||
var response = Client.get(url)
|
||||
return Json.parse(response["body"])
|
||||
}
|
||||
var result = fiber.try()
|
||||
if (fiber.error) {
|
||||
return {"error": fiber.error}
|
||||
}
|
||||
return {"data": result}
|
||||
}
|
||||
|
||||
var result = await safeFetch("https://api.example.com/data")
|
||||
if (result["error"]) {
|
||||
System.print("Error: %(result["error"])")
|
||||
} else {
|
||||
System.print("Data: %(result["data"])")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Retry with Backoff</h2>
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "timer" for Timer
|
||||
|
||||
var fetchWithRetry = async { |url, maxRetries|
|
||||
var attempt = 0
|
||||
var delay = 1000
|
||||
|
||||
while (attempt < maxRetries) {
|
||||
var fiber = Fiber.new { Client.get(url) }
|
||||
var result = fiber.try()
|
||||
|
||||
if (!fiber.error && result["status"] == 200) {
|
||||
return result
|
||||
}
|
||||
|
||||
attempt = attempt + 1
|
||||
System.print("Attempt %(attempt) failed, retrying...")
|
||||
Timer.sleep(delay)
|
||||
delay = delay * 2
|
||||
}
|
||||
|
||||
Fiber.abort("All %(maxRetries) attempts failed")
|
||||
}
|
||||
|
||||
var response = await fetchWithRetry("https://api.example.com/data", 3)
|
||||
System.print("Success: %(response["status"])")</code></pre>
|
||||
|
||||
<h2>Polling Pattern</h2>
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "timer" for Timer
|
||||
import "json" for Json
|
||||
|
||||
var pollUntilReady = async { |url, maxAttempts|
|
||||
var attempts = 0
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
attempts = attempts + 1
|
||||
System.print("Checking status (attempt %(attempts))...")
|
||||
|
||||
var response = Client.get(url)
|
||||
var data = Json.parse(response["body"])
|
||||
|
||||
if (data["status"] == "ready") {
|
||||
return data
|
||||
}
|
||||
|
||||
Timer.sleep(2000)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
var result = await pollUntilReady("https://api.example.com/job/123", 10)
|
||||
if (result) {
|
||||
System.print("Job completed: %(result)")
|
||||
} else {
|
||||
System.print("Timed out waiting for job")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Rate Limiting</h2>
|
||||
<pre><code>import "web" for Client
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "timer" for Timer
|
||||
|
||||
var rateLimitedFetch = async { |urls, delayMs|
|
||||
var results = []
|
||||
|
||||
for (url in urls) {
|
||||
var response = Client.get(url)
|
||||
results.add(response)
|
||||
Timer.sleep(delayMs)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
var urls = [
|
||||
"https://api.example.com/1",
|
||||
"https://api.example.com/2",
|
||||
"https://api.example.com/3"
|
||||
]
|
||||
|
||||
var responses = await rateLimitedFetch(urls, 500)
|
||||
for (r in responses) {
|
||||
System.print(r["status"])
|
||||
}</code></pre>
|
||||
|
||||
<h2>Graceful Shutdown</h2>
|
||||
<pre><code>import "signal" for Signal
|
||||
import "timer" for Timer
|
||||
|
||||
var running = true
|
||||
|
||||
Signal.handle("SIGINT", Fn.new {
|
||||
System.print("\nShutting down gracefully...")
|
||||
running = false
|
||||
})
|
||||
|
||||
System.print("Press Ctrl+C to stop")
|
||||
|
||||
while (running) {
|
||||
System.print("Working...")
|
||||
Timer.sleep(1000)
|
||||
}
|
||||
|
||||
System.print("Cleanup complete, exiting.")</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Always import <code>Scheduler</code> and <code>Future</code> from the scheduler module when using <code>async</code> and <code>await</code>. The syntax requires these classes to be in scope.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">See Also</div>
|
||||
<p>For more details, see the <a href="../api/scheduler.html">Scheduler API reference</a> and the <a href="../api/web.html">Web module</a> for HTTP client examples.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,378 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Error Handling" %}
|
||||
{% set breadcrumb = [{"url": "howto/index.html", "title": "How-To Guides"}, {"title": "Error Handling"}] %}
|
||||
{% set prev_page = {"url": "howto/async-operations.html", "title": "Async Operations"} %}
|
||||
{% set next_page = {"url": "contributing/index.html", "title": "Contributing"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Error Handling</h1>
|
||||
|
||||
<p>Wren uses fibers for error handling. The <code>fiber.try()</code> method catches errors without crashing your program.</p>
|
||||
|
||||
<h2>Basic Try/Catch Pattern</h2>
|
||||
<pre><code>var fiber = Fiber.new {
|
||||
Fiber.abort("Something went wrong!")
|
||||
}
|
||||
|
||||
var result = fiber.try()
|
||||
|
||||
if (fiber.error) {
|
||||
System.print("Error: %(fiber.error)")
|
||||
} else {
|
||||
System.print("Result: %(result)")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Throw an Error</h2>
|
||||
<pre><code>Fiber.abort("This is an error message")</code></pre>
|
||||
|
||||
<h2>Catch Specific Error Types</h2>
|
||||
<pre><code>var fiber = Fiber.new {
|
||||
var x = null
|
||||
return x.count // Error: null has no method 'count'
|
||||
}
|
||||
|
||||
var result = fiber.try()
|
||||
|
||||
if (fiber.error) {
|
||||
if (fiber.error.contains("null")) {
|
||||
System.print("Null reference error")
|
||||
} else {
|
||||
System.print("Other error: %(fiber.error)")
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h2>Safe File Read</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
var safeRead = Fn.new { |path|
|
||||
var fiber = Fiber.new { File.read(path) }
|
||||
var content = fiber.try()
|
||||
|
||||
if (fiber.error) {
|
||||
return null
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
var content = safeRead.call("config.txt")
|
||||
if (content) {
|
||||
System.print(content)
|
||||
} else {
|
||||
System.print("Could not read file")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Safe JSON Parse</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var safeParse = Fn.new { |jsonStr|
|
||||
var fiber = Fiber.new { Json.parse(jsonStr) }
|
||||
var data = fiber.try()
|
||||
|
||||
if (fiber.error) {
|
||||
System.print("Invalid JSON: %(fiber.error)")
|
||||
return null
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
var data = safeParse.call('{"valid": true}') // Works
|
||||
var bad = safeParse.call('not json') // Returns null</code></pre>
|
||||
|
||||
<h2>Safe HTTP Request</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var safeFetch = Fn.new { |url|
|
||||
var fiber = Fiber.new { Http.get(url) }
|
||||
var response = fiber.try()
|
||||
|
||||
if (fiber.error) {
|
||||
return {"error": fiber.error, "ok": false}
|
||||
}
|
||||
|
||||
if (response.statusCode >= 400) {
|
||||
return {"error": "HTTP %(response.statusCode)", "ok": false}
|
||||
}
|
||||
|
||||
return {"data": response.json, "ok": true}
|
||||
}
|
||||
|
||||
var result = safeFetch.call("https://api.example.com/data")
|
||||
if (result["ok"]) {
|
||||
System.print(result["data"])
|
||||
} else {
|
||||
System.print("Error: %(result["error"])")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Input Validation</h2>
|
||||
<pre><code>var validateEmail = Fn.new { |email|
|
||||
if (email == null) {
|
||||
Fiber.abort("Email is required")
|
||||
}
|
||||
if (!email.contains("@")) {
|
||||
Fiber.abort("Invalid email format")
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var validate = Fn.new { |email|
|
||||
var fiber = Fiber.new { validateEmail.call(email) }
|
||||
fiber.try()
|
||||
return fiber.error
|
||||
}
|
||||
|
||||
System.print(validate.call(null)) // Email is required
|
||||
System.print(validate.call("invalid")) // Invalid email format
|
||||
System.print(validate.call("a@b.com")) // null (no error)</code></pre>
|
||||
|
||||
<h2>Result Type Pattern</h2>
|
||||
<pre><code>class Result {
|
||||
construct ok(value) {
|
||||
_value = value
|
||||
_error = null
|
||||
}
|
||||
|
||||
construct error(message) {
|
||||
_value = null
|
||||
_error = message
|
||||
}
|
||||
|
||||
isOk { _error == null }
|
||||
isError { _error != null }
|
||||
value { _value }
|
||||
error { _error }
|
||||
|
||||
unwrap {
|
||||
if (isError) Fiber.abort(_error)
|
||||
return _value
|
||||
}
|
||||
|
||||
unwrapOr(default) { isOk ? _value : default }
|
||||
}
|
||||
|
||||
var divide = Fn.new { |a, b|
|
||||
if (b == 0) {
|
||||
return Result.error("Division by zero")
|
||||
}
|
||||
return Result.ok(a / b)
|
||||
}
|
||||
|
||||
var result = divide.call(10, 2)
|
||||
if (result.isOk) {
|
||||
System.print("Result: %(result.value)")
|
||||
}
|
||||
|
||||
var bad = divide.call(10, 0)
|
||||
if (bad.isError) {
|
||||
System.print("Error: %(bad.error)")
|
||||
}
|
||||
|
||||
System.print(divide.call(10, 5).unwrapOr(0)) // 2
|
||||
System.print(divide.call(10, 0).unwrapOr(0)) // 0</code></pre>
|
||||
|
||||
<h2>Assert Function</h2>
|
||||
<pre><code>var assert = Fn.new { |condition, message|
|
||||
if (!condition) {
|
||||
Fiber.abort("Assertion failed: %(message)")
|
||||
}
|
||||
}
|
||||
|
||||
var processUser = Fn.new { |user|
|
||||
assert.call(user != null, "User is required")
|
||||
assert.call(user["name"] != null, "User name is required")
|
||||
assert.call(user["age"] >= 0, "Age must be non-negative")
|
||||
|
||||
System.print("Processing %(user["name"])...")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Multiple Error Sources</h2>
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
var fetchAndParse = Fn.new { |url|
|
||||
var httpFiber = Fiber.new { Http.get(url) }
|
||||
var response = httpFiber.try()
|
||||
|
||||
if (httpFiber.error) {
|
||||
return {"error": "Network error: %(httpFiber.error)"}
|
||||
}
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
return {"error": "HTTP error: %(response.statusCode)"}
|
||||
}
|
||||
|
||||
var jsonFiber = Fiber.new { Json.parse(response.body) }
|
||||
var data = jsonFiber.try()
|
||||
|
||||
if (jsonFiber.error) {
|
||||
return {"error": "Parse error: %(jsonFiber.error)"}
|
||||
}
|
||||
|
||||
return {"data": data}
|
||||
}
|
||||
|
||||
var result = fetchAndParse.call("https://api.example.com/data")
|
||||
if (result.containsKey("error")) {
|
||||
System.print(result["error"])
|
||||
} else {
|
||||
System.print(result["data"])
|
||||
}</code></pre>
|
||||
|
||||
<h2>Error Logging</h2>
|
||||
<pre><code>import "datetime" for DateTime
|
||||
import "io" for File
|
||||
|
||||
class Logger {
|
||||
construct new(logFile) {
|
||||
_logFile = logFile
|
||||
}
|
||||
|
||||
log(level, message) {
|
||||
var timestamp = DateTime.now().toString
|
||||
var entry = "[%(timestamp)] [%(level)] %(message)\n"
|
||||
|
||||
var existing = ""
|
||||
var fiber = Fiber.new { File.read(_logFile) }
|
||||
existing = fiber.try() || ""
|
||||
|
||||
File.write(_logFile, existing + entry)
|
||||
|
||||
if (level == "ERROR") {
|
||||
System.print("ERROR: %(message)")
|
||||
}
|
||||
}
|
||||
|
||||
error(message) { log("ERROR", message) }
|
||||
warn(message) { log("WARN", message) }
|
||||
info(message) { log("INFO", message) }
|
||||
}
|
||||
|
||||
var logger = Logger.new("app.log")
|
||||
|
||||
var safeDivide = Fn.new { |a, b|
|
||||
if (b == 0) {
|
||||
logger.error("Division by zero: %(a) / %(b)")
|
||||
return null
|
||||
}
|
||||
return a / b
|
||||
}
|
||||
|
||||
var result = safeDivide.call(10, 0)</code></pre>
|
||||
|
||||
<h2>Cleanup with Finally Pattern</h2>
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
|
||||
var withDatabase = Fn.new { |dbPath, operation|
|
||||
var db = Sqlite.open(dbPath)
|
||||
var result = null
|
||||
var error = null
|
||||
|
||||
var fiber = Fiber.new { operation.call(db) }
|
||||
result = fiber.try()
|
||||
error = fiber.error
|
||||
|
||||
db.close()
|
||||
|
||||
if (error) {
|
||||
Fiber.abort(error)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
var users = withDatabase.call("app.db", Fn.new { |db|
|
||||
return db.execute("SELECT * FROM users")
|
||||
})
|
||||
|
||||
System.print(users)</code></pre>
|
||||
|
||||
<h2>Custom Error Class</h2>
|
||||
<pre><code>class AppError {
|
||||
construct new(code, message) {
|
||||
_code = code
|
||||
_message = message
|
||||
}
|
||||
|
||||
code { _code }
|
||||
message { _message }
|
||||
toString { "[%(code)] %(message)" }
|
||||
|
||||
static notFound(resource) {
|
||||
return AppError.new("NOT_FOUND", "%(resource) not found")
|
||||
}
|
||||
|
||||
static validation(field, reason) {
|
||||
return AppError.new("VALIDATION", "%(field): %(reason)")
|
||||
}
|
||||
|
||||
static unauthorized() {
|
||||
return AppError.new("UNAUTHORIZED", "Authentication required")
|
||||
}
|
||||
}
|
||||
|
||||
var findUser = Fn.new { |id|
|
||||
if (id == null) {
|
||||
Fiber.abort(AppError.validation("id", "is required").toString)
|
||||
}
|
||||
|
||||
var user = null
|
||||
|
||||
if (user == null) {
|
||||
Fiber.abort(AppError.notFound("User %(id)").toString)
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
var fiber = Fiber.new { findUser.call(null) }
|
||||
fiber.try()
|
||||
System.print(fiber.error) // [VALIDATION] id: is required</code></pre>
|
||||
|
||||
<h2>Retry on Error</h2>
|
||||
<pre><code>import "timer" for Timer
|
||||
|
||||
var retry = Fn.new { |operation, maxAttempts, delayMs|
|
||||
var lastError = null
|
||||
|
||||
for (i in 1..maxAttempts) {
|
||||
var fiber = Fiber.new { operation.call() }
|
||||
var result = fiber.try()
|
||||
|
||||
if (!fiber.error) {
|
||||
return result
|
||||
}
|
||||
|
||||
lastError = fiber.error
|
||||
System.print("Attempt %(i) failed: %(lastError)")
|
||||
|
||||
if (i < maxAttempts) {
|
||||
Timer.sleep(delayMs)
|
||||
}
|
||||
}
|
||||
|
||||
Fiber.abort("All %(maxAttempts) attempts failed. Last error: %(lastError)")
|
||||
}
|
||||
|
||||
var result = retry.call(Fn.new {
|
||||
return "success"
|
||||
}, 3, 1000)</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Best Practices</div>
|
||||
<ul>
|
||||
<li>Always wrap external calls (HTTP, file I/O) in fibers</li>
|
||||
<li>Provide meaningful error messages</li>
|
||||
<li>Log errors for debugging</li>
|
||||
<li>Fail fast on programming errors, recover from user errors</li>
|
||||
<li>Clean up resources (close files, connections) even on error</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">See Also</div>
|
||||
<p>For more on fibers, see the <a href="../language/fibers.html">Fibers language guide</a>.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,306 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "File Operations" %}
|
||||
{% set breadcrumb = [{"url": "howto/index.html", "title": "How-To Guides"}, {"title": "File Operations"}] %}
|
||||
{% set prev_page = {"url": "howto/regex-patterns.html", "title": "Regex Patterns"} %}
|
||||
{% set next_page = {"url": "howto/async-operations.html", "title": "Async Operations"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>File Operations</h1>
|
||||
|
||||
<h2>Read Entire File</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
var content = File.read("document.txt")
|
||||
System.print(content)</code></pre>
|
||||
|
||||
<h2>Write to File</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
File.write("output.txt", "Hello, World!")
|
||||
System.print("File written!")</code></pre>
|
||||
|
||||
<h2>Append to File</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
var existing = File.exists("log.txt") ? File.read("log.txt") : ""
|
||||
File.write("log.txt", existing + "New line\n")</code></pre>
|
||||
|
||||
<h2>Check if File Exists</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
if (File.exists("config.txt")) {
|
||||
System.print("Config found")
|
||||
var content = File.read("config.txt")
|
||||
} else {
|
||||
System.print("Config not found, using defaults")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Get File Size</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
var size = File.size("data.bin")
|
||||
System.print("File size: %(size) bytes")</code></pre>
|
||||
|
||||
<h2>Copy File</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
File.copy("source.txt", "destination.txt")
|
||||
System.print("File copied!")</code></pre>
|
||||
|
||||
<h2>Rename/Move File</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
File.rename("old_name.txt", "new_name.txt")
|
||||
System.print("File renamed!")
|
||||
|
||||
File.rename("file.txt", "subdir/file.txt")
|
||||
System.print("File moved!")</code></pre>
|
||||
|
||||
<h2>Delete File</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
if (File.exists("temp.txt")) {
|
||||
File.delete("temp.txt")
|
||||
System.print("File deleted!")
|
||||
}</code></pre>
|
||||
|
||||
<h2>List Directory Contents</h2>
|
||||
<pre><code>import "io" for Directory
|
||||
|
||||
var files = Directory.list(".")
|
||||
|
||||
for (file in files) {
|
||||
System.print(file)
|
||||
}</code></pre>
|
||||
|
||||
<h2>Check if Directory Exists</h2>
|
||||
<pre><code>import "io" for Directory
|
||||
|
||||
if (Directory.exists("data")) {
|
||||
System.print("Directory found")
|
||||
} else {
|
||||
System.print("Directory not found")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Create Directory</h2>
|
||||
<pre><code>import "io" for Directory
|
||||
|
||||
if (!Directory.exists("output")) {
|
||||
Directory.create("output")
|
||||
System.print("Directory created!")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Delete Empty Directory</h2>
|
||||
<pre><code>import "io" for Directory
|
||||
|
||||
Directory.delete("empty_folder")
|
||||
System.print("Directory deleted!")</code></pre>
|
||||
|
||||
<h2>Read File Line by Line</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
var content = File.read("data.txt")
|
||||
var lines = content.split("\n")
|
||||
|
||||
for (line in lines) {
|
||||
if (line.count > 0) {
|
||||
System.print(line)
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h2>Process Files in Directory</h2>
|
||||
<pre><code>import "io" for File, Directory
|
||||
|
||||
var files = Directory.list("./data")
|
||||
|
||||
for (filename in files) {
|
||||
if (filename.endsWith(".txt")) {
|
||||
var path = "./data/%(filename)"
|
||||
var content = File.read(path)
|
||||
System.print("%(filename): %(content.count) chars")
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h2>Recursive Directory Listing</h2>
|
||||
<pre><code>import "io" for File, Directory
|
||||
|
||||
var listRecursive = Fn.new { |path, indent|
|
||||
var items = Directory.list(path)
|
||||
|
||||
for (item in items) {
|
||||
var fullPath = "%(path)/%(item)"
|
||||
System.print("%(indent)%(item)")
|
||||
|
||||
if (Directory.exists(fullPath)) {
|
||||
listRecursive.call(fullPath, indent + " ")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
listRecursive.call(".", "")</code></pre>
|
||||
|
||||
<h2>Find Files by Extension</h2>
|
||||
<pre><code>import "io" for File, Directory
|
||||
|
||||
var findByExtension = Fn.new { |path, ext|
|
||||
var results = []
|
||||
var items = Directory.list(path)
|
||||
|
||||
for (item in items) {
|
||||
var fullPath = "%(path)/%(item)"
|
||||
|
||||
if (Directory.exists(fullPath)) {
|
||||
var subResults = findByExtension.call(fullPath, ext)
|
||||
for (r in subResults) results.add(r)
|
||||
} else if (item.endsWith(ext)) {
|
||||
results.add(fullPath)
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
var wrenFiles = findByExtension.call(".", ".wren")
|
||||
for (file in wrenFiles) {
|
||||
System.print(file)
|
||||
}</code></pre>
|
||||
|
||||
<h2>Read JSON Configuration</h2>
|
||||
<pre><code>import "io" for File
|
||||
import "json" for Json
|
||||
|
||||
var loadConfig = Fn.new { |path, defaults|
|
||||
if (!File.exists(path)) {
|
||||
return defaults
|
||||
}
|
||||
|
||||
var content = File.read(path)
|
||||
var config = Json.parse(content)
|
||||
|
||||
for (key in defaults.keys) {
|
||||
if (!config.containsKey(key)) {
|
||||
config[key] = defaults[key]
|
||||
}
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
var config = loadConfig.call("config.json", {
|
||||
"port": 8080,
|
||||
"debug": false
|
||||
})
|
||||
|
||||
System.print("Port: %(config["port"])")</code></pre>
|
||||
|
||||
<h2>Save JSON Configuration</h2>
|
||||
<pre><code>import "io" for File
|
||||
import "json" for Json
|
||||
|
||||
var config = {
|
||||
"database": "app.db",
|
||||
"port": 8080,
|
||||
"debug": true
|
||||
}
|
||||
|
||||
File.write("config.json", Json.stringify(config, 2))
|
||||
System.print("Configuration saved!")</code></pre>
|
||||
|
||||
<h2>Create Backup Copy</h2>
|
||||
<pre><code>import "io" for File
|
||||
import "datetime" for DateTime
|
||||
|
||||
var backup = Fn.new { |path|
|
||||
if (!File.exists(path)) {
|
||||
System.print("File not found: %(path)")
|
||||
return null
|
||||
}
|
||||
|
||||
var timestamp = DateTime.now().format("\%Y\%m\%d_\%H\%M\%S")
|
||||
var backupPath = "%(path).%(timestamp).bak"
|
||||
|
||||
File.copy(path, backupPath)
|
||||
System.print("Backup created: %(backupPath)")
|
||||
|
||||
return backupPath
|
||||
}
|
||||
|
||||
backup.call("important.txt")</code></pre>
|
||||
|
||||
<h2>Read User Input</h2>
|
||||
<pre><code>import "io" for Stdin
|
||||
|
||||
System.write("Enter your name: ")
|
||||
var name = Stdin.readLine()
|
||||
|
||||
System.print("Hello, %(name)!")</code></pre>
|
||||
|
||||
<h2>Interactive Menu</h2>
|
||||
<pre><code>import "io" for Stdin
|
||||
|
||||
System.print("Select an option:")
|
||||
System.print("1. Option A")
|
||||
System.print("2. Option B")
|
||||
System.print("3. Exit")
|
||||
|
||||
System.write("Choice: ")
|
||||
var choice = Stdin.readLine()
|
||||
|
||||
if (choice == "1") {
|
||||
System.print("You selected Option A")
|
||||
} else if (choice == "2") {
|
||||
System.print("You selected Option B")
|
||||
} else if (choice == "3") {
|
||||
System.print("Goodbye!")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Safe File Operations with Error Handling</h2>
|
||||
<pre><code>import "io" for File
|
||||
|
||||
var safeRead = Fn.new { |path|
|
||||
var fiber = Fiber.new { File.read(path) }
|
||||
var result = fiber.try()
|
||||
|
||||
if (fiber.error) {
|
||||
System.print("Error reading %(path): %(fiber.error)")
|
||||
return null
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
var content = safeRead.call("maybe_exists.txt")
|
||||
if (content) {
|
||||
System.print("Content: %(content)")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Calculate Directory Size</h2>
|
||||
<pre><code>import "io" for File, Directory
|
||||
|
||||
var dirSize = Fn.new { |path|
|
||||
var total = 0
|
||||
var items = Directory.list(path)
|
||||
|
||||
for (item in items) {
|
||||
var fullPath = "%(path)/%(item)"
|
||||
|
||||
if (Directory.exists(fullPath)) {
|
||||
total = total + dirSize.call(fullPath)
|
||||
} else if (File.exists(fullPath)) {
|
||||
total = total + File.size(fullPath)
|
||||
}
|
||||
}
|
||||
|
||||
return total
|
||||
}
|
||||
|
||||
var size = dirSize.call(".")
|
||||
System.print("Total size: %(size) bytes")</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">See Also</div>
|
||||
<p>For full API documentation, see the <a href="../api/io.html">IO module reference</a>. For object-oriented path manipulation with glob, walk, and tree operations, see the <a href="../api/pathlib.html">pathlib module reference</a>.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,234 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Making HTTP Requests" %}
|
||||
{% set breadcrumb = [{"url": "howto/index.html", "title": "How-To Guides"}, {"title": "HTTP Requests"}] %}
|
||||
{% set prev_page = {"url": "howto/index.html", "title": "How-To List"} %}
|
||||
{% set next_page = {"url": "howto/json-parsing.html", "title": "JSON Parsing"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Making HTTP Requests</h1>
|
||||
|
||||
<h2>Basic GET Request</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://api.example.com/data")
|
||||
System.print(response.body)</code></pre>
|
||||
|
||||
<h2>GET Request with JSON Response</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://jsonplaceholder.typicode.com/posts/1")
|
||||
var data = response.json
|
||||
|
||||
System.print("Title: %(data["title"])")</code></pre>
|
||||
|
||||
<h2>GET Request with Headers</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://api.example.com/data", {
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "Wren-CLI/1.0"
|
||||
})
|
||||
|
||||
System.print(response.body)</code></pre>
|
||||
|
||||
<h2>POST Request with JSON Body</h2>
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
var data = {
|
||||
"name": "John Doe",
|
||||
"email": "john@example.com"
|
||||
}
|
||||
|
||||
var response = Http.post(
|
||||
"https://api.example.com/users",
|
||||
Json.stringify(data),
|
||||
{"Content-Type": "application/json"}
|
||||
)
|
||||
|
||||
System.print("Status: %(response.statusCode)")
|
||||
System.print("Created: %(response.json)")</code></pre>
|
||||
|
||||
<h2>PUT Request</h2>
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
var data = {
|
||||
"id": 1,
|
||||
"name": "Jane Doe",
|
||||
"email": "jane@example.com"
|
||||
}
|
||||
|
||||
var response = Http.put(
|
||||
"https://api.example.com/users/1",
|
||||
Json.stringify(data),
|
||||
{"Content-Type": "application/json"}
|
||||
)
|
||||
|
||||
System.print("Updated: %(response.statusCode == 200)")</code></pre>
|
||||
|
||||
<h2>DELETE Request</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.delete("https://api.example.com/users/1")
|
||||
System.print("Deleted: %(response.statusCode == 204)")</code></pre>
|
||||
|
||||
<h2>PATCH Request</h2>
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
var response = Http.patch(
|
||||
"https://api.example.com/users/1",
|
||||
Json.stringify({"email": "newemail@example.com"}),
|
||||
{"Content-Type": "application/json"}
|
||||
)
|
||||
|
||||
System.print("Patched: %(response.statusCode)")</code></pre>
|
||||
|
||||
<h2>Bearer Token Authentication</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var token = "your-api-token"
|
||||
|
||||
var response = Http.get("https://api.example.com/protected", {
|
||||
"Authorization": "Bearer %(token)"
|
||||
})
|
||||
|
||||
System.print(response.json)</code></pre>
|
||||
|
||||
<h2>Basic Authentication</h2>
|
||||
<pre><code>import "http" for Http
|
||||
import "base64" for Base64
|
||||
|
||||
var username = "user"
|
||||
var password = "pass"
|
||||
var credentials = Base64.encode("%(username):%(password)")
|
||||
|
||||
var response = Http.get("https://api.example.com/protected", {
|
||||
"Authorization": "Basic %(credentials)"
|
||||
})
|
||||
|
||||
System.print(response.body)</code></pre>
|
||||
|
||||
<h2>API Key Authentication</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://api.example.com/data", {
|
||||
"X-API-Key": "your-api-key"
|
||||
})
|
||||
|
||||
System.print(response.body)</code></pre>
|
||||
|
||||
<h2>Check Response Status</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://api.example.com/data")
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
System.print("Success: %(response.json)")
|
||||
} else if (response.statusCode == 404) {
|
||||
System.print("Not found")
|
||||
} else if (response.statusCode >= 500) {
|
||||
System.print("Server error: %(response.statusCode)")
|
||||
} else {
|
||||
System.print("Error: %(response.statusCode)")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Access Response Headers</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://api.example.com/data")
|
||||
|
||||
System.print("Content-Type: %(response.headers["content-type"])")
|
||||
System.print("All headers: %(response.headers)")</code></pre>
|
||||
|
||||
<h2>URL Query Parameters</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://api.example.com/search?q=wren&limit=10")
|
||||
|
||||
System.print(response.json)</code></pre>
|
||||
|
||||
<h2>Form URL Encoded POST</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var body = "username=john&password=secret"
|
||||
|
||||
var response = Http.post(
|
||||
"https://api.example.com/login",
|
||||
body,
|
||||
{"Content-Type": "application/x-www-form-urlencoded"}
|
||||
)
|
||||
|
||||
System.print(response.json)</code></pre>
|
||||
|
||||
<h2>Download File</h2>
|
||||
<pre><code>import "http" for Http
|
||||
import "io" for File
|
||||
|
||||
var response = Http.get("https://example.com/file.txt")
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
File.write("downloaded.txt", response.body)
|
||||
System.print("File downloaded!")
|
||||
}</code></pre>
|
||||
|
||||
<h2>HTTPS Request</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://secure.example.com/api")
|
||||
System.print(response.body)</code></pre>
|
||||
|
||||
<h2>Error Handling</h2>
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var fiber = Fiber.new {
|
||||
return Http.get("https://api.example.com/data")
|
||||
}
|
||||
|
||||
var response = fiber.try()
|
||||
|
||||
if (fiber.error) {
|
||||
System.print("Request failed: %(fiber.error)")
|
||||
} else if (response.statusCode >= 400) {
|
||||
System.print("HTTP error: %(response.statusCode)")
|
||||
} else {
|
||||
System.print("Success: %(response.json)")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Retry on Failure</h2>
|
||||
<pre><code>import "http" for Http
|
||||
import "timer" for Timer
|
||||
|
||||
var fetchWithRetry = Fn.new { |url, maxRetries|
|
||||
var attempt = 0
|
||||
while (attempt < maxRetries) {
|
||||
var fiber = Fiber.new { Http.get(url) }
|
||||
var response = fiber.try()
|
||||
|
||||
if (!fiber.error && response.statusCode == 200) {
|
||||
return response
|
||||
}
|
||||
|
||||
attempt = attempt + 1
|
||||
if (attempt < maxRetries) {
|
||||
Timer.sleep(1000 * attempt)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
var response = fetchWithRetry.call("https://api.example.com/data", 3)
|
||||
if (response) {
|
||||
System.print(response.json)
|
||||
} else {
|
||||
System.print("Failed after 3 retries")
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">See Also</div>
|
||||
<p>For a complete API client example, see the <a href="../tutorials/http-client.html">HTTP Client Tutorial</a>. For full API documentation, see the <a href="../api/http.html">HTTP module reference</a>.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,110 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "How-To Guides" %}
|
||||
{% set breadcrumb = [{"title": "How-To Guides"}] %}
|
||||
{% set prev_page = {"url": "tutorials/web-server.html", "title": "Web Server"} %}
|
||||
{% set next_page = {"url": "howto/http-requests.html", "title": "HTTP Requests"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>How-To Guides</h1>
|
||||
|
||||
<p>Quick, focused guides that show you how to accomplish specific tasks. Each guide provides working code examples you can copy and adapt for your projects.</p>
|
||||
|
||||
<div class="card-grid">
|
||||
<div class="card">
|
||||
<h3><a href="http-requests.html">Making HTTP Requests</a></h3>
|
||||
<p>GET, POST, PUT, DELETE requests with headers, authentication, and error handling.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">http</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3><a href="json-parsing.html">Working with JSON</a></h3>
|
||||
<p>Parse JSON strings, access nested data, create JSON output, and handle errors.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">json</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3><a href="regex-patterns.html">Using Regular Expressions</a></h3>
|
||||
<p>Match, search, replace, and split text with regex patterns.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">regex</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3><a href="file-operations.html">File Operations</a></h3>
|
||||
<p>Read, write, copy, and delete files. Work with directories and paths.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">io</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3><a href="async-operations.html">Async Programming</a></h3>
|
||||
<p>Use fibers for concurrent operations, parallel requests, and timeouts.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">fibers</span>
|
||||
<span class="tag">scheduler</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3><a href="error-handling.html">Error Handling</a></h3>
|
||||
<p>Catch errors with fibers, validate input, and handle edge cases gracefully.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">fibers</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>How-To vs Tutorials</h2>
|
||||
|
||||
<p><strong>Tutorials</strong> are learning-oriented. They walk you through building complete applications step by step, introducing concepts gradually.</p>
|
||||
|
||||
<p><strong>How-To Guides</strong> are goal-oriented. They assume you know the basics and need to accomplish a specific task quickly. Each guide focuses on one topic with copy-paste examples.</p>
|
||||
|
||||
<h2>Quick Reference</h2>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Task</th>
|
||||
<th>Guide</th>
|
||||
<th>Key Functions</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Fetch data from API</td>
|
||||
<td><a href="http-requests.html">HTTP Requests</a></td>
|
||||
<td><code>Http.get()</code>, <code>response.json</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Parse JSON string</td>
|
||||
<td><a href="json-parsing.html">JSON Parsing</a></td>
|
||||
<td><code>Json.parse()</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Validate email format</td>
|
||||
<td><a href="regex-patterns.html">Regex Patterns</a></td>
|
||||
<td><code>Regex.new().test()</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Read file contents</td>
|
||||
<td><a href="file-operations.html">File Operations</a></td>
|
||||
<td><code>File.read()</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Run tasks in parallel</td>
|
||||
<td><a href="async-operations.html">Async Operations</a></td>
|
||||
<td><code>Fiber.new { }</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Handle runtime errors</td>
|
||||
<td><a href="error-handling.html">Error Handling</a></td>
|
||||
<td><code>fiber.try()</code></td>
|
||||
</tr>
|
||||
</table>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,243 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Working with JSON" %}
|
||||
{% set breadcrumb = [{"url": "howto/index.html", "title": "How-To Guides"}, {"title": "JSON Parsing"}] %}
|
||||
{% set prev_page = {"url": "howto/http-requests.html", "title": "HTTP Requests"} %}
|
||||
{% set next_page = {"url": "howto/regex-patterns.html", "title": "Regex Patterns"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Working with JSON</h1>
|
||||
|
||||
<h2>Parse JSON String</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var jsonStr = '{"name": "Alice", "age": 30}'
|
||||
var data = Json.parse(jsonStr)
|
||||
|
||||
System.print(data["name"]) // Alice
|
||||
System.print(data["age"]) // 30</code></pre>
|
||||
|
||||
<h2>Parse JSON Array</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var jsonStr = '[1, 2, 3, "four", true, null]'
|
||||
var items = Json.parse(jsonStr)
|
||||
|
||||
for (item in items) {
|
||||
System.print(item)
|
||||
}</code></pre>
|
||||
|
||||
<h2>Access Nested Objects</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var jsonStr = '{"user": {"name": "Bob", "address": {"city": "NYC"}}}'
|
||||
var data = Json.parse(jsonStr)
|
||||
|
||||
System.print(data["user"]["name"]) // Bob
|
||||
System.print(data["user"]["address"]["city"]) // NYC</code></pre>
|
||||
|
||||
<h2>Convert Wren Object to JSON</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var data = {
|
||||
"name": "Charlie",
|
||||
"age": 25,
|
||||
"active": true
|
||||
}
|
||||
|
||||
var jsonStr = Json.stringify(data)
|
||||
System.print(jsonStr) // {"name":"Charlie","age":25,"active":true}</code></pre>
|
||||
|
||||
<h2>Pretty Print JSON</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var data = {
|
||||
"users": [
|
||||
{"name": "Alice", "age": 30},
|
||||
{"name": "Bob", "age": 25}
|
||||
]
|
||||
}
|
||||
|
||||
var pretty = Json.stringify(data, 2)
|
||||
System.print(pretty)</code></pre>
|
||||
|
||||
<p>Output:</p>
|
||||
<pre><code>{
|
||||
"users": [
|
||||
{
|
||||
"name": "Alice",
|
||||
"age": 30
|
||||
},
|
||||
{
|
||||
"name": "Bob",
|
||||
"age": 25
|
||||
}
|
||||
]
|
||||
}</code></pre>
|
||||
|
||||
<h2>Check if Key Exists</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var data = Json.parse('{"name": "Alice"}')
|
||||
|
||||
if (data.containsKey("name")) {
|
||||
System.print("Name: %(data["name"])")
|
||||
}
|
||||
|
||||
if (!data.containsKey("age")) {
|
||||
System.print("Age not specified")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Provide Default Values</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var data = Json.parse('{"name": "Alice"}')
|
||||
|
||||
var name = data["name"]
|
||||
var age = data.containsKey("age") ? data["age"] : 0
|
||||
var city = data.containsKey("city") ? data["city"] : "Unknown"
|
||||
|
||||
System.print("%(name), %(age), %(city)")</code></pre>
|
||||
|
||||
<h2>Iterate Over Object Keys</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var data = Json.parse('{"a": 1, "b": 2, "c": 3}')
|
||||
|
||||
for (key in data.keys) {
|
||||
System.print("%(key): %(data[key])")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Iterate Over Array</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var users = Json.parse('[{"name": "Alice"}, {"name": "Bob"}]')
|
||||
|
||||
for (i in 0...users.count) {
|
||||
System.print("%(i + 1). %(users[i]["name"])")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Modify JSON Data</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var data = Json.parse('{"name": "Alice", "age": 30}')
|
||||
|
||||
data["age"] = 31
|
||||
data["email"] = "alice@example.com"
|
||||
data.remove("name")
|
||||
|
||||
System.print(Json.stringify(data))</code></pre>
|
||||
|
||||
<h2>Parse JSON from File</h2>
|
||||
<pre><code>import "json" for Json
|
||||
import "io" for File
|
||||
|
||||
var content = File.read("config.json")
|
||||
var config = Json.parse(content)
|
||||
|
||||
System.print(config["setting"])</code></pre>
|
||||
|
||||
<h2>Write JSON to File</h2>
|
||||
<pre><code>import "json" for Json
|
||||
import "io" for File
|
||||
|
||||
var data = {
|
||||
"database": "myapp.db",
|
||||
"port": 8080,
|
||||
"debug": true
|
||||
}
|
||||
|
||||
File.write("config.json", Json.stringify(data, 2))</code></pre>
|
||||
|
||||
<h2>Handle Parse Errors</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var jsonStr = "invalid json {"
|
||||
|
||||
var fiber = Fiber.new { Json.parse(jsonStr) }
|
||||
var result = fiber.try()
|
||||
|
||||
if (fiber.error) {
|
||||
System.print("Parse error: %(fiber.error)")
|
||||
} else {
|
||||
System.print(result)
|
||||
}</code></pre>
|
||||
|
||||
<h2>Work with Null Values</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var data = Json.parse('{"name": "Alice", "address": null}')
|
||||
|
||||
if (data["address"] == null) {
|
||||
System.print("No address provided")
|
||||
}
|
||||
|
||||
var output = {"value": null}
|
||||
System.print(Json.stringify(output)) // {"value":null}</code></pre>
|
||||
|
||||
<h2>Build JSON Array Dynamically</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var users = []
|
||||
|
||||
users.add({"name": "Alice", "role": "admin"})
|
||||
users.add({"name": "Bob", "role": "user"})
|
||||
users.add({"name": "Charlie", "role": "user"})
|
||||
|
||||
System.print(Json.stringify(users, 2))</code></pre>
|
||||
|
||||
<h2>Filter JSON Array</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var users = Json.parse('[
|
||||
{"name": "Alice", "age": 30},
|
||||
{"name": "Bob", "age": 17},
|
||||
{"name": "Charlie", "age": 25}
|
||||
]')
|
||||
|
||||
var adults = []
|
||||
for (user in users) {
|
||||
if (user["age"] >= 18) {
|
||||
adults.add(user)
|
||||
}
|
||||
}
|
||||
|
||||
System.print("Adults: %(Json.stringify(adults))")</code></pre>
|
||||
|
||||
<h2>Transform JSON Data</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var users = Json.parse('[
|
||||
{"firstName": "Alice", "lastName": "Smith"},
|
||||
{"firstName": "Bob", "lastName": "Jones"}
|
||||
]')
|
||||
|
||||
var names = []
|
||||
for (user in users) {
|
||||
names.add("%(user["firstName"]) %(user["lastName"])")
|
||||
}
|
||||
|
||||
System.print(names.join(", "))</code></pre>
|
||||
|
||||
<h2>Merge JSON Objects</h2>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var defaults = {"theme": "light", "language": "en", "timeout": 30}
|
||||
var userPrefs = {"theme": "dark"}
|
||||
|
||||
var config = {}
|
||||
for (key in defaults.keys) {
|
||||
config[key] = defaults[key]
|
||||
}
|
||||
for (key in userPrefs.keys) {
|
||||
config[key] = userPrefs[key]
|
||||
}
|
||||
|
||||
System.print(Json.stringify(config, 2))</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">See Also</div>
|
||||
<p>For full API documentation, see the <a href="../api/json.html">JSON module reference</a>.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,237 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Using Regular Expressions" %}
|
||||
{% set breadcrumb = [{"url": "howto/index.html", "title": "How-To Guides"}, {"title": "Regex Patterns"}] %}
|
||||
{% set prev_page = {"url": "howto/json-parsing.html", "title": "JSON Parsing"} %}
|
||||
{% set next_page = {"url": "howto/file-operations.html", "title": "File Operations"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Using Regular Expressions</h1>
|
||||
|
||||
<h2>Test if String Matches Pattern</h2>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var pattern = Regex.new("^hello")
|
||||
|
||||
System.print(pattern.test("hello world")) // true
|
||||
System.print(pattern.test("say hello")) // false</code></pre>
|
||||
|
||||
<h2>Find First Match</h2>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var pattern = Regex.new("\\d+")
|
||||
var match = pattern.match("Order 12345 shipped")
|
||||
|
||||
if (match) {
|
||||
System.print(match.text) // 12345
|
||||
System.print(match.start) // 6
|
||||
System.print(match.end) // 11
|
||||
}</code></pre>
|
||||
|
||||
<h2>Find All Matches</h2>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var pattern = Regex.new("\\d+")
|
||||
var matches = pattern.matchAll("Items: 10, 20, 30")
|
||||
|
||||
for (match in matches) {
|
||||
System.print(match.text)
|
||||
}
|
||||
// 10
|
||||
// 20
|
||||
// 30</code></pre>
|
||||
|
||||
<h2>Capture Groups</h2>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var pattern = Regex.new("(\\w+)@(\\w+\\.\\w+)")
|
||||
var match = pattern.match("Contact: alice@example.com")
|
||||
|
||||
if (match) {
|
||||
System.print(match.group(0)) // alice@example.com
|
||||
System.print(match.group(1)) // alice
|
||||
System.print(match.group(2)) // example.com
|
||||
}</code></pre>
|
||||
|
||||
<h2>Replace Matches</h2>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var pattern = Regex.new("\\bcat\\b")
|
||||
var result = pattern.replace("The cat sat on the cat mat", "dog")
|
||||
|
||||
System.print(result) // The dog sat on the dog mat</code></pre>
|
||||
|
||||
<h2>Replace with Callback</h2>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var pattern = Regex.new("\\d+")
|
||||
var result = pattern.replace("a1b2c3", Fn.new { |match|
|
||||
return "[%(match.text)]"
|
||||
})
|
||||
|
||||
System.print(result) // a[1]b[2]c[3]</code></pre>
|
||||
|
||||
<h2>Split String</h2>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var pattern = Regex.new("[,;\\s]+")
|
||||
var parts = pattern.split("apple, banana; cherry date")
|
||||
|
||||
for (part in parts) {
|
||||
System.print(part)
|
||||
}
|
||||
// apple
|
||||
// banana
|
||||
// cherry
|
||||
// date</code></pre>
|
||||
|
||||
<h2>Case Insensitive Matching</h2>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var pattern = Regex.new("hello", "i")
|
||||
|
||||
System.print(pattern.test("Hello World")) // true
|
||||
System.print(pattern.test("HELLO")) // true</code></pre>
|
||||
|
||||
<h2>Multiline Matching</h2>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var text = "Line 1\nLine 2\nLine 3"
|
||||
var pattern = Regex.new("^Line", "m")
|
||||
|
||||
var matches = pattern.matchAll(text)
|
||||
System.print(matches.count) // 3</code></pre>
|
||||
|
||||
<h2>Common Patterns</h2>
|
||||
|
||||
<h3>Validate Email</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var emailPattern = Regex.new("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$")
|
||||
|
||||
System.print(emailPattern.test("user@example.com")) // true
|
||||
System.print(emailPattern.test("invalid-email")) // false</code></pre>
|
||||
|
||||
<h3>Validate URL</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var urlPattern = Regex.new("^https?://[a-zA-Z0-9.-]+(/.*)?$")
|
||||
|
||||
System.print(urlPattern.test("https://example.com")) // true
|
||||
System.print(urlPattern.test("http://example.com/path")) // true
|
||||
System.print(urlPattern.test("ftp://invalid")) // false</code></pre>
|
||||
|
||||
<h3>Validate Phone Number</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var phonePattern = Regex.new("^\\+?\\d{1,3}[-.\\s]?\\(?\\d{3}\\)?[-.\\s]?\\d{3}[-.\\s]?\\d{4}$")
|
||||
|
||||
System.print(phonePattern.test("+1-555-123-4567")) // true
|
||||
System.print(phonePattern.test("(555) 123-4567")) // true</code></pre>
|
||||
|
||||
<h3>Extract Numbers</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var numberPattern = Regex.new("-?\\d+\\.?\\d*")
|
||||
var text = "Temperature: -5.5 to 32.0 degrees"
|
||||
|
||||
var matches = numberPattern.matchAll(text)
|
||||
for (match in matches) {
|
||||
System.print(match.text)
|
||||
}
|
||||
// -5.5
|
||||
// 32.0</code></pre>
|
||||
|
||||
<h3>Extract Hashtags</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var hashtagPattern = Regex.new("#\\w+")
|
||||
var text = "Check out #wren and #programming!"
|
||||
|
||||
var matches = hashtagPattern.matchAll(text)
|
||||
for (match in matches) {
|
||||
System.print(match.text)
|
||||
}
|
||||
// #wren
|
||||
// #programming</code></pre>
|
||||
|
||||
<h3>Remove HTML Tags</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var tagPattern = Regex.new("<[^>]+>")
|
||||
var html = "<p>Hello <b>World</b>!</p>"
|
||||
|
||||
var text = tagPattern.replace(html, "")
|
||||
System.print(text) // Hello World!</code></pre>
|
||||
|
||||
<h3>Validate Password Strength</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var hasUpper = Regex.new("[A-Z]")
|
||||
var hasLower = Regex.new("[a-z]")
|
||||
var hasDigit = Regex.new("\\d")
|
||||
var hasSpecial = Regex.new("[!@#$%^&*]")
|
||||
var minLength = 8
|
||||
|
||||
var validatePassword = Fn.new { |password|
|
||||
if (password.count < minLength) return false
|
||||
if (!hasUpper.test(password)) return false
|
||||
if (!hasLower.test(password)) return false
|
||||
if (!hasDigit.test(password)) return false
|
||||
if (!hasSpecial.test(password)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
System.print(validatePassword.call("Weak")) // false
|
||||
System.print(validatePassword.call("Strong@Pass1")) // true</code></pre>
|
||||
|
||||
<h3>Parse Log Lines</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var logPattern = Regex.new("\\[(\\d{4}-\\d{2}-\\d{2})\\]\\s+(\\w+):\\s+(.+)")
|
||||
|
||||
var line = "[2024-01-15] ERROR: Connection failed"
|
||||
var match = logPattern.match(line)
|
||||
|
||||
if (match) {
|
||||
System.print("Date: %(match.group(1))") // 2024-01-15
|
||||
System.print("Level: %(match.group(2))") // ERROR
|
||||
System.print("Message: %(match.group(3))") // Connection failed
|
||||
}</code></pre>
|
||||
|
||||
<h3>Validate IP Address</h3>
|
||||
<pre><code>import "regex" for Regex
|
||||
|
||||
var ipPattern = Regex.new("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$")
|
||||
|
||||
System.print(ipPattern.test("192.168.1.1")) // true
|
||||
System.print(ipPattern.test("256.1.1.1")) // false
|
||||
System.print(ipPattern.test("10.0.0.255")) // true</code></pre>
|
||||
|
||||
<h2>Pattern Syntax Quick Reference</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>Pattern</th><th>Description</th></tr>
|
||||
<tr><td><code>.</code></td><td>Any character except newline</td></tr>
|
||||
<tr><td><code>\\d</code></td><td>Digit (0-9)</td></tr>
|
||||
<tr><td><code>\\w</code></td><td>Word character (a-z, A-Z, 0-9, _)</td></tr>
|
||||
<tr><td><code>\\s</code></td><td>Whitespace</td></tr>
|
||||
<tr><td><code>^</code></td><td>Start of string/line</td></tr>
|
||||
<tr><td><code>$</code></td><td>End of string/line</td></tr>
|
||||
<tr><td><code>*</code></td><td>Zero or more</td></tr>
|
||||
<tr><td><code>+</code></td><td>One or more</td></tr>
|
||||
<tr><td><code>?</code></td><td>Zero or one</td></tr>
|
||||
<tr><td><code>{n,m}</code></td><td>Between n and m times</td></tr>
|
||||
<tr><td><code>[abc]</code></td><td>Character class</td></tr>
|
||||
<tr><td><code>[^abc]</code></td><td>Negated character class</td></tr>
|
||||
<tr><td><code>(group)</code></td><td>Capture group</td></tr>
|
||||
<tr><td><code>a|b</code></td><td>Alternation (a or b)</td></tr>
|
||||
<tr><td><code>\\b</code></td><td>Word boundary</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">See Also</div>
|
||||
<p>For full API documentation, see the <a href="../api/regex.html">Regex module reference</a>.</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,93 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'home.html' %}
|
||||
|
||||
{% set page_title = "Wren-CLI Manual" %}
|
||||
{% set next_page = {"url": "getting-started/index.html", "title": "Getting Started"} %}
|
||||
|
||||
{% block article %}
|
||||
<h2>What is Wren-CLI?</h2>
|
||||
<p>Wren-CLI is a command-line interface for the <a href="https://wren.io">Wren programming language</a>, extended with powerful modules for networking, file I/O, databases, and more. It provides an async event loop powered by libuv, making it suitable for building servers, automation scripts, and command-line tools.</p>
|
||||
|
||||
<div class="card-grid">
|
||||
<div class="card">
|
||||
<h3><a href="getting-started/index.html">Getting Started</a></h3>
|
||||
<p>Install Wren-CLI, write your first script, and learn the basics of the language.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="language/index.html">Language Reference</a></h3>
|
||||
<p>Learn about classes, methods, control flow, fibers, and the module system.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="api/index.html">API Reference</a></h3>
|
||||
<p>Complete documentation for all 32 built-in modules including HTTP, WebSocket, and SQLite.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="tutorials/index.html">Tutorials</a></h3>
|
||||
<p>Step-by-step guides for building real applications with Wren-CLI.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Available Modules</h2>
|
||||
<p>Wren-CLI provides a rich set of modules for common programming tasks:</p>
|
||||
|
||||
<h3>Networking</h3>
|
||||
<div class="module-grid">
|
||||
<a href="api/http.html" class="module-card">http</a>
|
||||
<a href="api/websocket.html" class="module-card">websocket</a>
|
||||
<a href="api/tls.html" class="module-card">tls</a>
|
||||
<a href="api/net.html" class="module-card">net</a>
|
||||
<a href="api/udp.html" class="module-card">udp</a>
|
||||
<a href="api/dns.html" class="module-card">dns</a>
|
||||
</div>
|
||||
|
||||
<h3>Data Processing</h3>
|
||||
<div class="module-grid">
|
||||
<a href="api/json.html" class="module-card">json</a>
|
||||
<a href="api/base64.html" class="module-card">base64</a>
|
||||
<a href="api/regex.html" class="module-card">regex</a>
|
||||
<a href="api/jinja.html" class="module-card">jinja</a>
|
||||
<a href="api/crypto.html" class="module-card">crypto</a>
|
||||
</div>
|
||||
|
||||
<h3>System</h3>
|
||||
<div class="module-grid">
|
||||
<a href="api/os.html" class="module-card">os</a>
|
||||
<a href="api/env.html" class="module-card">env</a>
|
||||
<a href="api/signal.html" class="module-card">signal</a>
|
||||
<a href="api/subprocess.html" class="module-card">subprocess</a>
|
||||
<a href="api/io.html" class="module-card">io</a>
|
||||
<a href="api/pathlib.html" class="module-card">pathlib</a>
|
||||
<a href="api/sysinfo.html" class="module-card">sysinfo</a>
|
||||
<a href="api/fswatch.html" class="module-card">fswatch</a>
|
||||
</div>
|
||||
|
||||
<h3>Data & Time</h3>
|
||||
<div class="module-grid">
|
||||
<a href="api/sqlite.html" class="module-card">sqlite</a>
|
||||
<a href="api/datetime.html" class="module-card">datetime</a>
|
||||
<a href="api/timer.html" class="module-card">timer</a>
|
||||
<a href="api/math.html" class="module-card">math</a>
|
||||
<a href="api/scheduler.html" class="module-card">scheduler</a>
|
||||
</div>
|
||||
|
||||
<h2>Quick Example</h2>
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
var response = Http.get("https://api.github.com/users/wren-lang")
|
||||
var data = Json.parse(response.body)
|
||||
|
||||
System.print("User: %(data["login"])")
|
||||
System.print("Repos: %(data["public_repos"])")</code></pre>
|
||||
|
||||
<h2>Features</h2>
|
||||
<ul>
|
||||
<li><strong>Async I/O</strong> - Non-blocking operations powered by libuv</li>
|
||||
<li><strong>HTTP/HTTPS</strong> - Full HTTP client with TLS support</li>
|
||||
<li><strong>WebSocket</strong> - Client and server WebSocket support</li>
|
||||
<li><strong>SQLite</strong> - Embedded database for persistent storage</li>
|
||||
<li><strong>Templates</strong> - Jinja2-compatible template engine</li>
|
||||
<li><strong>Regex</strong> - Full regular expression support</li>
|
||||
<li><strong>Cross-platform</strong> - Runs on Linux, macOS, and FreeBSD</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,322 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Classes" %}
|
||||
{% set breadcrumb = [{"url": "language/index.html", "title": "Language"}, {"title": "Classes"}] %}
|
||||
{% set prev_page = {"url": "language/index.html", "title": "Syntax Overview"} %}
|
||||
{% set next_page = {"url": "language/methods.html", "title": "Methods"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Classes</h1>
|
||||
|
||||
<p>Wren is a class-based object-oriented language. Everything in Wren is an object, and every object is an instance of a class.</p>
|
||||
|
||||
<h2>Defining Classes</h2>
|
||||
<p>Define a class with the <code>class</code> keyword:</p>
|
||||
<pre><code>class Animal {
|
||||
}</code></pre>
|
||||
|
||||
<p>This creates a class named <code>Animal</code> with no methods or fields.</p>
|
||||
|
||||
<h2>Constructors</h2>
|
||||
<p>Constructors create new instances. Define them with <code>construct</code>:</p>
|
||||
<pre><code>class Person {
|
||||
construct new(name, age) {
|
||||
_name = name
|
||||
_age = age
|
||||
}
|
||||
}
|
||||
|
||||
var alice = Person.new("Alice", 30)</code></pre>
|
||||
|
||||
<p>A class can have multiple named constructors:</p>
|
||||
<pre><code>class Point {
|
||||
construct new(x, y) {
|
||||
_x = x
|
||||
_y = y
|
||||
}
|
||||
|
||||
construct origin() {
|
||||
_x = 0
|
||||
_y = 0
|
||||
}
|
||||
|
||||
construct fromList(list) {
|
||||
_x = list[0]
|
||||
_y = list[1]
|
||||
}
|
||||
}
|
||||
|
||||
var p1 = Point.new(3, 4)
|
||||
var p2 = Point.origin()
|
||||
var p3 = Point.fromList([5, 6])</code></pre>
|
||||
|
||||
<h2>Fields</h2>
|
||||
<p>Instance fields are prefixed with <code>_</code>. They are private to the class:</p>
|
||||
<pre><code>class Counter {
|
||||
construct new() {
|
||||
_count = 0
|
||||
}
|
||||
|
||||
increment() {
|
||||
_count = _count + 1
|
||||
}
|
||||
|
||||
count { _count }
|
||||
}</code></pre>
|
||||
|
||||
<p>Fields are not declared; they are created when first assigned.</p>
|
||||
|
||||
<h2>Getters and Setters</h2>
|
||||
<p>Getters are methods without parentheses:</p>
|
||||
<pre><code>class Circle {
|
||||
construct new(radius) {
|
||||
_radius = radius
|
||||
}
|
||||
|
||||
radius { _radius }
|
||||
area { 3.14159 * _radius * _radius }
|
||||
}
|
||||
|
||||
var c = Circle.new(5)
|
||||
System.print(c.radius) // 5
|
||||
System.print(c.area) // 78.53975</code></pre>
|
||||
|
||||
<p>Setters use <code>=</code> suffix:</p>
|
||||
<pre><code>class Circle {
|
||||
construct new(radius) {
|
||||
_radius = radius
|
||||
}
|
||||
|
||||
radius { _radius }
|
||||
radius=(value) { _radius = value }
|
||||
}
|
||||
|
||||
var c = Circle.new(5)
|
||||
c.radius = 10
|
||||
System.print(c.radius) // 10</code></pre>
|
||||
|
||||
<h2>Methods</h2>
|
||||
<p>Methods are defined inside the class body:</p>
|
||||
<pre><code>class Rectangle {
|
||||
construct new(width, height) {
|
||||
_width = width
|
||||
_height = height
|
||||
}
|
||||
|
||||
area() {
|
||||
return _width * _height
|
||||
}
|
||||
|
||||
perimeter() {
|
||||
return 2 * (_width + _height)
|
||||
}
|
||||
}
|
||||
|
||||
var rect = Rectangle.new(4, 5)
|
||||
System.print(rect.area()) // 20
|
||||
System.print(rect.perimeter()) // 18</code></pre>
|
||||
|
||||
<h2>Static Members</h2>
|
||||
<p>Static methods and fields belong to the class, not instances:</p>
|
||||
<pre><code>class Math {
|
||||
static pi { 3.14159 }
|
||||
|
||||
static square(x) {
|
||||
return x * x
|
||||
}
|
||||
|
||||
static cube(x) {
|
||||
return x * x * x
|
||||
}
|
||||
}
|
||||
|
||||
System.print(Math.pi) // 3.14159
|
||||
System.print(Math.square(4)) // 16
|
||||
System.print(Math.cube(3)) // 27</code></pre>
|
||||
|
||||
<p>Static fields use double underscore:</p>
|
||||
<pre><code>class Counter {
|
||||
static count { __count }
|
||||
|
||||
static increment() {
|
||||
if (__count == null) __count = 0
|
||||
__count = __count + 1
|
||||
}
|
||||
}
|
||||
|
||||
Counter.increment()
|
||||
Counter.increment()
|
||||
System.print(Counter.count) // 2</code></pre>
|
||||
|
||||
<h2>Inheritance</h2>
|
||||
<p>Classes can inherit from a single superclass using <code>is</code>:</p>
|
||||
<pre><code>class Animal {
|
||||
construct new(name) {
|
||||
_name = name
|
||||
}
|
||||
|
||||
name { _name }
|
||||
|
||||
speak() {
|
||||
System.print("...")
|
||||
}
|
||||
}
|
||||
|
||||
class Dog is Animal {
|
||||
construct new(name, breed) {
|
||||
super(name)
|
||||
_breed = breed
|
||||
}
|
||||
|
||||
breed { _breed }
|
||||
|
||||
speak() {
|
||||
System.print("Woof!")
|
||||
}
|
||||
}
|
||||
|
||||
var dog = Dog.new("Rex", "German Shepherd")
|
||||
System.print(dog.name) // Rex
|
||||
System.print(dog.breed) // German Shepherd
|
||||
dog.speak() // Woof!</code></pre>
|
||||
|
||||
<h3>Calling Super</h3>
|
||||
<p>Use <code>super</code> to call the superclass constructor or methods:</p>
|
||||
<pre><code>class Parent {
|
||||
construct new() {
|
||||
_value = 10
|
||||
}
|
||||
|
||||
value { _value }
|
||||
|
||||
describe() {
|
||||
System.print("Parent value: %(_value)")
|
||||
}
|
||||
}
|
||||
|
||||
class Child is Parent {
|
||||
construct new() {
|
||||
super()
|
||||
_extra = 20
|
||||
}
|
||||
|
||||
describe() {
|
||||
super.describe()
|
||||
System.print("Child extra: %(_extra)")
|
||||
}
|
||||
}
|
||||
|
||||
var child = Child.new()
|
||||
child.describe()
|
||||
// Output:
|
||||
// Parent value: 10
|
||||
// Child extra: 20</code></pre>
|
||||
|
||||
<h2>This</h2>
|
||||
<p>Use <code>this</code> to refer to the current instance:</p>
|
||||
<pre><code>class Node {
|
||||
construct new(value) {
|
||||
_value = value
|
||||
_next = null
|
||||
}
|
||||
|
||||
value { _value }
|
||||
next { _next }
|
||||
|
||||
append(value) {
|
||||
_next = Node.new(value)
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
||||
var n = Node.new(1).append(2).append(3)</code></pre>
|
||||
|
||||
<h2>Object Class</h2>
|
||||
<p>All classes implicitly inherit from <code>Object</code>:</p>
|
||||
<pre><code>class Foo {}
|
||||
|
||||
System.print(Foo is Class) // true
|
||||
System.print(Foo.supertype) // Object</code></pre>
|
||||
|
||||
<h2>Type Checking</h2>
|
||||
<p>Use <code>is</code> to check if an object is an instance of a class:</p>
|
||||
<pre><code>var dog = Dog.new("Rex", "Shepherd")
|
||||
|
||||
System.print(dog is Dog) // true
|
||||
System.print(dog is Animal) // true
|
||||
System.print(dog is Object) // true
|
||||
System.print(dog is String) // false</code></pre>
|
||||
|
||||
<p>Get the class of an object with <code>type</code>:</p>
|
||||
<pre><code>System.print(dog.type) // Dog
|
||||
System.print(dog.type.name) // Dog
|
||||
System.print(dog.type.supertype) // Animal</code></pre>
|
||||
|
||||
<h2>Foreign Classes</h2>
|
||||
<p>Foreign classes are implemented in C. They can hold native data:</p>
|
||||
<pre><code>foreign class Socket {
|
||||
construct new() {}
|
||||
foreign connect(host, port)
|
||||
foreign send(data)
|
||||
foreign receive()
|
||||
foreign close()
|
||||
}</code></pre>
|
||||
|
||||
<p>Foreign classes are used by built-in modules to provide native functionality.</p>
|
||||
|
||||
<h2>Complete Example</h2>
|
||||
<pre><code>class Shape {
|
||||
construct new() {}
|
||||
|
||||
area { 0 }
|
||||
perimeter { 0 }
|
||||
|
||||
describe() {
|
||||
System.print("Area: %(area)")
|
||||
System.print("Perimeter: %(perimeter)")
|
||||
}
|
||||
}
|
||||
|
||||
class Rectangle is Shape {
|
||||
construct new(width, height) {
|
||||
_width = width
|
||||
_height = height
|
||||
}
|
||||
|
||||
width { _width }
|
||||
height { _height }
|
||||
area { _width * _height }
|
||||
perimeter { 2 * (_width + _height) }
|
||||
}
|
||||
|
||||
class Square is Rectangle {
|
||||
construct new(side) {
|
||||
super(side, side)
|
||||
}
|
||||
}
|
||||
|
||||
class Circle is Shape {
|
||||
construct new(radius) {
|
||||
_radius = radius
|
||||
}
|
||||
|
||||
static pi { 3.14159 }
|
||||
|
||||
radius { _radius }
|
||||
area { Circle.pi * _radius * _radius }
|
||||
perimeter { 2 * Circle.pi * _radius }
|
||||
}
|
||||
|
||||
var shapes = [
|
||||
Rectangle.new(4, 5),
|
||||
Square.new(3),
|
||||
Circle.new(2)
|
||||
]
|
||||
|
||||
for (shape in shapes) {
|
||||
System.print("%(shape.type.name):")
|
||||
shape.describe()
|
||||
System.print("")
|
||||
}</code></pre>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,232 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Control Flow" %}
|
||||
{% set breadcrumb = [{"url": "language/index.html", "title": "Language"}, {"title": "Control Flow"}] %}
|
||||
{% set prev_page = {"url": "language/methods.html", "title": "Methods"} %}
|
||||
{% set next_page = {"url": "language/fibers.html", "title": "Fibers"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Control Flow</h1>
|
||||
|
||||
<p>Wren provides standard control flow constructs for conditionals, loops, and early exit.</p>
|
||||
|
||||
<h2>Truthiness</h2>
|
||||
<p>Before covering control flow, understand how Wren evaluates truthiness:</p>
|
||||
<ul>
|
||||
<li><code>false</code> is falsy</li>
|
||||
<li><code>null</code> is falsy</li>
|
||||
<li>Everything else is truthy (including <code>0</code>, <code>""</code>, <code>[]</code>)</li>
|
||||
</ul>
|
||||
<pre><code>if (0) System.print("0 is truthy")
|
||||
if ("") System.print("empty string is truthy")
|
||||
if ([]) System.print("empty list is truthy")
|
||||
if (false) System.print("false is falsy") // Not printed
|
||||
if (null) System.print("null is falsy") // Not printed</code></pre>
|
||||
|
||||
<h2>If Statements</h2>
|
||||
<p>Basic conditional execution:</p>
|
||||
<pre><code>if (condition) {
|
||||
System.print("condition is true")
|
||||
}</code></pre>
|
||||
|
||||
<h3>If-Else</h3>
|
||||
<pre><code>if (score >= 90) {
|
||||
System.print("A")
|
||||
} else {
|
||||
System.print("Not A")
|
||||
}</code></pre>
|
||||
|
||||
<h3>If-Else If-Else</h3>
|
||||
<pre><code>if (score >= 90) {
|
||||
System.print("A")
|
||||
} else if (score >= 80) {
|
||||
System.print("B")
|
||||
} else if (score >= 70) {
|
||||
System.print("C")
|
||||
} else {
|
||||
System.print("F")
|
||||
}</code></pre>
|
||||
|
||||
<h3>Single Expression</h3>
|
||||
<p>For single expressions, braces are optional:</p>
|
||||
<pre><code>if (x > 0) System.print("positive")</code></pre>
|
||||
|
||||
<h2>Ternary Operator</h2>
|
||||
<p>For inline conditionals:</p>
|
||||
<pre><code>var status = age >= 18 ? "adult" : "minor"
|
||||
var max = a > b ? a : b</code></pre>
|
||||
|
||||
<h2>Logical Operators</h2>
|
||||
|
||||
<h3>And (&&)</h3>
|
||||
<p>Returns the first falsy value or the last value:</p>
|
||||
<pre><code>System.print(true && false) // false
|
||||
System.print(true && true) // true
|
||||
System.print(1 && 2) // 2
|
||||
System.print(null && 1) // null</code></pre>
|
||||
|
||||
<h3>Or (||)</h3>
|
||||
<p>Returns the first truthy value or the last value:</p>
|
||||
<pre><code>System.print(false || true) // true
|
||||
System.print(false || false) // false
|
||||
System.print(null || "default") // default
|
||||
System.print(1 || 2) // 1</code></pre>
|
||||
|
||||
<p>Use <code>||</code> for default values:</p>
|
||||
<pre><code>var name = providedName || "Anonymous"</code></pre>
|
||||
|
||||
<h2>While Loops</h2>
|
||||
<p>Repeat while a condition is true:</p>
|
||||
<pre><code>var i = 0
|
||||
while (i < 5) {
|
||||
System.print(i)
|
||||
i = i + 1
|
||||
}</code></pre>
|
||||
|
||||
<div class="example-output">0
|
||||
1
|
||||
2
|
||||
3
|
||||
4</div>
|
||||
|
||||
<h2>For Loops</h2>
|
||||
<p>Iterate over any sequence:</p>
|
||||
<pre><code>for (item in [1, 2, 3]) {
|
||||
System.print(item)
|
||||
}</code></pre>
|
||||
|
||||
<h3>Range Iteration</h3>
|
||||
<pre><code>for (i in 1..5) {
|
||||
System.print(i)
|
||||
}
|
||||
// Prints: 1 2 3 4 5
|
||||
|
||||
for (i in 1...5) {
|
||||
System.print(i)
|
||||
}
|
||||
// Prints: 1 2 3 4 (exclusive)</code></pre>
|
||||
|
||||
<h3>String Iteration</h3>
|
||||
<pre><code>for (char in "hello") {
|
||||
System.print(char)
|
||||
}
|
||||
// Prints each character</code></pre>
|
||||
|
||||
<h3>Map Iteration</h3>
|
||||
<pre><code>var person = {"name": "Alice", "age": 30}
|
||||
for (key in person.keys) {
|
||||
System.print("%(key): %(person[key])")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Break</h2>
|
||||
<p>Exit a loop early:</p>
|
||||
<pre><code>for (i in 1..100) {
|
||||
if (i > 5) break
|
||||
System.print(i)
|
||||
}
|
||||
// Prints: 1 2 3 4 5</code></pre>
|
||||
|
||||
<h2>Continue</h2>
|
||||
<p>Skip to the next iteration:</p>
|
||||
<pre><code>for (i in 1..10) {
|
||||
if (i % 2 == 0) continue
|
||||
System.print(i)
|
||||
}
|
||||
// Prints: 1 3 5 7 9 (odd numbers only)</code></pre>
|
||||
|
||||
<h2>Block Scoping</h2>
|
||||
<p>Blocks create new scopes:</p>
|
||||
<pre><code>var x = "outer"
|
||||
{
|
||||
var x = "inner"
|
||||
System.print(x) // inner
|
||||
}
|
||||
System.print(x) // outer</code></pre>
|
||||
|
||||
<p>Variables declared in a block are not visible outside:</p>
|
||||
<pre><code>if (true) {
|
||||
var temp = "temporary"
|
||||
}
|
||||
// temp is not accessible here</code></pre>
|
||||
|
||||
<h2>Iterating with Index</h2>
|
||||
<p>Use range to get indices:</p>
|
||||
<pre><code>var list = ["a", "b", "c"]
|
||||
for (i in 0...list.count) {
|
||||
System.print("%(i): %(list[i])")
|
||||
}</code></pre>
|
||||
|
||||
<div class="example-output">0: a
|
||||
1: b
|
||||
2: c</div>
|
||||
|
||||
<h2>Infinite Loops</h2>
|
||||
<p>Create with <code>while (true)</code>:</p>
|
||||
<pre><code>var count = 0
|
||||
while (true) {
|
||||
count = count + 1
|
||||
if (count >= 5) break
|
||||
System.print(count)
|
||||
}</code></pre>
|
||||
|
||||
<h2>Nested Loops</h2>
|
||||
<pre><code>for (i in 1..3) {
|
||||
for (j in 1..3) {
|
||||
System.print("%(i), %(j)")
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<p>Break only exits the innermost loop:</p>
|
||||
<pre><code>for (i in 1..3) {
|
||||
for (j in 1..10) {
|
||||
if (j > 2) break // Only breaks inner loop
|
||||
System.print("%(i), %(j)")
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h2>Iteration Patterns</h2>
|
||||
|
||||
<h3>Filtering</h3>
|
||||
<pre><code>var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
var evens = []
|
||||
for (n in numbers) {
|
||||
if (n % 2 == 0) evens.add(n)
|
||||
}
|
||||
System.print(evens) // [2, 4, 6, 8, 10]</code></pre>
|
||||
|
||||
<h3>Mapping</h3>
|
||||
<pre><code>var numbers = [1, 2, 3, 4, 5]
|
||||
var squared = []
|
||||
for (n in numbers) {
|
||||
squared.add(n * n)
|
||||
}
|
||||
System.print(squared) // [1, 4, 9, 16, 25]</code></pre>
|
||||
|
||||
<h3>Finding</h3>
|
||||
<pre><code>var numbers = [1, 3, 5, 8, 9, 11]
|
||||
var firstEven = null
|
||||
for (n in numbers) {
|
||||
if (n % 2 == 0) {
|
||||
firstEven = n
|
||||
break
|
||||
}
|
||||
}
|
||||
System.print(firstEven) // 8</code></pre>
|
||||
|
||||
<h3>Reducing</h3>
|
||||
<pre><code>var numbers = [1, 2, 3, 4, 5]
|
||||
var sum = 0
|
||||
for (n in numbers) {
|
||||
sum = sum + n
|
||||
}
|
||||
System.print(sum) // 15</code></pre>
|
||||
|
||||
<h2>Functional Alternatives</h2>
|
||||
<p>Lists provide functional methods that are often cleaner:</p>
|
||||
<pre><code>var numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
var evens = numbers.where { |n| n % 2 == 0 }.toList
|
||||
var squared = numbers.map { |n| n * n }.toList
|
||||
var sum = numbers.reduce(0) { |acc, n| acc + n }</code></pre>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,284 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Fibers" %}
|
||||
{% set breadcrumb = [{"url": "language/index.html", "title": "Language"}, {"title": "Fibers"}] %}
|
||||
{% set prev_page = {"url": "language/control-flow.html", "title": "Control Flow"} %}
|
||||
{% set next_page = {"url": "language/modules.html", "title": "Modules"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Fibers</h1>
|
||||
|
||||
<p>Fibers are Wren's mechanism for cooperative concurrency. They are lightweight threads of execution that you explicitly control. Unlike OS threads, only one fiber runs at a time, and switching between them is explicit.</p>
|
||||
|
||||
<h2>Creating Fibers</h2>
|
||||
<p>Create a fiber with <code>Fiber.new</code>:</p>
|
||||
<pre><code>var fiber = Fiber.new {
|
||||
System.print("Inside fiber")
|
||||
}</code></pre>
|
||||
|
||||
<p>The fiber does not run immediately. It is suspended until you start it.</p>
|
||||
|
||||
<h2>Running Fibers</h2>
|
||||
|
||||
<h3>call()</h3>
|
||||
<p>Start a fiber and wait for it to complete or yield:</p>
|
||||
<pre><code>var fiber = Fiber.new {
|
||||
System.print("Running")
|
||||
}
|
||||
|
||||
fiber.call() // Prints "Running"</code></pre>
|
||||
|
||||
<h3>try()</h3>
|
||||
<p>Start a fiber and catch any runtime errors:</p>
|
||||
<pre><code>var fiber = Fiber.new {
|
||||
Fiber.abort("Something went wrong")
|
||||
}
|
||||
|
||||
var error = fiber.try()
|
||||
System.print("Error: %(error)") // Error: Something went wrong</code></pre>
|
||||
|
||||
<h2>Yielding</h2>
|
||||
<p>Fibers can pause execution and return control to the caller:</p>
|
||||
<pre><code>var fiber = Fiber.new {
|
||||
System.print("First")
|
||||
Fiber.yield()
|
||||
System.print("Second")
|
||||
Fiber.yield()
|
||||
System.print("Third")
|
||||
}
|
||||
|
||||
fiber.call() // Prints "First"
|
||||
fiber.call() // Prints "Second"
|
||||
fiber.call() // Prints "Third"</code></pre>
|
||||
|
||||
<h3>Yielding Values</h3>
|
||||
<pre><code>var counter = Fiber.new {
|
||||
Fiber.yield(1)
|
||||
Fiber.yield(2)
|
||||
Fiber.yield(3)
|
||||
}
|
||||
|
||||
System.print(counter.call()) // 1
|
||||
System.print(counter.call()) // 2
|
||||
System.print(counter.call()) // 3</code></pre>
|
||||
|
||||
<h3>Passing Values In</h3>
|
||||
<pre><code>var adder = Fiber.new {
|
||||
var total = 0
|
||||
while (true) {
|
||||
var value = Fiber.yield(total)
|
||||
total = total + value
|
||||
}
|
||||
}
|
||||
|
||||
adder.call() // Start the fiber
|
||||
System.print(adder.call(5)) // 5
|
||||
System.print(adder.call(10)) // 15
|
||||
System.print(adder.call(3)) // 18</code></pre>
|
||||
|
||||
<h2>Fiber State</h2>
|
||||
<p>Check the state of a fiber:</p>
|
||||
<pre><code>var fiber = Fiber.new {
|
||||
Fiber.yield()
|
||||
}
|
||||
|
||||
System.print(fiber.isDone) // false
|
||||
|
||||
fiber.call()
|
||||
System.print(fiber.isDone) // false (yielded)
|
||||
|
||||
fiber.call()
|
||||
System.print(fiber.isDone) // true (completed)</code></pre>
|
||||
|
||||
<h2>Error Handling</h2>
|
||||
<p>Fibers can abort with an error:</p>
|
||||
<pre><code>Fiber.abort("Error message")</code></pre>
|
||||
|
||||
<p>Use <code>try()</code> to catch errors:</p>
|
||||
<pre><code>var fiber = Fiber.new {
|
||||
var x = 1 / 0 // Will cause infinity, not error
|
||||
[1, 2, 3][10] // This will cause an error
|
||||
}
|
||||
|
||||
var error = fiber.try()
|
||||
if (error != null) {
|
||||
System.print("Caught: %(error)")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Current Fiber</h2>
|
||||
<p>Get the currently executing fiber:</p>
|
||||
<pre><code>var current = Fiber.current
|
||||
System.print(current) // Fiber instance</code></pre>
|
||||
|
||||
<h2>Generator Pattern</h2>
|
||||
<p>Fibers naturally implement generators:</p>
|
||||
<pre><code>var range = Fn.new { |start, end|
|
||||
return Fiber.new {
|
||||
var i = start
|
||||
while (i <= end) {
|
||||
Fiber.yield(i)
|
||||
i = i + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var nums = range.call(1, 5)
|
||||
while (!nums.isDone) {
|
||||
var value = nums.call()
|
||||
if (value != null) System.print(value)
|
||||
}</code></pre>
|
||||
|
||||
<h2>Coroutine Pattern</h2>
|
||||
<p>Two fibers can communicate back and forth:</p>
|
||||
<pre><code>var producer = Fiber.new {
|
||||
for (i in 1..5) {
|
||||
System.print("Producing %(i)")
|
||||
Fiber.yield(i)
|
||||
}
|
||||
}
|
||||
|
||||
var consumer = Fiber.new {
|
||||
while (!producer.isDone) {
|
||||
var value = producer.call()
|
||||
if (value != null) {
|
||||
System.print("Consuming %(value)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
consumer.call()</code></pre>
|
||||
|
||||
<h2>Async Operations with Scheduler</h2>
|
||||
<p>Wren-CLI uses fibers for async I/O. The scheduler suspends fibers during I/O and resumes them when the operation completes:</p>
|
||||
<pre><code>import "timer" for Timer
|
||||
|
||||
System.print("Before sleep")
|
||||
Timer.sleep(1000) // Fiber suspends here
|
||||
System.print("After sleep")</code></pre>
|
||||
|
||||
<p>The scheduler pattern internally looks like:</p>
|
||||
<pre><code>import "scheduler" for Scheduler
|
||||
|
||||
Scheduler.await_ {
|
||||
Timer.sleep_(1000, Fiber.current)
|
||||
}</code></pre>
|
||||
|
||||
<h2>Fiber Methods</h2>
|
||||
|
||||
<h3>Static Methods</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Method</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Fiber.new { block }</code></td>
|
||||
<td>Create a new fiber</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Fiber.current</code></td>
|
||||
<td>Get the current fiber</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Fiber.yield()</code></td>
|
||||
<td>Pause and return null</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Fiber.yield(value)</code></td>
|
||||
<td>Pause and return value</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Fiber.abort(message)</code></td>
|
||||
<td>Abort with error</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Fiber.suspend()</code></td>
|
||||
<td>Suspend the current fiber</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Instance Methods</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Method</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fiber.call()</code></td>
|
||||
<td>Run fiber, wait for yield/complete</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fiber.call(value)</code></td>
|
||||
<td>Run with value passed to yield</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fiber.try()</code></td>
|
||||
<td>Run and catch errors</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fiber.isDone</code></td>
|
||||
<td>True if completed</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fiber.error</code></td>
|
||||
<td>Error message if aborted</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fiber.transfer()</code></td>
|
||||
<td>Switch to this fiber</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fiber.transfer(value)</code></td>
|
||||
<td>Switch with value</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>fiber.transferError(msg)</code></td>
|
||||
<td>Switch and raise error</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>Transfer vs Call</h2>
|
||||
<p><code>call()</code> maintains a call stack and returns when the fiber yields:</p>
|
||||
<pre><code>var a = Fiber.new {
|
||||
System.print("a: before yield")
|
||||
Fiber.yield()
|
||||
System.print("a: after yield")
|
||||
}
|
||||
|
||||
a.call()
|
||||
System.print("back in main")
|
||||
a.call()
|
||||
|
||||
// Output:
|
||||
// a: before yield
|
||||
// back in main
|
||||
// a: after yield</code></pre>
|
||||
|
||||
<p><code>transfer()</code> does not maintain a call stack:</p>
|
||||
<pre><code>var main = Fiber.current
|
||||
var a = null
|
||||
var b = null
|
||||
|
||||
a = Fiber.new {
|
||||
System.print("in a")
|
||||
b.transfer()
|
||||
System.print("back in a")
|
||||
main.transfer()
|
||||
}
|
||||
|
||||
b = Fiber.new {
|
||||
System.print("in b")
|
||||
a.transfer()
|
||||
System.print("back in b")
|
||||
}
|
||||
|
||||
a.transfer()
|
||||
System.print("done")
|
||||
|
||||
// Output:
|
||||
// in a
|
||||
// in b
|
||||
// back in a
|
||||
// done</code></pre>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,204 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Syntax Overview" %}
|
||||
{% set breadcrumb = [{"title": "Language Reference"}] %}
|
||||
{% set prev_page = {"url": "getting-started/repl.html", "title": "Using the REPL"} %}
|
||||
{% set next_page = {"url": "language/classes.html", "title": "Classes"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Syntax Overview</h1>
|
||||
|
||||
<p>Wren is a small, fast, class-based scripting language with a clean syntax inspired by languages like Dart, Lua, and Smalltalk. This section covers the core language features.</p>
|
||||
|
||||
<div class="toc">
|
||||
<h4>Language Topics</h4>
|
||||
<ul>
|
||||
<li><a href="classes.html">Classes</a> - Object-oriented programming</li>
|
||||
<li><a href="methods.html">Methods</a> - Method definition and operators</li>
|
||||
<li><a href="control-flow.html">Control Flow</a> - Conditionals and loops</li>
|
||||
<li><a href="fibers.html">Fibers</a> - Cooperative concurrency</li>
|
||||
<li><a href="modules.html">Modules</a> - Import system</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>Comments</h2>
|
||||
<p>Single-line comments start with <code>//</code>:</p>
|
||||
<pre><code>// This is a comment
|
||||
var x = 42 // Inline comment</code></pre>
|
||||
|
||||
<p>Block comments use <code>/* */</code> and can nest:</p>
|
||||
<pre><code>/* This is a
|
||||
multi-line comment */
|
||||
|
||||
/* Outer /* nested */ comment */</code></pre>
|
||||
|
||||
<h2>Variables</h2>
|
||||
<p>Declare variables with <code>var</code>:</p>
|
||||
<pre><code>var name = "Wren"
|
||||
var count = 42
|
||||
var active = true
|
||||
var nothing = null</code></pre>
|
||||
|
||||
<p>Variables must be initialized when declared. They are lexically scoped:</p>
|
||||
<pre><code>var outer = "outside"
|
||||
{
|
||||
var inner = "inside"
|
||||
System.print(outer) // Works
|
||||
}
|
||||
// inner is not accessible here</code></pre>
|
||||
|
||||
<h2>Data Types</h2>
|
||||
|
||||
<h3>Numbers</h3>
|
||||
<p>All numbers are 64-bit floating point:</p>
|
||||
<pre><code>var integer = 42
|
||||
var decimal = 3.14159
|
||||
var negative = -100
|
||||
var scientific = 1.5e10
|
||||
var hex = 0xFF
|
||||
var binary = 0b1010</code></pre>
|
||||
|
||||
<h3>Strings</h3>
|
||||
<p>Strings are immutable sequences of bytes:</p>
|
||||
<pre><code>var single = "Hello"
|
||||
var escape = "Line 1\nLine 2"
|
||||
var interpolation = "Value: %(1 + 2)"</code></pre>
|
||||
|
||||
<p>Raw strings avoid escape processing:</p>
|
||||
<pre><code>var raw = """
|
||||
This is a raw string.
|
||||
Backslashes \ are literal.
|
||||
"""</code></pre>
|
||||
|
||||
<h3>Booleans</h3>
|
||||
<pre><code>var yes = true
|
||||
var no = false</code></pre>
|
||||
|
||||
<p>Only <code>false</code> and <code>null</code> are falsy. All other values, including <code>0</code> and empty strings, are truthy.</p>
|
||||
|
||||
<h3>Null</h3>
|
||||
<pre><code>var nothing = null</code></pre>
|
||||
|
||||
<h3>Ranges</h3>
|
||||
<p>Ranges represent sequences of numbers:</p>
|
||||
<pre><code>var inclusive = 1..5 // 1, 2, 3, 4, 5
|
||||
var exclusive = 1...5 // 1, 2, 3, 4</code></pre>
|
||||
|
||||
<h3>Lists</h3>
|
||||
<p>Ordered, indexable collections:</p>
|
||||
<pre><code>var empty = []
|
||||
var numbers = [1, 2, 3, 4, 5]
|
||||
var mixed = [1, "two", true, null]
|
||||
|
||||
System.print(numbers[0]) // 1
|
||||
System.print(numbers[-1]) // 5 (last element)
|
||||
numbers[0] = 10
|
||||
numbers.add(6)</code></pre>
|
||||
|
||||
<h3>Maps</h3>
|
||||
<p>Key-value collections:</p>
|
||||
<pre><code>var empty = {}
|
||||
var person = {
|
||||
"name": "Alice",
|
||||
"age": 30
|
||||
}
|
||||
|
||||
System.print(person["name"]) // Alice
|
||||
person["city"] = "Amsterdam"</code></pre>
|
||||
|
||||
<h2>Operators</h2>
|
||||
|
||||
<h3>Arithmetic</h3>
|
||||
<pre><code>1 + 2 // 3
|
||||
5 - 3 // 2
|
||||
4 * 3 // 12
|
||||
10 / 4 // 2.5
|
||||
10 % 3 // 1 (modulo)</code></pre>
|
||||
|
||||
<h3>Comparison</h3>
|
||||
<pre><code>1 == 1 // true
|
||||
1 != 2 // true
|
||||
1 < 2 // true
|
||||
1 <= 1 // true
|
||||
2 > 1 // true
|
||||
2 >= 2 // true</code></pre>
|
||||
|
||||
<h3>Logical</h3>
|
||||
<pre><code>true && false // false
|
||||
true || false // true
|
||||
!true // false</code></pre>
|
||||
|
||||
<p>Logical operators short-circuit:</p>
|
||||
<pre><code>false && expensive() // expensive() not called
|
||||
true || expensive() // expensive() not called</code></pre>
|
||||
|
||||
<h3>Bitwise</h3>
|
||||
<pre><code>5 & 3 // 1 (AND)
|
||||
5 | 3 // 7 (OR)
|
||||
5 ^ 3 // 6 (XOR)
|
||||
~5 // -6 (NOT)
|
||||
8 << 2 // 32 (left shift)
|
||||
8 >> 2 // 2 (right shift)</code></pre>
|
||||
|
||||
<h3>Ternary</h3>
|
||||
<pre><code>var result = condition ? valueIfTrue : valueIfFalse</code></pre>
|
||||
|
||||
<h2>String Interpolation</h2>
|
||||
<p>Embed expressions in strings with <code>%()</code>:</p>
|
||||
<pre><code>var name = "World"
|
||||
System.print("Hello, %(name)!")
|
||||
|
||||
var a = 3
|
||||
var b = 4
|
||||
System.print("%(a) + %(b) = %(a + b)")</code></pre>
|
||||
|
||||
<p>Any expression can be interpolated:</p>
|
||||
<pre><code>System.print("Random: %(Random.new().float())")
|
||||
System.print("List: %([1, 2, 3].map { |x| x * 2 })")</code></pre>
|
||||
|
||||
<h2>Blocks</h2>
|
||||
<p>Blocks are anonymous functions. They use curly braces:</p>
|
||||
<pre><code>var block = { System.print("Hello") }
|
||||
block.call()
|
||||
|
||||
var add = { |a, b| a + b }
|
||||
System.print(add.call(1, 2)) // 3</code></pre>
|
||||
|
||||
<p>Blocks with a single expression return that value:</p>
|
||||
<pre><code>var square = { |x| x * x }
|
||||
System.print(square.call(5)) // 25</code></pre>
|
||||
|
||||
<h2>Functions</h2>
|
||||
<p>Use <code>Fn.new</code> for functions stored in variables:</p>
|
||||
<pre><code>var greet = Fn.new { |name|
|
||||
return "Hello, %(name)!"
|
||||
}
|
||||
System.print(greet.call("World"))</code></pre>
|
||||
|
||||
<p>Functions can have multiple statements:</p>
|
||||
<pre><code>var factorial = Fn.new { |n|
|
||||
if (n <= 1) return 1
|
||||
return n * factorial.call(n - 1)
|
||||
}</code></pre>
|
||||
|
||||
<h2>Is Operator</h2>
|
||||
<p>Check if an object is an instance of a class:</p>
|
||||
<pre><code>"hello" is String // true
|
||||
42 is Num // true
|
||||
[1, 2] is List // true</code></pre>
|
||||
|
||||
<h2>Reserved Words</h2>
|
||||
<p>The following are reserved and cannot be used as identifiers:</p>
|
||||
<pre><code>break class construct else false for foreign if import
|
||||
in is null return static super this true var while</code></pre>
|
||||
|
||||
<h2>Identifiers</h2>
|
||||
<p>Identifiers follow these conventions:</p>
|
||||
<ul>
|
||||
<li><code>camelCase</code> for variables and methods</li>
|
||||
<li><code>PascalCase</code> for class names</li>
|
||||
<li><code>_underscore</code> prefix for private fields</li>
|
||||
<li><code>UPPER_CASE</code> for constants (by convention)</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,276 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Methods" %}
|
||||
{% set breadcrumb = [{"url": "language/index.html", "title": "Language"}, {"title": "Methods"}] %}
|
||||
{% set prev_page = {"url": "language/classes.html", "title": "Classes"} %}
|
||||
{% set next_page = {"url": "language/control-flow.html", "title": "Control Flow"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Methods</h1>
|
||||
|
||||
<p>Methods are the primary way to define behavior in Wren. They can be instance methods, static methods, getters, setters, or operators.</p>
|
||||
|
||||
<h2>Instance Methods</h2>
|
||||
<p>Instance methods operate on a specific object:</p>
|
||||
<pre><code>class Greeter {
|
||||
construct new(name) {
|
||||
_name = name
|
||||
}
|
||||
|
||||
greet() {
|
||||
return "Hello, %(_name)!"
|
||||
}
|
||||
|
||||
greetWith(greeting) {
|
||||
return "%(greeting), %(_name)!"
|
||||
}
|
||||
}
|
||||
|
||||
var g = Greeter.new("World")
|
||||
System.print(g.greet()) // Hello, World!
|
||||
System.print(g.greetWith("Hi")) // Hi, World!</code></pre>
|
||||
|
||||
<h2>Static Methods</h2>
|
||||
<p>Static methods belong to the class rather than instances:</p>
|
||||
<pre><code>class StringUtils {
|
||||
static reverse(s) {
|
||||
var result = ""
|
||||
for (i in (s.count - 1)..0) {
|
||||
result = result + s[i]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
static capitalize(s) {
|
||||
if (s.count == 0) return s
|
||||
return s[0].toString.toUpperCase + s[1..-1]
|
||||
}
|
||||
}
|
||||
|
||||
System.print(StringUtils.reverse("hello")) // olleh
|
||||
System.print(StringUtils.capitalize("hello")) // Hello</code></pre>
|
||||
|
||||
<h2>Getters</h2>
|
||||
<p>Getters are methods without parentheses that act like properties:</p>
|
||||
<pre><code>class Temperature {
|
||||
construct celsius(c) {
|
||||
_celsius = c
|
||||
}
|
||||
|
||||
celsius { _celsius }
|
||||
fahrenheit { _celsius * 9 / 5 + 32 }
|
||||
kelvin { _celsius + 273.15 }
|
||||
}
|
||||
|
||||
var temp = Temperature.celsius(100)
|
||||
System.print(temp.celsius) // 100
|
||||
System.print(temp.fahrenheit) // 212
|
||||
System.print(temp.kelvin) // 373.15</code></pre>
|
||||
|
||||
<h2>Setters</h2>
|
||||
<p>Setters use the <code>=</code> suffix:</p>
|
||||
<pre><code>class Box {
|
||||
construct new(value) {
|
||||
_value = value
|
||||
}
|
||||
|
||||
value { _value }
|
||||
|
||||
value=(v) {
|
||||
if (v < 0) Fiber.abort("Value must be non-negative")
|
||||
_value = v
|
||||
}
|
||||
}
|
||||
|
||||
var box = Box.new(10)
|
||||
box.value = 20
|
||||
System.print(box.value) // 20</code></pre>
|
||||
|
||||
<h2>Method Signatures</h2>
|
||||
<p>Wren distinguishes methods by their signature (name + arity):</p>
|
||||
<pre><code>class Example {
|
||||
method { "no args" }
|
||||
method() { "zero args with parens" }
|
||||
method(a) { "one arg" }
|
||||
method(a, b) { "two args" }
|
||||
}
|
||||
|
||||
var e = Example.new()
|
||||
System.print(e.method) // no args
|
||||
System.print(e.method()) // zero args with parens
|
||||
System.print(e.method(1)) // one arg
|
||||
System.print(e.method(1, 2)) // two args</code></pre>
|
||||
|
||||
<h2>Block Arguments</h2>
|
||||
<p>Methods can take a block as the last argument:</p>
|
||||
<pre><code>class List {
|
||||
static each(list, fn) {
|
||||
for (item in list) {
|
||||
fn.call(item)
|
||||
}
|
||||
}
|
||||
|
||||
static map(list, fn) {
|
||||
var result = []
|
||||
for (item in list) {
|
||||
result.add(fn.call(item))
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
var numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
List.each(numbers) { |n|
|
||||
System.print(n)
|
||||
}
|
||||
|
||||
var doubled = List.map(numbers) { |n| n * 2 }
|
||||
System.print(doubled) // [2, 4, 6, 8, 10]</code></pre>
|
||||
|
||||
<h2>Operator Overloading</h2>
|
||||
<p>Classes can define custom behavior for operators:</p>
|
||||
|
||||
<h3>Binary Operators</h3>
|
||||
<pre><code>class Vector {
|
||||
construct new(x, y) {
|
||||
_x = x
|
||||
_y = y
|
||||
}
|
||||
|
||||
x { _x }
|
||||
y { _y }
|
||||
|
||||
+(other) { Vector.new(_x + other.x, _y + other.y) }
|
||||
-(other) { Vector.new(_x - other.x, _y - other.y) }
|
||||
*(scalar) { Vector.new(_x * scalar, _y * scalar) }
|
||||
/(scalar) { Vector.new(_x / scalar, _y / scalar) }
|
||||
|
||||
==(other) {
|
||||
return _x == other.x && _y == other.y
|
||||
}
|
||||
|
||||
toString { "(%(_x), %(_y))" }
|
||||
}
|
||||
|
||||
var a = Vector.new(1, 2)
|
||||
var b = Vector.new(3, 4)
|
||||
|
||||
System.print((a + b).toString) // (4, 6)
|
||||
System.print((a * 2).toString) // (2, 4)
|
||||
System.print(a == b) // false</code></pre>
|
||||
|
||||
<h3>Available Operators</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Operator</th>
|
||||
<th>Signature</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr><td><code>+</code></td><td><code>+(other)</code></td><td>Addition</td></tr>
|
||||
<tr><td><code>-</code></td><td><code>-(other)</code></td><td>Subtraction</td></tr>
|
||||
<tr><td><code>*</code></td><td><code>*(other)</code></td><td>Multiplication</td></tr>
|
||||
<tr><td><code>/</code></td><td><code>/(other)</code></td><td>Division</td></tr>
|
||||
<tr><td><code>%</code></td><td><code>%(other)</code></td><td>Modulo</td></tr>
|
||||
<tr><td><code><</code></td><td><code><(other)</code></td><td>Less than</td></tr>
|
||||
<tr><td><code>></code></td><td><code>>(other)</code></td><td>Greater than</td></tr>
|
||||
<tr><td><code><=</code></td><td><code><=(other)</code></td><td>Less or equal</td></tr>
|
||||
<tr><td><code>>=</code></td><td><code>>=(other)</code></td><td>Greater or equal</td></tr>
|
||||
<tr><td><code>==</code></td><td><code>==(other)</code></td><td>Equality</td></tr>
|
||||
<tr><td><code>!=</code></td><td><code>!=(other)</code></td><td>Inequality</td></tr>
|
||||
<tr><td><code>&</code></td><td><code>&(other)</code></td><td>Bitwise AND</td></tr>
|
||||
<tr><td><code>|</code></td><td><code>|(other)</code></td><td>Bitwise OR</td></tr>
|
||||
<tr><td><code>^</code></td><td><code>^(other)</code></td><td>Bitwise XOR</td></tr>
|
||||
<tr><td><code><<</code></td><td><code><<(other)</code></td><td>Left shift</td></tr>
|
||||
<tr><td><code>>></code></td><td><code>>>(other)</code></td><td>Right shift</td></tr>
|
||||
<tr><td><code>..</code></td><td><code>..(other)</code></td><td>Inclusive range</td></tr>
|
||||
<tr><td><code>...</code></td><td><code>...(other)</code></td><td>Exclusive range</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>Unary Operators</h3>
|
||||
<pre><code>class Vector {
|
||||
construct new(x, y) {
|
||||
_x = x
|
||||
_y = y
|
||||
}
|
||||
|
||||
- { Vector.new(-_x, -_y) }
|
||||
! { Vector.new(_y, _x) } // Perpendicular
|
||||
|
||||
toString { "(%(_x), %(_y))" }
|
||||
}
|
||||
|
||||
var v = Vector.new(3, 4)
|
||||
System.print((-v).toString) // (-3, -4)</code></pre>
|
||||
|
||||
<h3>Subscript Operators</h3>
|
||||
<pre><code>class Grid {
|
||||
construct new(width, height) {
|
||||
_width = width
|
||||
_height = height
|
||||
_cells = List.filled(width * height, 0)
|
||||
}
|
||||
|
||||
[x, y] { _cells[y * _width + x] }
|
||||
[x, y]=(value) { _cells[y * _width + x] = value }
|
||||
}
|
||||
|
||||
var grid = Grid.new(10, 10)
|
||||
grid[5, 3] = 42
|
||||
System.print(grid[5, 3]) // 42</code></pre>
|
||||
|
||||
<h2>Calling Methods</h2>
|
||||
|
||||
<h3>With Parentheses</h3>
|
||||
<pre><code>object.method()
|
||||
object.method(arg1)
|
||||
object.method(arg1, arg2)</code></pre>
|
||||
|
||||
<h3>Without Parentheses (Getters)</h3>
|
||||
<pre><code>object.property
|
||||
object.count
|
||||
string.bytes</code></pre>
|
||||
|
||||
<h3>With Block Argument</h3>
|
||||
<pre><code>list.map { |x| x * 2 }
|
||||
list.where { |x| x > 5 }
|
||||
list.each { |x| System.print(x) }</code></pre>
|
||||
|
||||
<h3>Chaining</h3>
|
||||
<pre><code>var result = list
|
||||
.where { |x| x > 0 }
|
||||
.map { |x| x * 2 }
|
||||
.toList</code></pre>
|
||||
|
||||
<h2>Return Values</h2>
|
||||
<p>Methods return the last expression or use <code>return</code>:</p>
|
||||
<pre><code>class Example {
|
||||
implicit() {
|
||||
42 // Implicit return
|
||||
}
|
||||
|
||||
explicit() {
|
||||
return 42 // Explicit return
|
||||
}
|
||||
|
||||
early(x) {
|
||||
if (x < 0) return -1
|
||||
if (x > 0) return 1
|
||||
return 0
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<p>Methods without a return statement return <code>null</code>.</p>
|
||||
|
||||
<h2>Method References</h2>
|
||||
<p>You cannot directly reference a method as a value. Use a block wrapper:</p>
|
||||
<pre><code>class Printer {
|
||||
static print(value) {
|
||||
System.print(value)
|
||||
}
|
||||
}
|
||||
|
||||
var fn = Fn.new { |x| Printer.print(x) }
|
||||
fn.call("Hello") // Hello</code></pre>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,302 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Modules" %}
|
||||
{% set breadcrumb = [{"url": "language/index.html", "title": "Language"}, {"title": "Modules"}] %}
|
||||
{% set prev_page = {"url": "language/fibers.html", "title": "Fibers"} %}
|
||||
{% set next_page = {"url": "api/index.html", "title": "API Reference"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Modules</h1>
|
||||
|
||||
<p>Modules organize code into separate, reusable files. Wren-CLI provides built-in modules and supports user-defined modules.</p>
|
||||
|
||||
<h2>Importing</h2>
|
||||
<p>Use <code>import</code> to load a module and access its classes:</p>
|
||||
<pre><code>import "json" for Json
|
||||
|
||||
var data = Json.parse('{"name": "Wren"}')
|
||||
System.print(data["name"])</code></pre>
|
||||
|
||||
<h3>Multiple Imports</h3>
|
||||
<p>Import multiple classes from one module:</p>
|
||||
<pre><code>import "io" for File, Directory, Stdin</code></pre>
|
||||
|
||||
<h3>Import All</h3>
|
||||
<p>Some modules export many classes. Import what you need:</p>
|
||||
<pre><code>import "os" for Process, Platform</code></pre>
|
||||
|
||||
<h2>Built-in Modules</h2>
|
||||
<p>Wren-CLI provides these modules:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Module</th>
|
||||
<th>Description</th>
|
||||
<th>Main Classes</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/http.html">http</a></td>
|
||||
<td>HTTP client</td>
|
||||
<td>Http, HttpResponse, Url</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/websocket.html">websocket</a></td>
|
||||
<td>WebSocket client/server</td>
|
||||
<td>WebSocket, WebSocketServer</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/tls.html">tls</a></td>
|
||||
<td>TLS/SSL sockets</td>
|
||||
<td>TlsSocket</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/net.html">net</a></td>
|
||||
<td>TCP networking</td>
|
||||
<td>Socket, Server</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/dns.html">dns</a></td>
|
||||
<td>DNS resolution</td>
|
||||
<td>Dns</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/json.html">json</a></td>
|
||||
<td>JSON parsing</td>
|
||||
<td>Json</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/base64.html">base64</a></td>
|
||||
<td>Base64 encoding</td>
|
||||
<td>Base64</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/regex.html">regex</a></td>
|
||||
<td>Regular expressions</td>
|
||||
<td>Regex, Match</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/jinja.html">jinja</a></td>
|
||||
<td>Template engine</td>
|
||||
<td>Environment, Template</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/crypto.html">crypto</a></td>
|
||||
<td>Cryptography</td>
|
||||
<td>Hash</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/os.html">os</a></td>
|
||||
<td>OS information</td>
|
||||
<td>Process, Platform</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/env.html">env</a></td>
|
||||
<td>Environment variables</td>
|
||||
<td>Env</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/signal.html">signal</a></td>
|
||||
<td>Unix signals</td>
|
||||
<td>Signal</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/subprocess.html">subprocess</a></td>
|
||||
<td>Run processes</td>
|
||||
<td>Subprocess</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/sqlite.html">sqlite</a></td>
|
||||
<td>SQLite database</td>
|
||||
<td>Sqlite</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/datetime.html">datetime</a></td>
|
||||
<td>Date/time handling</td>
|
||||
<td>DateTime, Duration</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/timer.html">timer</a></td>
|
||||
<td>Timers and delays</td>
|
||||
<td>Timer</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/io.html">io</a></td>
|
||||
<td>File I/O</td>
|
||||
<td>File, Directory, Stdin</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/pathlib.html">pathlib</a></td>
|
||||
<td>Filesystem paths</td>
|
||||
<td>Path, PurePath</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/scheduler.html">scheduler</a></td>
|
||||
<td>Async scheduling</td>
|
||||
<td>Scheduler</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="../api/math.html">math</a></td>
|
||||
<td>Math functions</td>
|
||||
<td>Math</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>User Modules</h2>
|
||||
<p>Create your own modules by putting code in <code>.wren</code> files.</p>
|
||||
|
||||
<h3>Creating a Module</h3>
|
||||
<p>Create <code>utils.wren</code>:</p>
|
||||
<pre><code>class StringUtils {
|
||||
static reverse(s) {
|
||||
var result = ""
|
||||
for (i in (s.count - 1)..0) {
|
||||
result = result + s[i]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
static capitalize(s) {
|
||||
if (s.count == 0) return s
|
||||
return s[0].toString.toUpperCase + s[1..-1]
|
||||
}
|
||||
}
|
||||
|
||||
class MathUtils {
|
||||
static clamp(value, min, max) {
|
||||
if (value < min) return min
|
||||
if (value > max) return max
|
||||
return value
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h3>Using a Module</h3>
|
||||
<p>Import with a relative path:</p>
|
||||
<pre><code>import "./utils" for StringUtils, MathUtils
|
||||
|
||||
System.print(StringUtils.reverse("hello")) // olleh
|
||||
System.print(StringUtils.capitalize("world")) // World
|
||||
System.print(MathUtils.clamp(15, 0, 10)) // 10</code></pre>
|
||||
|
||||
<h2>Module Resolution</h2>
|
||||
|
||||
<h3>Built-in Modules</h3>
|
||||
<p>Names without paths are built-in modules:</p>
|
||||
<pre><code>import "json" for Json // Built-in
|
||||
import "http" for Http // Built-in</code></pre>
|
||||
|
||||
<h3>Relative Paths</h3>
|
||||
<p>Paths starting with <code>./</code> or <code>../</code> are relative to the current file:</p>
|
||||
<pre><code>import "./helpers" for Helper // Same directory
|
||||
import "../utils/string" for StringUtil // Parent directory</code></pre>
|
||||
|
||||
<h3>Absolute Paths</h3>
|
||||
<p>Paths starting with <code>/</code> are absolute:</p>
|
||||
<pre><code>import "/home/user/libs/mylib" for MyClass</code></pre>
|
||||
|
||||
<h2>Module Structure</h2>
|
||||
<p>A typical project structure:</p>
|
||||
<pre><code>project/
|
||||
├── main.wren
|
||||
├── lib/
|
||||
│ ├── http_client.wren
|
||||
│ ├── database.wren
|
||||
│ └── templates.wren
|
||||
└── tests/
|
||||
└── test_http.wren</code></pre>
|
||||
|
||||
<p>In <code>main.wren</code>:</p>
|
||||
<pre><code>import "./lib/http_client" for HttpClient
|
||||
import "./lib/database" for Database
|
||||
import "./lib/templates" for TemplateEngine
|
||||
|
||||
var client = HttpClient.new()
|
||||
var db = Database.new("data.db")
|
||||
var tmpl = TemplateEngine.new()</code></pre>
|
||||
|
||||
<h2>Module Top-Level Code</h2>
|
||||
<p>Code outside classes runs when the module is first imported:</p>
|
||||
<pre><code>// config.wren
|
||||
System.print("Config module loading...")
|
||||
|
||||
class Config {
|
||||
static port { 8080 }
|
||||
static host { "localhost" }
|
||||
}
|
||||
|
||||
System.print("Config ready")</code></pre>
|
||||
|
||||
<pre><code>// main.wren
|
||||
System.print("Before import")
|
||||
import "./config" for Config
|
||||
System.print("After import")
|
||||
System.print("Port: %(Config.port)")
|
||||
|
||||
// Output:
|
||||
// Before import
|
||||
// Config module loading...
|
||||
// Config ready
|
||||
// After import
|
||||
// Port: 8080</code></pre>
|
||||
|
||||
<h2>Module Variables</h2>
|
||||
<p>Top-level variables are module-private by default:</p>
|
||||
<pre><code>// counter.wren
|
||||
var _count = 0 // Private to module
|
||||
|
||||
class Counter {
|
||||
static increment() { _count = _count + 1 }
|
||||
static count { _count }
|
||||
}</code></pre>
|
||||
|
||||
<pre><code>// main.wren
|
||||
import "./counter" for Counter
|
||||
|
||||
Counter.increment()
|
||||
Counter.increment()
|
||||
System.print(Counter.count) // 2
|
||||
// _count is not accessible here</code></pre>
|
||||
|
||||
<h2>Circular Imports</h2>
|
||||
<p>Wren handles circular imports by completing partial modules:</p>
|
||||
<pre><code>// a.wren
|
||||
import "./b" for B
|
||||
|
||||
class A {
|
||||
static greet() { "Hello from A" }
|
||||
static callB() { B.greet() }
|
||||
}
|
||||
|
||||
// b.wren
|
||||
import "./a" for A
|
||||
|
||||
class B {
|
||||
static greet() { "Hello from B" }
|
||||
static callA() { A.greet() }
|
||||
}</code></pre>
|
||||
|
||||
<p>This works because class definitions are hoisted.</p>
|
||||
|
||||
<div class="admonition warning">
|
||||
<div class="admonition-title">Warning</div>
|
||||
<p>Avoid calling imported classes in top-level code during circular imports, as they may not be fully initialized.</p>
|
||||
</div>
|
||||
|
||||
<h2>Re-exporting</h2>
|
||||
<p>Create a facade module that re-exports from multiple modules:</p>
|
||||
<pre><code>// lib/index.wren
|
||||
import "./http_client" for HttpClient
|
||||
import "./database" for Database
|
||||
import "./templates" for TemplateEngine
|
||||
|
||||
class Lib {
|
||||
static httpClient { HttpClient }
|
||||
static database { Database }
|
||||
static templates { TemplateEngine }
|
||||
}</code></pre>
|
||||
|
||||
<pre><code>// main.wren
|
||||
import "./lib/index" for Lib
|
||||
|
||||
var client = Lib.httpClient.new()</code></pre>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,85 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Try Wren" %}
|
||||
{% set breadcrumb = [{"title": "Playground"}] %}
|
||||
{% set prev_page = {"url": "getting-started/repl.html", "title": "Using the REPL"} %}
|
||||
{% set next_page = {"url": "language/index.html", "title": "Syntax Overview"} %}
|
||||
|
||||
{% block extra_head %}
|
||||
<link rel="stylesheet" href="{{ static_prefix }}css/playground.css">
|
||||
<script src="{{ static_prefix }}wasm/wren.js"></script>
|
||||
{% endblock %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Try Wren</h1>
|
||||
|
||||
<p>Write and run Wren code directly in your browser. This playground uses WebAssembly to run a subset of Wren-CLI modules.</p>
|
||||
|
||||
<div class="playground-container">
|
||||
<div class="playground-toolbar">
|
||||
<button id="run-button" class="primary" disabled>Run</button>
|
||||
<button id="clear-button">Clear Output</button>
|
||||
<select id="example-select">
|
||||
<option value="">Load Example...</option>
|
||||
<option value="hello">Hello World</option>
|
||||
<option value="fibonacci">Fibonacci</option>
|
||||
<option value="classes">Classes</option>
|
||||
<option value="math">Math Module</option>
|
||||
<option value="json">JSON</option>
|
||||
<option value="datetime">DateTime</option>
|
||||
<option value="base64">Base64</option>
|
||||
<option value="strutil">String Utils</option>
|
||||
<option value="faker">Faker Data</option>
|
||||
<option value="lists">Lists and Iteration</option>
|
||||
</select>
|
||||
<span id="wasm-status" class="wasm-status loading">Loading...</span>
|
||||
</div>
|
||||
|
||||
<div class="playground-editor-wrapper">
|
||||
<textarea id="wren-editor" spellcheck="false" placeholder="Enter Wren code here...">System.print("Hello, World!")</textarea>
|
||||
</div>
|
||||
|
||||
<div class="output-panel">
|
||||
<div class="output-header">Output</div>
|
||||
<pre id="wren-output"></pre>
|
||||
</div>
|
||||
|
||||
<div class="playground-help">
|
||||
<kbd>Ctrl</kbd> + <kbd>Enter</kbd> to run • <kbd>Tab</kbd> inserts spaces
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Available Modules</h2>
|
||||
<p>The following modules are available in this browser-based playground:</p>
|
||||
|
||||
<div class="modules-list">
|
||||
<span class="module-badge">math</span>
|
||||
<span class="module-badge">json</span>
|
||||
<span class="module-badge">base64</span>
|
||||
<span class="module-badge">bytes</span>
|
||||
<span class="module-badge">datetime</span>
|
||||
<span class="module-badge">strutil</span>
|
||||
<span class="module-badge">html</span>
|
||||
<span class="module-badge">markdown</span>
|
||||
<span class="module-badge">argparse</span>
|
||||
<span class="module-badge">wdantic</span>
|
||||
<span class="module-badge">uuid</span>
|
||||
<span class="module-badge">faker</span>
|
||||
</div>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Some modules require system access and are not available in the browser, including: <code>io</code>, <code>net</code>, <code>http</code>, <code>tls</code>, <code>sqlite</code>, <code>subprocess</code>, <code>os</code>, and <code>scheduler</code>.</p>
|
||||
</div>
|
||||
|
||||
<h2>Learn More</h2>
|
||||
<p>This playground is a quick way to experiment. For full functionality, install Wren-CLI locally:</p>
|
||||
<ul>
|
||||
<li><a href="getting-started/installation.html">Installation Guide</a></li>
|
||||
<li><a href="language/index.html">Language Reference</a></li>
|
||||
<li><a href="api/index.html">API Reference</a></li>
|
||||
</ul>
|
||||
|
||||
<script src="{{ static_prefix }}js/playground.js"></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,645 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Building a CLI Tool" %}
|
||||
{% set breadcrumb = [{"url": "tutorials/index.html", "title": "Tutorials"}, {"title": "CLI Tool"}] %}
|
||||
{% set prev_page = {"url": "tutorials/template-rendering.html", "title": "Template Rendering"} %}
|
||||
{% set next_page = {"url": "tutorials/pexpect.html", "title": "Process Automation"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Building a CLI Tool</h1>
|
||||
|
||||
<p>In this tutorial, you will build a complete command-line application. You will learn to parse arguments, handle user input, run subprocesses, and create a professional CLI experience.</p>
|
||||
|
||||
<h2>What You Will Learn</h2>
|
||||
|
||||
<ul>
|
||||
<li>Parsing command-line arguments</li>
|
||||
<li>Handling user input interactively</li>
|
||||
<li>Running external commands</li>
|
||||
<li>Working with environment variables</li>
|
||||
<li>Signal handling for graceful shutdown</li>
|
||||
<li>Creating subcommands</li>
|
||||
</ul>
|
||||
|
||||
<h2>Step 1: Accessing Command-Line Arguments</h2>
|
||||
|
||||
<p>Create a file called <code>cli_tool.wren</code>:</p>
|
||||
|
||||
<pre><code>import "os" for Process
|
||||
|
||||
var args = Process.arguments
|
||||
|
||||
System.print("Script: %(Process.arguments[0])")
|
||||
System.print("Arguments: %(args.count - 1)")
|
||||
|
||||
for (i in 1...args.count) {
|
||||
System.print(" arg[%(i)]: %(args[i])")
|
||||
}</code></pre>
|
||||
|
||||
<p>Run it:</p>
|
||||
<pre><code>$ wren_cli cli_tool.wren hello world --verbose
|
||||
Script: cli_tool.wren
|
||||
Arguments: 3
|
||||
arg[1]: hello
|
||||
arg[2]: world
|
||||
arg[3]: --verbose</code></pre>
|
||||
|
||||
<h2>Step 2: Building an Argument Parser</h2>
|
||||
|
||||
<pre><code>import "os" for Process
|
||||
|
||||
class ArgParser {
|
||||
construct new() {
|
||||
_commands = {}
|
||||
_options = {}
|
||||
_flags = {}
|
||||
_positional = []
|
||||
}
|
||||
|
||||
parse(args) {
|
||||
var i = 1
|
||||
while (i < args.count) {
|
||||
var arg = args[i]
|
||||
|
||||
if (arg.startsWith("--")) {
|
||||
var key = arg[2..-1]
|
||||
if (key.contains("=")) {
|
||||
var parts = key.split("=")
|
||||
_options[parts[0]] = parts[1]
|
||||
} else if (i + 1 < args.count && !args[i + 1].startsWith("-")) {
|
||||
_options[key] = args[i + 1]
|
||||
i = i + 1
|
||||
} else {
|
||||
_flags[key] = true
|
||||
}
|
||||
} else if (arg.startsWith("-")) {
|
||||
for (char in arg[1..-1]) {
|
||||
_flags[char] = true
|
||||
}
|
||||
} else {
|
||||
_positional.add(arg)
|
||||
}
|
||||
i = i + 1
|
||||
}
|
||||
}
|
||||
|
||||
option(name) { _options[name] }
|
||||
flag(name) { _flags.containsKey(name) && _flags[name] }
|
||||
positional { _positional }
|
||||
hasOption(name) { _options.containsKey(name) }
|
||||
}
|
||||
|
||||
var parser = ArgParser.new()
|
||||
parser.parse(Process.arguments)
|
||||
|
||||
System.print("Positional: %(parser.positional)")
|
||||
System.print("Verbose: %(parser.flag("verbose") || parser.flag("v"))")
|
||||
System.print("Output: %(parser.option("output") || "stdout")")</code></pre>
|
||||
|
||||
<p>Run it:</p>
|
||||
<pre><code>$ wren_cli cli_tool.wren file1.txt file2.txt -v --output=result.txt
|
||||
Positional: [file1.txt, file2.txt]
|
||||
Verbose: true
|
||||
Output: result.txt</code></pre>
|
||||
|
||||
<h2>Step 3: Creating Subcommands</h2>
|
||||
|
||||
<pre><code>import "os" for Process
|
||||
import "io" for File, Directory, Stdin
|
||||
|
||||
class CLI {
|
||||
construct new(name, version) {
|
||||
_name = name
|
||||
_version = version
|
||||
_commands = {}
|
||||
}
|
||||
|
||||
command(name, description, handler) {
|
||||
_commands[name] = {"description": description, "handler": handler}
|
||||
}
|
||||
|
||||
run(args) {
|
||||
if (args.count < 2) {
|
||||
showHelp()
|
||||
return
|
||||
}
|
||||
|
||||
var cmd = args[1]
|
||||
|
||||
if (cmd == "--help" || cmd == "-h") {
|
||||
showHelp()
|
||||
} else if (cmd == "--version" || cmd == "-V") {
|
||||
System.print("%(_name) %(_version)")
|
||||
} else if (_commands.containsKey(cmd)) {
|
||||
_commands[cmd]["handler"].call(args[2..-1])
|
||||
} else {
|
||||
System.print("Unknown command: %(cmd)")
|
||||
System.print("Run '%(_name) --help' for usage.")
|
||||
}
|
||||
}
|
||||
|
||||
showHelp() {
|
||||
System.print("%(_name) %(_version)")
|
||||
System.print("")
|
||||
System.print("Usage: %(_name) <command> [options]")
|
||||
System.print("")
|
||||
System.print("Commands:")
|
||||
for (name in _commands.keys) {
|
||||
var desc = _commands[name]["description"]
|
||||
System.print(" %(name.padRight(15)) %(desc)")
|
||||
}
|
||||
System.print("")
|
||||
System.print("Options:")
|
||||
System.print(" --help, -h Show this help")
|
||||
System.print(" --version, -V Show version")
|
||||
}
|
||||
}
|
||||
|
||||
var cli = CLI.new("mytool", "1.0.0")
|
||||
|
||||
cli.command("list", "List files in directory", Fn.new { |args|
|
||||
var path = args.count > 0 ? args[0] : "."
|
||||
var files = Directory.list(path)
|
||||
for (file in files) {
|
||||
System.print(file)
|
||||
}
|
||||
})
|
||||
|
||||
cli.command("read", "Read and display a file", Fn.new { |args|
|
||||
if (args.count == 0) {
|
||||
System.print("Usage: mytool read <file>")
|
||||
return
|
||||
}
|
||||
System.print(File.read(args[0]))
|
||||
})
|
||||
|
||||
cli.command("info", "Show file information", Fn.new { |args|
|
||||
if (args.count == 0) {
|
||||
System.print("Usage: mytool info <file>")
|
||||
return
|
||||
}
|
||||
var path = args[0]
|
||||
if (File.exists(path)) {
|
||||
System.print("File: %(path)")
|
||||
System.print("Size: %(File.size(path)) bytes")
|
||||
} else {
|
||||
System.print("File not found: %(path)")
|
||||
}
|
||||
})
|
||||
|
||||
cli.run(Process.arguments)</code></pre>
|
||||
|
||||
<h2>Step 4: Interactive Input</h2>
|
||||
|
||||
<pre><code>import "io" for Stdin
|
||||
|
||||
class Prompt {
|
||||
static ask(question) {
|
||||
System.write("%(question) ")
|
||||
return Stdin.readLine()
|
||||
}
|
||||
|
||||
static confirm(question) {
|
||||
System.write("%(question) (y/n) ")
|
||||
var answer = Stdin.readLine().lower
|
||||
return answer == "y" || answer == "yes"
|
||||
}
|
||||
|
||||
static choose(question, options) {
|
||||
System.print(question)
|
||||
var i = 1
|
||||
for (opt in options) {
|
||||
System.print(" %(i). %(opt)")
|
||||
i = i + 1
|
||||
}
|
||||
System.write("Choice: ")
|
||||
var choice = Num.fromString(Stdin.readLine())
|
||||
if (choice && choice >= 1 && choice <= options.count) {
|
||||
return options[choice - 1]
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
static password(question) {
|
||||
System.write("%(question) ")
|
||||
return Stdin.readLine()
|
||||
}
|
||||
}
|
||||
|
||||
var name = Prompt.ask("What is your name?")
|
||||
System.print("Hello, %(name)!")
|
||||
|
||||
if (Prompt.confirm("Do you want to continue?")) {
|
||||
var color = Prompt.choose("Pick a color:", ["Red", "Green", "Blue"])
|
||||
System.print("You chose: %(color)")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Step 5: Running External Commands</h2>
|
||||
|
||||
<pre><code>import "subprocess" for Subprocess
|
||||
import "os" for Process
|
||||
|
||||
class Shell {
|
||||
static run(command) {
|
||||
var result = Subprocess.exec(command)
|
||||
return {
|
||||
"output": result.stdout,
|
||||
"error": result.stderr,
|
||||
"code": result.exitCode
|
||||
}
|
||||
}
|
||||
|
||||
static runOrFail(command) {
|
||||
var result = run(command)
|
||||
if (result["code"] != 0) {
|
||||
Fiber.abort("Command failed: %(command)\n%(result["error"])")
|
||||
}
|
||||
return result["output"]
|
||||
}
|
||||
|
||||
static which(program) {
|
||||
var result = run("which %(program)")
|
||||
return result["code"] == 0 ? result["output"].trim() : null
|
||||
}
|
||||
}
|
||||
|
||||
System.print("Git status:")
|
||||
var result = Shell.run("git status --porcelain")
|
||||
if (result["code"] == 0) {
|
||||
if (result["output"].count == 0) {
|
||||
System.print(" Working directory clean")
|
||||
} else {
|
||||
System.print(result["output"])
|
||||
}
|
||||
} else {
|
||||
System.print(" Not a git repository")
|
||||
}
|
||||
|
||||
var gitPath = Shell.which("git")
|
||||
if (gitPath) {
|
||||
System.print("Git found at: %(gitPath)")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Step 6: Environment Variables</h2>
|
||||
|
||||
<pre><code>import "env" for Env
|
||||
import "os" for Process
|
||||
|
||||
class Config {
|
||||
static get(key, defaultValue) {
|
||||
return Env.get(key) || defaultValue
|
||||
}
|
||||
|
||||
static require(key) {
|
||||
var value = Env.get(key)
|
||||
if (!value) {
|
||||
Fiber.abort("Required environment variable not set: %(key)")
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
var home = Config.get("HOME", "/tmp")
|
||||
var editor = Config.get("EDITOR", "vim")
|
||||
var debug = Config.get("DEBUG", "false") == "true"
|
||||
|
||||
System.print("Home: %(home)")
|
||||
System.print("Editor: %(editor)")
|
||||
System.print("Debug mode: %(debug)")
|
||||
|
||||
System.print("\nAll environment variables:")
|
||||
for (key in Env.keys()) {
|
||||
System.print(" %(key)=%(Env.get(key))")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Step 7: Signal Handling</h2>
|
||||
|
||||
<pre><code>import "signal" for Signal
|
||||
import "timer" for Timer
|
||||
|
||||
var running = true
|
||||
|
||||
Signal.handle("SIGINT", Fn.new {
|
||||
System.print("\nReceived SIGINT, shutting down...")
|
||||
running = false
|
||||
})
|
||||
|
||||
Signal.handle("SIGTERM", Fn.new {
|
||||
System.print("\nReceived SIGTERM, shutting down...")
|
||||
running = false
|
||||
})
|
||||
|
||||
System.print("Running... Press Ctrl+C to stop")
|
||||
|
||||
var counter = 0
|
||||
while (running) {
|
||||
counter = counter + 1
|
||||
System.write("\rProcessed %(counter) items...")
|
||||
Timer.sleep(100)
|
||||
}
|
||||
|
||||
System.print("\nGraceful shutdown complete. Processed %(counter) items.")</code></pre>
|
||||
|
||||
<h2>Step 8: Complete CLI Application</h2>
|
||||
|
||||
<p>Let's build a complete file utility tool:</p>
|
||||
|
||||
<pre><code>import "os" for Process
|
||||
import "io" for File, Directory, Stdin
|
||||
import "json" for Json
|
||||
import "crypto" for Crypto
|
||||
import "subprocess" for Subprocess
|
||||
import "signal" for Signal
|
||||
import "env" for Env
|
||||
|
||||
class FileUtil {
|
||||
construct new() {
|
||||
_verbose = false
|
||||
}
|
||||
|
||||
verbose=(value) { _verbose = value }
|
||||
|
||||
log(message) {
|
||||
if (_verbose) System.print("[INFO] %(message)")
|
||||
}
|
||||
|
||||
list(path, recursive) {
|
||||
var files = Directory.list(path)
|
||||
var results = []
|
||||
|
||||
for (file in files) {
|
||||
var fullPath = "%(path)/%(file)"
|
||||
results.add(fullPath)
|
||||
|
||||
if (recursive && Directory.exists(fullPath)) {
|
||||
var subFiles = list(fullPath, true)
|
||||
for (sub in subFiles) {
|
||||
results.add(sub)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
copy(source, dest) {
|
||||
log("Copying %(source) to %(dest)")
|
||||
File.copy(source, dest)
|
||||
}
|
||||
|
||||
hash(path, algorithm) {
|
||||
var content = File.read(path)
|
||||
if (algorithm == "md5") {
|
||||
return Crypto.md5(content)
|
||||
} else if (algorithm == "sha256") {
|
||||
return Crypto.sha256(content)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
search(path, pattern) {
|
||||
var files = list(path, true)
|
||||
var matches = []
|
||||
|
||||
for (file in files) {
|
||||
if (file.contains(pattern)) {
|
||||
matches.add(file)
|
||||
}
|
||||
}
|
||||
|
||||
return matches
|
||||
}
|
||||
|
||||
stats(path) {
|
||||
var files = list(path, true)
|
||||
var totalSize = 0
|
||||
var fileCount = 0
|
||||
var dirCount = 0
|
||||
|
||||
for (file in files) {
|
||||
if (Directory.exists(file)) {
|
||||
dirCount = dirCount + 1
|
||||
} else if (File.exists(file)) {
|
||||
fileCount = fileCount + 1
|
||||
totalSize = totalSize + File.size(file)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"files": fileCount,
|
||||
"directories": dirCount,
|
||||
"totalSize": totalSize
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class CLI {
|
||||
construct new() {
|
||||
_name = "fileutil"
|
||||
_version = "1.0.0"
|
||||
_util = FileUtil.new()
|
||||
}
|
||||
|
||||
run(args) {
|
||||
if (args.count < 2) {
|
||||
showHelp()
|
||||
return
|
||||
}
|
||||
|
||||
var verbose = args.contains("-v") || args.contains("--verbose")
|
||||
_util.verbose = verbose
|
||||
|
||||
var cmd = args[1]
|
||||
|
||||
if (cmd == "list" || cmd == "ls") {
|
||||
cmdList(args)
|
||||
} else if (cmd == "copy" || cmd == "cp") {
|
||||
cmdCopy(args)
|
||||
} else if (cmd == "hash") {
|
||||
cmdHash(args)
|
||||
} else if (cmd == "search" || cmd == "find") {
|
||||
cmdSearch(args)
|
||||
} else if (cmd == "stats") {
|
||||
cmdStats(args)
|
||||
} else if (cmd == "--help" || cmd == "-h") {
|
||||
showHelp()
|
||||
} else if (cmd == "--version" || cmd == "-V") {
|
||||
System.print("%(_name) %(_version)")
|
||||
} else {
|
||||
System.print("Unknown command: %(cmd)")
|
||||
System.print("Run '%(_name) --help' for usage.")
|
||||
}
|
||||
}
|
||||
|
||||
cmdList(args) {
|
||||
var path = "."
|
||||
var recursive = args.contains("-r") || args.contains("--recursive")
|
||||
|
||||
for (arg in args[2..-1]) {
|
||||
if (!arg.startsWith("-")) {
|
||||
path = arg
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
var files = _util.list(path, recursive)
|
||||
for (file in files) {
|
||||
if (File.exists(file)) {
|
||||
var size = File.size(file)
|
||||
System.print("%(formatSize(size).padLeft(10)) %(file)")
|
||||
} else {
|
||||
System.print(" DIR %(file)/")
|
||||
}
|
||||
}
|
||||
|
||||
System.print("\n%(files.count) items")
|
||||
}
|
||||
|
||||
cmdCopy(args) {
|
||||
if (args.count < 4) {
|
||||
System.print("Usage: %(_name) copy <source> <dest>")
|
||||
return
|
||||
}
|
||||
|
||||
var source = args[2]
|
||||
var dest = args[3]
|
||||
|
||||
if (!File.exists(source)) {
|
||||
System.print("Source file not found: %(source)")
|
||||
return
|
||||
}
|
||||
|
||||
_util.copy(source, dest)
|
||||
System.print("Copied %(source) to %(dest)")
|
||||
}
|
||||
|
||||
cmdHash(args) {
|
||||
if (args.count < 3) {
|
||||
System.print("Usage: %(_name) hash <file> [--algorithm=sha256|md5]")
|
||||
return
|
||||
}
|
||||
|
||||
var file = args[2]
|
||||
var algorithm = "sha256"
|
||||
|
||||
for (arg in args) {
|
||||
if (arg.startsWith("--algorithm=")) {
|
||||
algorithm = arg[12..-1]
|
||||
}
|
||||
}
|
||||
|
||||
if (!File.exists(file)) {
|
||||
System.print("File not found: %(file)")
|
||||
return
|
||||
}
|
||||
|
||||
var hash = _util.hash(file, algorithm)
|
||||
System.print("%(algorithm.upper): %(hash)")
|
||||
}
|
||||
|
||||
cmdSearch(args) {
|
||||
if (args.count < 3) {
|
||||
System.print("Usage: %(_name) search <pattern> [path]")
|
||||
return
|
||||
}
|
||||
|
||||
var pattern = args[2]
|
||||
var path = args.count > 3 ? args[3] : "."
|
||||
|
||||
var matches = _util.search(path, pattern)
|
||||
|
||||
if (matches.count == 0) {
|
||||
System.print("No matches found for '%(pattern)'")
|
||||
} else {
|
||||
System.print("Found %(matches.count) matches:")
|
||||
for (match in matches) {
|
||||
System.print(" %(match)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cmdStats(args) {
|
||||
var path = args.count > 2 ? args[2] : "."
|
||||
var stats = _util.stats(path)
|
||||
|
||||
System.print("Statistics for %(path):")
|
||||
System.print(" Files: %(stats["files"])")
|
||||
System.print(" Directories: %(stats["directories"])")
|
||||
System.print(" Total size: %(formatSize(stats["totalSize"]))")
|
||||
}
|
||||
|
||||
formatSize(bytes) {
|
||||
if (bytes < 1024) return "%(bytes) B"
|
||||
if (bytes < 1024 * 1024) return "%(((bytes / 1024) * 10).round / 10) KB"
|
||||
if (bytes < 1024 * 1024 * 1024) return "%(((bytes / 1024 / 1024) * 10).round / 10) MB"
|
||||
return "%(((bytes / 1024 / 1024 / 1024) * 10).round / 10) GB"
|
||||
}
|
||||
|
||||
showHelp() {
|
||||
System.print("%(_name) %(_version) - File utility tool")
|
||||
System.print("")
|
||||
System.print("Usage: %(_name) <command> [options] [arguments]")
|
||||
System.print("")
|
||||
System.print("Commands:")
|
||||
System.print(" list, ls List files in directory")
|
||||
System.print(" -r, --recursive Include subdirectories")
|
||||
System.print("")
|
||||
System.print(" copy, cp Copy a file")
|
||||
System.print(" <source> <dest>")
|
||||
System.print("")
|
||||
System.print(" hash Calculate file hash")
|
||||
System.print(" --algorithm=sha256|md5")
|
||||
System.print("")
|
||||
System.print(" search Search for files by name")
|
||||
System.print(" <pattern> [path]")
|
||||
System.print("")
|
||||
System.print(" stats Show directory statistics")
|
||||
System.print(" [path]")
|
||||
System.print("")
|
||||
System.print("Global Options:")
|
||||
System.print(" -v, --verbose Verbose output")
|
||||
System.print(" -h, --help Show this help")
|
||||
System.print(" -V, --version Show version")
|
||||
}
|
||||
}
|
||||
|
||||
var cli = CLI.new()
|
||||
cli.run(Process.arguments)</code></pre>
|
||||
|
||||
<h2>Running the Tool</h2>
|
||||
|
||||
<pre><code>$ wren_cli fileutil.wren --help
|
||||
fileutil 1.0.0 - File utility tool
|
||||
|
||||
Usage: fileutil <command> [options] [arguments]
|
||||
|
||||
Commands:
|
||||
list, ls List files in directory
|
||||
...
|
||||
|
||||
$ wren_cli fileutil.wren list -r src/
|
||||
1.2 KB src/main.wren
|
||||
3.4 KB src/utils.wren
|
||||
DIR src/lib/
|
||||
2.1 KB src/lib/helper.wren
|
||||
|
||||
4 items
|
||||
|
||||
$ wren_cli fileutil.wren hash README.md
|
||||
SHA256: a3f2e8b9c4d5...</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Create a shell alias or wrapper script to run your Wren CLI tools more conveniently: <code>alias fileutil='wren_cli /path/to/fileutil.wren'</code></p>
|
||||
</div>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<ul>
|
||||
<li>Add configuration file support with <a href="../api/json.html">JSON</a></li>
|
||||
<li>Implement colored output for better UX</li>
|
||||
<li>Add tab completion hints</li>
|
||||
<li>See the <a href="../api/os.html">OS</a> and <a href="../api/subprocess.html">Subprocess</a> API references</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,628 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Database Application" %}
|
||||
{% set breadcrumb = [{"url": "tutorials/index.html", "title": "Tutorials"}, {"title": "Database App"}] %}
|
||||
{% set prev_page = {"url": "tutorials/websocket-chat.html", "title": "WebSocket Chat"} %}
|
||||
{% set next_page = {"url": "tutorials/template-rendering.html", "title": "Template Rendering"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Database Application</h1>
|
||||
|
||||
<p>In this tutorial, you will build a complete task management application using SQLite for persistent storage. You will learn to create tables, perform CRUD operations, and build a command-line interface.</p>
|
||||
|
||||
<h2>What You Will Learn</h2>
|
||||
|
||||
<ul>
|
||||
<li>Creating and managing SQLite databases</li>
|
||||
<li>Designing database schemas</li>
|
||||
<li>Performing CRUD operations (Create, Read, Update, Delete)</li>
|
||||
<li>Using parameterized queries to prevent SQL injection</li>
|
||||
<li>Building a command-line interface</li>
|
||||
</ul>
|
||||
|
||||
<h2>Step 1: Setting Up the Database</h2>
|
||||
|
||||
<p>Create a file called <code>task_app.wren</code>:</p>
|
||||
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
|
||||
var db = Sqlite.open("tasks.db")
|
||||
|
||||
db.execute("
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
priority INTEGER DEFAULT 1,
|
||||
completed INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
due_date DATE
|
||||
)
|
||||
")
|
||||
|
||||
System.print("Database initialized!")
|
||||
db.close()</code></pre>
|
||||
|
||||
<h2>Step 2: Creating a Task Model</h2>
|
||||
|
||||
<p>Let's create a class to manage task operations:</p>
|
||||
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
import "datetime" for DateTime
|
||||
|
||||
class TaskManager {
|
||||
construct new(dbPath) {
|
||||
_db = Sqlite.open(dbPath)
|
||||
initDatabase()
|
||||
}
|
||||
|
||||
initDatabase() {
|
||||
_db.execute("
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
priority INTEGER DEFAULT 1,
|
||||
completed INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
due_date DATE
|
||||
)
|
||||
")
|
||||
}
|
||||
|
||||
create(title, description, priority, dueDate) {
|
||||
_db.execute(
|
||||
"INSERT INTO tasks (title, description, priority, due_date) VALUES (?, ?, ?, ?)",
|
||||
[title, description, priority, dueDate]
|
||||
)
|
||||
return _db.lastInsertId
|
||||
}
|
||||
|
||||
findAll() {
|
||||
return _db.execute("SELECT * FROM tasks ORDER BY priority DESC, due_date ASC")
|
||||
}
|
||||
|
||||
findById(id) {
|
||||
var results = _db.execute("SELECT * FROM tasks WHERE id = ?", [id])
|
||||
return results.count > 0 ? results[0] : null
|
||||
}
|
||||
|
||||
findPending() {
|
||||
return _db.execute("SELECT * FROM tasks WHERE completed = 0 ORDER BY priority DESC")
|
||||
}
|
||||
|
||||
findCompleted() {
|
||||
return _db.execute("SELECT * FROM tasks WHERE completed = 1 ORDER BY created_at DESC")
|
||||
}
|
||||
|
||||
update(id, title, description, priority, dueDate) {
|
||||
_db.execute(
|
||||
"UPDATE tasks SET title = ?, description = ?, priority = ?, due_date = ? WHERE id = ?",
|
||||
[title, description, priority, dueDate, id]
|
||||
)
|
||||
}
|
||||
|
||||
complete(id) {
|
||||
_db.execute("UPDATE tasks SET completed = 1 WHERE id = ?", [id])
|
||||
}
|
||||
|
||||
uncomplete(id) {
|
||||
_db.execute("UPDATE tasks SET completed = 0 WHERE id = ?", [id])
|
||||
}
|
||||
|
||||
delete(id) {
|
||||
_db.execute("DELETE FROM tasks WHERE id = ?", [id])
|
||||
}
|
||||
|
||||
search(query) {
|
||||
return _db.execute(
|
||||
"SELECT * FROM tasks WHERE title LIKE ? OR description LIKE ?",
|
||||
["\%%(query)\%", "\%%(query)\%"]
|
||||
)
|
||||
}
|
||||
|
||||
close() {
|
||||
_db.close()
|
||||
}
|
||||
}
|
||||
|
||||
var tasks = TaskManager.new("tasks.db")
|
||||
|
||||
var id = tasks.create("Learn Wren-CLI", "Complete the database tutorial", 3, "2024-12-31")
|
||||
System.print("Created task with ID: %(id)")
|
||||
|
||||
tasks.close()</code></pre>
|
||||
|
||||
<h2>Step 3: Building the CLI Interface</h2>
|
||||
|
||||
<p>Now let's create an interactive command-line interface:</p>
|
||||
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
import "io" for Stdin
|
||||
|
||||
class TaskManager {
|
||||
construct new(dbPath) {
|
||||
_db = Sqlite.open(dbPath)
|
||||
initDatabase()
|
||||
}
|
||||
|
||||
initDatabase() {
|
||||
_db.execute("
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
priority INTEGER DEFAULT 1,
|
||||
completed INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
")
|
||||
}
|
||||
|
||||
create(title, description, priority) {
|
||||
_db.execute(
|
||||
"INSERT INTO tasks (title, description, priority) VALUES (?, ?, ?)",
|
||||
[title, description, priority]
|
||||
)
|
||||
return _db.lastInsertId
|
||||
}
|
||||
|
||||
findAll() {
|
||||
return _db.execute("SELECT * FROM tasks ORDER BY completed ASC, priority DESC")
|
||||
}
|
||||
|
||||
complete(id) {
|
||||
_db.execute("UPDATE tasks SET completed = 1 WHERE id = ?", [id])
|
||||
}
|
||||
|
||||
delete(id) {
|
||||
_db.execute("DELETE FROM tasks WHERE id = ?", [id])
|
||||
}
|
||||
|
||||
close() {
|
||||
_db.close()
|
||||
}
|
||||
}
|
||||
|
||||
class TaskApp {
|
||||
construct new() {
|
||||
_tasks = TaskManager.new("tasks.db")
|
||||
_running = true
|
||||
}
|
||||
|
||||
run() {
|
||||
System.print("=== Task Manager ===\n")
|
||||
showHelp()
|
||||
|
||||
while (_running) {
|
||||
System.write("\n> ")
|
||||
var input = Stdin.readLine()
|
||||
|
||||
if (input == null) break
|
||||
|
||||
var parts = input.split(" ")
|
||||
var command = parts.count > 0 ? parts[0] : ""
|
||||
|
||||
if (command == "list") {
|
||||
listTasks()
|
||||
} else if (command == "add") {
|
||||
addTask()
|
||||
} else if (command == "done") {
|
||||
if (parts.count > 1) {
|
||||
completeTask(Num.fromString(parts[1]))
|
||||
} else {
|
||||
System.print("Usage: done <id>")
|
||||
}
|
||||
} else if (command == "delete") {
|
||||
if (parts.count > 1) {
|
||||
deleteTask(Num.fromString(parts[1]))
|
||||
} else {
|
||||
System.print("Usage: delete <id>")
|
||||
}
|
||||
} else if (command == "help") {
|
||||
showHelp()
|
||||
} else if (command == "quit" || command == "exit") {
|
||||
_running = false
|
||||
} else if (command.count > 0) {
|
||||
System.print("Unknown command: %(command)")
|
||||
}
|
||||
}
|
||||
|
||||
_tasks.close()
|
||||
System.print("Goodbye!")
|
||||
}
|
||||
|
||||
showHelp() {
|
||||
System.print("Commands:")
|
||||
System.print(" list - Show all tasks")
|
||||
System.print(" add - Add a new task")
|
||||
System.print(" done <id> - Mark task as complete")
|
||||
System.print(" delete <id> - Delete a task")
|
||||
System.print(" help - Show this help")
|
||||
System.print(" quit - Exit the application")
|
||||
}
|
||||
|
||||
listTasks() {
|
||||
var tasks = _tasks.findAll()
|
||||
|
||||
if (tasks.count == 0) {
|
||||
System.print("No tasks found.")
|
||||
return
|
||||
}
|
||||
|
||||
System.print("\nID | Pri | Status | Title")
|
||||
System.print("----|-----|--------|------")
|
||||
|
||||
for (task in tasks) {
|
||||
var status = task["completed"] == 1 ? "[X]" : "[ ]"
|
||||
var priority = ["Low", "Med", "High"][task["priority"] - 1]
|
||||
System.print("%(task["id"]) | %(priority) | %(status) | %(task["title"])")
|
||||
}
|
||||
}
|
||||
|
||||
addTask() {
|
||||
System.write("Title: ")
|
||||
var title = Stdin.readLine()
|
||||
|
||||
System.write("Description (optional): ")
|
||||
var description = Stdin.readLine()
|
||||
|
||||
System.write("Priority (1=Low, 2=Medium, 3=High): ")
|
||||
var priorityStr = Stdin.readLine()
|
||||
var priority = Num.fromString(priorityStr) || 1
|
||||
|
||||
if (priority < 1) priority = 1
|
||||
if (priority > 3) priority = 3
|
||||
|
||||
var id = _tasks.create(title, description, priority)
|
||||
System.print("Task created with ID: %(id)")
|
||||
}
|
||||
|
||||
completeTask(id) {
|
||||
_tasks.complete(id)
|
||||
System.print("Task %(id) marked as complete.")
|
||||
}
|
||||
|
||||
deleteTask(id) {
|
||||
_tasks.delete(id)
|
||||
System.print("Task %(id) deleted.")
|
||||
}
|
||||
}
|
||||
|
||||
var app = TaskApp.new()
|
||||
app.run()</code></pre>
|
||||
|
||||
<h2>Step 4: Adding Advanced Features</h2>
|
||||
|
||||
<p>Let's enhance our application with categories and due dates:</p>
|
||||
|
||||
<pre><code>import "sqlite" for Sqlite
|
||||
import "io" for Stdin
|
||||
import "datetime" for DateTime
|
||||
|
||||
class TaskManager {
|
||||
construct new(dbPath) {
|
||||
_db = Sqlite.open(dbPath)
|
||||
initDatabase()
|
||||
}
|
||||
|
||||
initDatabase() {
|
||||
_db.execute("
|
||||
CREATE TABLE IF NOT EXISTS categories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
color TEXT DEFAULT '#808080'
|
||||
)
|
||||
")
|
||||
|
||||
_db.execute("
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
category_id INTEGER,
|
||||
priority INTEGER DEFAULT 1,
|
||||
completed INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
due_date DATE,
|
||||
FOREIGN KEY (category_id) REFERENCES categories(id)
|
||||
)
|
||||
")
|
||||
|
||||
var categories = _db.execute("SELECT COUNT(*) as count FROM categories")
|
||||
if (categories[0]["count"] == 0) {
|
||||
_db.execute("INSERT INTO categories (name, color) VALUES ('Work', '#FF6B6B')")
|
||||
_db.execute("INSERT INTO categories (name, color) VALUES ('Personal', '#4ECDC4')")
|
||||
_db.execute("INSERT INTO categories (name, color) VALUES ('Shopping', '#45B7D1')")
|
||||
}
|
||||
}
|
||||
|
||||
createTask(title, description, categoryId, priority, dueDate) {
|
||||
_db.execute(
|
||||
"INSERT INTO tasks (title, description, category_id, priority, due_date) VALUES (?, ?, ?, ?, ?)",
|
||||
[title, description, categoryId, priority, dueDate]
|
||||
)
|
||||
return _db.lastInsertId
|
||||
}
|
||||
|
||||
findAllTasks() {
|
||||
return _db.execute("
|
||||
SELECT t.*, c.name as category_name
|
||||
FROM tasks t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
ORDER BY t.completed ASC, t.priority DESC, t.due_date ASC
|
||||
")
|
||||
}
|
||||
|
||||
findTasksByCategory(categoryId) {
|
||||
return _db.execute("
|
||||
SELECT t.*, c.name as category_name
|
||||
FROM tasks t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
WHERE t.category_id = ?
|
||||
ORDER BY t.completed ASC, t.priority DESC
|
||||
", [categoryId])
|
||||
}
|
||||
|
||||
findOverdueTasks() {
|
||||
return _db.execute("
|
||||
SELECT t.*, c.name as category_name
|
||||
FROM tasks t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
WHERE t.completed = 0 AND t.due_date < DATE('now')
|
||||
ORDER BY t.due_date ASC
|
||||
")
|
||||
}
|
||||
|
||||
findDueToday() {
|
||||
return _db.execute("
|
||||
SELECT t.*, c.name as category_name
|
||||
FROM tasks t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
WHERE t.completed = 0 AND t.due_date = DATE('now')
|
||||
ORDER BY t.priority DESC
|
||||
")
|
||||
}
|
||||
|
||||
findCategories() {
|
||||
return _db.execute("SELECT * FROM categories ORDER BY name")
|
||||
}
|
||||
|
||||
createCategory(name, color) {
|
||||
_db.execute("INSERT INTO categories (name, color) VALUES (?, ?)", [name, color])
|
||||
return _db.lastInsertId
|
||||
}
|
||||
|
||||
completeTask(id) {
|
||||
_db.execute("UPDATE tasks SET completed = 1 WHERE id = ?", [id])
|
||||
}
|
||||
|
||||
deleteTask(id) {
|
||||
_db.execute("DELETE FROM tasks WHERE id = ?", [id])
|
||||
}
|
||||
|
||||
getStats() {
|
||||
var total = _db.execute("SELECT COUNT(*) as count FROM tasks")[0]["count"]
|
||||
var completed = _db.execute("SELECT COUNT(*) as count FROM tasks WHERE completed = 1")[0]["count"]
|
||||
var pending = total - completed
|
||||
var overdue = _db.execute("SELECT COUNT(*) as count FROM tasks WHERE completed = 0 AND due_date < DATE('now')")[0]["count"]
|
||||
|
||||
return {
|
||||
"total": total,
|
||||
"completed": completed,
|
||||
"pending": pending,
|
||||
"overdue": overdue
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
_db.close()
|
||||
}
|
||||
}
|
||||
|
||||
class TaskApp {
|
||||
construct new() {
|
||||
_tasks = TaskManager.new("tasks.db")
|
||||
_running = true
|
||||
}
|
||||
|
||||
run() {
|
||||
System.print("=== Task Manager v2 ===\n")
|
||||
|
||||
while (_running) {
|
||||
showMenu()
|
||||
System.write("\nChoice: ")
|
||||
var choice = Stdin.readLine()
|
||||
|
||||
if (choice == "1") {
|
||||
listTasks()
|
||||
} else if (choice == "2") {
|
||||
addTask()
|
||||
} else if (choice == "3") {
|
||||
completeTask()
|
||||
} else if (choice == "4") {
|
||||
showOverdue()
|
||||
} else if (choice == "5") {
|
||||
showStats()
|
||||
} else if (choice == "6") {
|
||||
manageCategories()
|
||||
} else if (choice == "0") {
|
||||
_running = false
|
||||
}
|
||||
}
|
||||
|
||||
_tasks.close()
|
||||
System.print("\nGoodbye!")
|
||||
}
|
||||
|
||||
showMenu() {
|
||||
System.print("\n--- Main Menu ---")
|
||||
System.print("1. List all tasks")
|
||||
System.print("2. Add new task")
|
||||
System.print("3. Complete task")
|
||||
System.print("4. Show overdue")
|
||||
System.print("5. Statistics")
|
||||
System.print("6. Categories")
|
||||
System.print("0. Exit")
|
||||
}
|
||||
|
||||
listTasks() {
|
||||
var tasks = _tasks.findAllTasks()
|
||||
|
||||
if (tasks.count == 0) {
|
||||
System.print("\nNo tasks found.")
|
||||
return
|
||||
}
|
||||
|
||||
System.print("\n--- All Tasks ---")
|
||||
for (task in tasks) {
|
||||
var status = task["completed"] == 1 ? "[X]" : "[ ]"
|
||||
var category = task["category_name"] || "None"
|
||||
var due = task["due_date"] || "No due date"
|
||||
|
||||
System.print("%(task["id"]). %(status) %(task["title"])")
|
||||
System.print(" Category: %(category) | Due: %(due)")
|
||||
}
|
||||
}
|
||||
|
||||
addTask() {
|
||||
System.print("\n--- Add Task ---")
|
||||
|
||||
System.write("Title: ")
|
||||
var title = Stdin.readLine()
|
||||
if (title.count == 0) return
|
||||
|
||||
System.write("Description: ")
|
||||
var description = Stdin.readLine()
|
||||
|
||||
var categories = _tasks.findCategories()
|
||||
System.print("\nCategories:")
|
||||
for (cat in categories) {
|
||||
System.print(" %(cat["id"]). %(cat["name"])")
|
||||
}
|
||||
System.write("Category ID (or 0 for none): ")
|
||||
var categoryId = Num.fromString(Stdin.readLine())
|
||||
if (categoryId == 0) categoryId = null
|
||||
|
||||
System.write("Priority (1-3): ")
|
||||
var priority = Num.fromString(Stdin.readLine()) || 1
|
||||
|
||||
System.write("Due date (YYYY-MM-DD or empty): ")
|
||||
var dueDate = Stdin.readLine()
|
||||
if (dueDate.count == 0) dueDate = null
|
||||
|
||||
var id = _tasks.createTask(title, description, categoryId, priority, dueDate)
|
||||
System.print("\nTask created with ID: %(id)")
|
||||
}
|
||||
|
||||
completeTask() {
|
||||
System.write("\nTask ID to complete: ")
|
||||
var id = Num.fromString(Stdin.readLine())
|
||||
if (id) {
|
||||
_tasks.completeTask(id)
|
||||
System.print("Task %(id) marked as complete!")
|
||||
}
|
||||
}
|
||||
|
||||
showOverdue() {
|
||||
var tasks = _tasks.findOverdueTasks()
|
||||
|
||||
if (tasks.count == 0) {
|
||||
System.print("\nNo overdue tasks!")
|
||||
return
|
||||
}
|
||||
|
||||
System.print("\n--- Overdue Tasks ---")
|
||||
for (task in tasks) {
|
||||
System.print("%(task["id"]). %(task["title"]) (Due: %(task["due_date"]))")
|
||||
}
|
||||
}
|
||||
|
||||
showStats() {
|
||||
var stats = _tasks.getStats()
|
||||
|
||||
System.print("\n--- Statistics ---")
|
||||
System.print("Total tasks: %(stats["total"])")
|
||||
System.print("Completed: %(stats["completed"])")
|
||||
System.print("Pending: %(stats["pending"])")
|
||||
System.print("Overdue: %(stats["overdue"])")
|
||||
|
||||
if (stats["total"] > 0) {
|
||||
var pct = (stats["completed"] / stats["total"] * 100).round
|
||||
System.print("Completion rate: %(pct)\%")
|
||||
}
|
||||
}
|
||||
|
||||
manageCategories() {
|
||||
var categories = _tasks.findCategories()
|
||||
|
||||
System.print("\n--- Categories ---")
|
||||
for (cat in categories) {
|
||||
System.print("%(cat["id"]). %(cat["name"])")
|
||||
}
|
||||
|
||||
System.write("\nAdd new category? (y/n): ")
|
||||
if (Stdin.readLine().lower == "y") {
|
||||
System.write("Category name: ")
|
||||
var name = Stdin.readLine()
|
||||
if (name.count > 0) {
|
||||
_tasks.createCategory(name, "#808080")
|
||||
System.print("Category created!")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var app = TaskApp.new()
|
||||
app.run()</code></pre>
|
||||
|
||||
<h2>Running the Application</h2>
|
||||
|
||||
<pre><code>$ wren_cli task_app.wren
|
||||
=== Task Manager v2 ===
|
||||
|
||||
--- Main Menu ---
|
||||
1. List all tasks
|
||||
2. Add new task
|
||||
3. Complete task
|
||||
4. Show overdue
|
||||
5. Statistics
|
||||
6. Categories
|
||||
0. Exit
|
||||
|
||||
Choice: 2
|
||||
|
||||
--- Add Task ---
|
||||
Title: Complete database tutorial
|
||||
Description: Learn SQLite with Wren-CLI
|
||||
|
||||
Categories:
|
||||
1. Work
|
||||
2. Personal
|
||||
3. Shopping
|
||||
Category ID (or 0 for none): 1
|
||||
Priority (1-3): 3
|
||||
Due date (YYYY-MM-DD or empty): 2024-12-31
|
||||
|
||||
Task created with ID: 1</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Always use parameterized queries with <code>?</code> placeholders instead of string concatenation. This prevents SQL injection vulnerabilities.</p>
|
||||
</div>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Use <code>":memory:"</code> as the database path for testing without creating a file on disk.</p>
|
||||
</div>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<ul>
|
||||
<li>Add data export to JSON or CSV</li>
|
||||
<li>Implement task reminders with <a href="../api/timer.html">Timer</a></li>
|
||||
<li>Generate HTML reports with <a href="template-rendering.html">Jinja templates</a></li>
|
||||
<li>See the <a href="../api/sqlite.html">SQLite API reference</a></li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,519 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Building an HTTP Client" %}
|
||||
{% set breadcrumb = [{"url": "tutorials/index.html", "title": "Tutorials"}, {"title": "HTTP Client"}] %}
|
||||
{% set prev_page = {"url": "tutorials/index.html", "title": "Tutorials"} %}
|
||||
{% set next_page = {"url": "tutorials/websocket-chat.html", "title": "WebSocket Chat"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Building an HTTP Client</h1>
|
||||
|
||||
<p>In this tutorial, you will learn how to build a REST API client using Wren-CLI's <code>http</code> and <code>json</code> modules. By the end, you will have a reusable API client class that can interact with any JSON REST API.</p>
|
||||
|
||||
<h2>What You Will Learn</h2>
|
||||
|
||||
<ul>
|
||||
<li>Making GET, POST, PUT, and DELETE requests</li>
|
||||
<li>Parsing JSON responses</li>
|
||||
<li>Handling HTTP errors</li>
|
||||
<li>Working with request headers</li>
|
||||
<li>Building a reusable API client class</li>
|
||||
</ul>
|
||||
|
||||
<h2>Step 1: Your First HTTP Request</h2>
|
||||
|
||||
<p>Let's start with a simple GET request. Create a file called <code>http_client.wren</code>:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://jsonplaceholder.typicode.com/posts/1")
|
||||
|
||||
System.print("Status: %(response.statusCode)")
|
||||
System.print("Body: %(response.body)")</code></pre>
|
||||
|
||||
<p>Run it:</p>
|
||||
|
||||
<pre><code>$ wren_cli http_client.wren
|
||||
Status: 200
|
||||
Body: {
|
||||
"userId": 1,
|
||||
"id": 1,
|
||||
"title": "sunt aut facere...",
|
||||
"body": "quia et suscipit..."
|
||||
}</code></pre>
|
||||
|
||||
<h2>Step 2: Parsing JSON Responses</h2>
|
||||
|
||||
<p>Raw JSON strings are not very useful. Let's parse them into Wren objects:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
var response = Http.get("https://jsonplaceholder.typicode.com/posts/1")
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
var post = Json.parse(response.body)
|
||||
System.print("Title: %(post["title"])")
|
||||
System.print("User ID: %(post["userId"])")
|
||||
} else {
|
||||
System.print("Error: %(response.statusCode)")
|
||||
}</code></pre>
|
||||
|
||||
<p>The <code>HttpResponse</code> class also provides a convenient <code>json</code> property:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://jsonplaceholder.typicode.com/posts/1")
|
||||
var post = response.json
|
||||
|
||||
System.print("Title: %(post["title"])")</code></pre>
|
||||
|
||||
<h2>Step 3: Fetching Lists</h2>
|
||||
|
||||
<p>APIs often return arrays of objects. Let's fetch multiple posts:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
|
||||
var response = Http.get("https://jsonplaceholder.typicode.com/posts")
|
||||
var posts = response.json
|
||||
|
||||
System.print("Found %(posts.count) posts\n")
|
||||
|
||||
for (i in 0...5) {
|
||||
var post = posts[i]
|
||||
System.print("%(post["id"]). %(post["title"])")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Step 4: Making POST Requests</h2>
|
||||
|
||||
<p>To create resources, use POST with a JSON body:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
var newPost = {
|
||||
"title": "My New Post",
|
||||
"body": "This is the content of my post.",
|
||||
"userId": 1
|
||||
}
|
||||
|
||||
var response = Http.post(
|
||||
"https://jsonplaceholder.typicode.com/posts",
|
||||
Json.stringify(newPost),
|
||||
{"Content-Type": "application/json"}
|
||||
)
|
||||
|
||||
System.print("Status: %(response.statusCode)")
|
||||
System.print("Created post with ID: %(response.json["id"])")</code></pre>
|
||||
|
||||
<h2>Step 5: PUT and DELETE Requests</h2>
|
||||
|
||||
<p>Update and delete resources with PUT and DELETE:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
var updatedPost = {
|
||||
"id": 1,
|
||||
"title": "Updated Title",
|
||||
"body": "Updated content.",
|
||||
"userId": 1
|
||||
}
|
||||
|
||||
var putResponse = Http.put(
|
||||
"https://jsonplaceholder.typicode.com/posts/1",
|
||||
Json.stringify(updatedPost),
|
||||
{"Content-Type": "application/json"}
|
||||
)
|
||||
System.print("PUT Status: %(putResponse.statusCode)")
|
||||
|
||||
var deleteResponse = Http.delete("https://jsonplaceholder.typicode.com/posts/1")
|
||||
System.print("DELETE Status: %(deleteResponse.statusCode)")</code></pre>
|
||||
|
||||
<h2>Step 6: Building an API Client Class</h2>
|
||||
|
||||
<p>Let's create a reusable API client that encapsulates all these patterns:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
class ApiClient {
|
||||
construct new(baseUrl) {
|
||||
_baseUrl = baseUrl
|
||||
_headers = {"Content-Type": "application/json"}
|
||||
}
|
||||
|
||||
headers { _headers }
|
||||
headers=(value) { _headers = value }
|
||||
|
||||
setHeader(name, value) {
|
||||
_headers[name] = value
|
||||
}
|
||||
|
||||
get(path) {
|
||||
var response = Http.get(_baseUrl + path, _headers)
|
||||
return handleResponse(response)
|
||||
}
|
||||
|
||||
post(path, data) {
|
||||
var body = Json.stringify(data)
|
||||
var response = Http.post(_baseUrl + path, body, _headers)
|
||||
return handleResponse(response)
|
||||
}
|
||||
|
||||
put(path, data) {
|
||||
var body = Json.stringify(data)
|
||||
var response = Http.put(_baseUrl + path, body, _headers)
|
||||
return handleResponse(response)
|
||||
}
|
||||
|
||||
delete(path) {
|
||||
var response = Http.delete(_baseUrl + path, _headers)
|
||||
return handleResponse(response)
|
||||
}
|
||||
|
||||
handleResponse(response) {
|
||||
if (response.statusCode >= 200 && response.statusCode < 300) {
|
||||
if (response.body.count > 0) {
|
||||
return response.json
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
Fiber.abort("API Error: %(response.statusCode)")
|
||||
}
|
||||
}
|
||||
|
||||
var api = ApiClient.new("https://jsonplaceholder.typicode.com")
|
||||
|
||||
var posts = api.get("/posts")
|
||||
System.print("Fetched %(posts.count) posts")
|
||||
|
||||
var newPost = api.post("/posts", {
|
||||
"title": "Hello from Wren",
|
||||
"body": "Created with ApiClient",
|
||||
"userId": 1
|
||||
})
|
||||
System.print("Created post: %(newPost["id"])")</code></pre>
|
||||
|
||||
<h2>Step 7: Adding Authentication</h2>
|
||||
|
||||
<p>Many APIs require authentication. Add support for API keys and bearer tokens:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
import "base64" for Base64
|
||||
|
||||
class ApiClient {
|
||||
construct new(baseUrl) {
|
||||
_baseUrl = baseUrl
|
||||
_headers = {"Content-Type": "application/json"}
|
||||
}
|
||||
|
||||
setApiKey(key) {
|
||||
_headers["X-API-Key"] = key
|
||||
}
|
||||
|
||||
setBearerToken(token) {
|
||||
_headers["Authorization"] = "Bearer %(token)"
|
||||
}
|
||||
|
||||
setBasicAuth(username, password) {
|
||||
var credentials = Base64.encode("%(username):%(password)")
|
||||
_headers["Authorization"] = "Basic %(credentials)"
|
||||
}
|
||||
|
||||
get(path) {
|
||||
var response = Http.get(_baseUrl + path, _headers)
|
||||
return handleResponse(response)
|
||||
}
|
||||
|
||||
handleResponse(response) {
|
||||
if (response.statusCode == 401) {
|
||||
Fiber.abort("Authentication failed")
|
||||
}
|
||||
if (response.statusCode == 403) {
|
||||
Fiber.abort("Access forbidden")
|
||||
}
|
||||
if (response.statusCode >= 200 && response.statusCode < 300) {
|
||||
return response.json
|
||||
}
|
||||
Fiber.abort("API Error: %(response.statusCode)")
|
||||
}
|
||||
}
|
||||
|
||||
var api = ApiClient.new("https://api.example.com")
|
||||
api.setBearerToken("your-auth-token")
|
||||
|
||||
var data = api.get("/protected/resource")</code></pre>
|
||||
|
||||
<h2>Step 8: Error Handling</h2>
|
||||
|
||||
<p>Proper error handling makes your client robust:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
|
||||
class ApiError {
|
||||
construct new(statusCode, message) {
|
||||
_statusCode = statusCode
|
||||
_message = message
|
||||
}
|
||||
|
||||
statusCode { _statusCode }
|
||||
message { _message }
|
||||
|
||||
toString { "ApiError %(statusCode): %(message)" }
|
||||
}
|
||||
|
||||
class ApiClient {
|
||||
construct new(baseUrl) {
|
||||
_baseUrl = baseUrl
|
||||
_headers = {"Content-Type": "application/json"}
|
||||
}
|
||||
|
||||
get(path) {
|
||||
var fiber = Fiber.new {
|
||||
return Http.get(_baseUrl + path, _headers)
|
||||
}
|
||||
|
||||
var response = fiber.try()
|
||||
if (fiber.error) {
|
||||
return {"error": ApiError.new(0, fiber.error)}
|
||||
}
|
||||
|
||||
return handleResponse(response)
|
||||
}
|
||||
|
||||
handleResponse(response) {
|
||||
if (response.statusCode >= 200 && response.statusCode < 300) {
|
||||
return {"data": response.json}
|
||||
}
|
||||
|
||||
var message = "Unknown error"
|
||||
var fiber = Fiber.new { response.json["message"] }
|
||||
var apiMessage = fiber.try()
|
||||
if (!fiber.error && apiMessage) {
|
||||
message = apiMessage
|
||||
}
|
||||
|
||||
return {"error": ApiError.new(response.statusCode, message)}
|
||||
}
|
||||
}
|
||||
|
||||
var api = ApiClient.new("https://jsonplaceholder.typicode.com")
|
||||
var result = api.get("/posts/1")
|
||||
|
||||
if (result["error"]) {
|
||||
System.print("Error: %(result["error"])")
|
||||
} else {
|
||||
System.print("Success: %(result["data"]["title"])")
|
||||
}</code></pre>
|
||||
|
||||
<h2>Step 9: Concurrent HTTP Requests</h2>
|
||||
|
||||
<p>When you need to fetch data from multiple endpoints, sequential requests can be slow. Use <code>async</code> and <code>await</code> to run requests concurrently:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "json" for Json
|
||||
|
||||
var fetchJson = async { |url|
|
||||
var response = Http.get(url)
|
||||
return response.json
|
||||
}
|
||||
|
||||
// SEQUENTIAL: Each request waits for the previous one
|
||||
System.print("--- Sequential requests ---")
|
||||
var user = await fetchJson("https://jsonplaceholder.typicode.com/users/1")
|
||||
var posts = await fetchJson("https://jsonplaceholder.typicode.com/posts?userId=1")
|
||||
var todos = await fetchJson("https://jsonplaceholder.typicode.com/todos?userId=1")
|
||||
|
||||
System.print("User: %(user["name"])")
|
||||
System.print("Posts: %(posts.count)")
|
||||
System.print("Todos: %(todos.count)")</code></pre>
|
||||
|
||||
<p>For concurrent execution, use <code>.call()</code> to start requests without waiting, then <code>await</code> the results:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "json" for Json
|
||||
|
||||
var fetchJson = async { |url|
|
||||
var response = Http.get(url)
|
||||
return response.json
|
||||
}
|
||||
|
||||
// CONCURRENT: All requests start at once
|
||||
System.print("--- Concurrent requests ---")
|
||||
var f1 = fetchJson.call("https://jsonplaceholder.typicode.com/users/1")
|
||||
var f2 = fetchJson.call("https://jsonplaceholder.typicode.com/posts?userId=1")
|
||||
var f3 = fetchJson.call("https://jsonplaceholder.typicode.com/todos?userId=1")
|
||||
|
||||
// Wait for results (requests run in parallel)
|
||||
var user = await f1
|
||||
var posts = await f2
|
||||
var todos = await f3
|
||||
|
||||
System.print("User: %(user["name"])")
|
||||
System.print("Posts: %(posts.count)")
|
||||
System.print("Todos: %(todos.count)")</code></pre>
|
||||
|
||||
<h3>Batch Fetching with Concurrent Requests</h3>
|
||||
|
||||
<p>For fetching multiple URLs dynamically, create futures in a loop:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "scheduler" for Scheduler, Future
|
||||
import "json" for Json
|
||||
|
||||
var fetchJson = async { |url|
|
||||
var response = Http.get(url)
|
||||
return response.json
|
||||
}
|
||||
|
||||
var userIds = [1, 2, 3, 4, 5]
|
||||
|
||||
// Start all requests concurrently
|
||||
var futures = []
|
||||
for (id in userIds) {
|
||||
futures.add(fetchJson.call("https://jsonplaceholder.typicode.com/users/%(id)"))
|
||||
}
|
||||
|
||||
// Collect results
|
||||
var users = []
|
||||
for (f in futures) {
|
||||
users.add(await f)
|
||||
}
|
||||
|
||||
System.print("Fetched %(users.count) users:")
|
||||
for (user in users) {
|
||||
System.print(" - %(user["name"]) (%(user["email"]))")
|
||||
}</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Direct Calling vs .call()</div>
|
||||
<p>Use <code>await fn(args)</code> for sequential execution (waits immediately). Use <code>fn.call(args)</code> to start without waiting, enabling concurrent execution.</p>
|
||||
</div>
|
||||
|
||||
<h2>Complete Example</h2>
|
||||
|
||||
<p>Here is a complete, production-ready API client:</p>
|
||||
|
||||
<pre><code>import "http" for Http
|
||||
import "json" for Json
|
||||
import "base64" for Base64
|
||||
|
||||
class ApiClient {
|
||||
construct new(baseUrl) {
|
||||
_baseUrl = baseUrl
|
||||
_headers = {"Content-Type": "application/json"}
|
||||
_timeout = 30000
|
||||
}
|
||||
|
||||
baseUrl { _baseUrl }
|
||||
headers { _headers }
|
||||
|
||||
setHeader(name, value) { _headers[name] = value }
|
||||
removeHeader(name) { _headers.remove(name) }
|
||||
|
||||
setBearerToken(token) {
|
||||
_headers["Authorization"] = "Bearer %(token)"
|
||||
}
|
||||
|
||||
setBasicAuth(username, password) {
|
||||
var credentials = Base64.encode("%(username):%(password)")
|
||||
_headers["Authorization"] = "Basic %(credentials)"
|
||||
}
|
||||
|
||||
get(path) { request("GET", path, null) }
|
||||
post(path, data) { request("POST", path, data) }
|
||||
put(path, data) { request("PUT", path, data) }
|
||||
patch(path, data) { request("PATCH", path, data) }
|
||||
delete(path) { request("DELETE", path, null) }
|
||||
|
||||
request(method, path, data) {
|
||||
var url = _baseUrl + path
|
||||
var body = data ? Json.stringify(data) : ""
|
||||
|
||||
var response
|
||||
if (method == "GET") {
|
||||
response = Http.get(url, _headers)
|
||||
} else if (method == "POST") {
|
||||
response = Http.post(url, body, _headers)
|
||||
} else if (method == "PUT") {
|
||||
response = Http.put(url, body, _headers)
|
||||
} else if (method == "PATCH") {
|
||||
response = Http.patch(url, body, _headers)
|
||||
} else if (method == "DELETE") {
|
||||
response = Http.delete(url, _headers)
|
||||
}
|
||||
|
||||
return parseResponse(response)
|
||||
}
|
||||
|
||||
parseResponse(response) {
|
||||
var result = {
|
||||
"status": response.statusCode,
|
||||
"headers": response.headers,
|
||||
"ok": response.statusCode >= 200 && response.statusCode < 300
|
||||
}
|
||||
|
||||
if (response.body.count > 0) {
|
||||
var fiber = Fiber.new { Json.parse(response.body) }
|
||||
var data = fiber.try()
|
||||
result["data"] = fiber.error ? response.body : data
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
System.print("=== API Client Demo ===\n")
|
||||
|
||||
var api = ApiClient.new("https://jsonplaceholder.typicode.com")
|
||||
|
||||
System.print("--- Fetching posts ---")
|
||||
var result = api.get("/posts")
|
||||
if (result["ok"]) {
|
||||
System.print("Found %(result["data"].count) posts")
|
||||
System.print("First post: %(result["data"][0]["title"])")
|
||||
}
|
||||
|
||||
System.print("\n--- Creating post ---")
|
||||
result = api.post("/posts", {
|
||||
"title": "Created with Wren-CLI",
|
||||
"body": "This is a test post",
|
||||
"userId": 1
|
||||
})
|
||||
if (result["ok"]) {
|
||||
System.print("Created post ID: %(result["data"]["id"])")
|
||||
}
|
||||
|
||||
System.print("\n--- Updating post ---")
|
||||
result = api.put("/posts/1", {
|
||||
"id": 1,
|
||||
"title": "Updated Title",
|
||||
"body": "Updated body",
|
||||
"userId": 1
|
||||
})
|
||||
System.print("Update status: %(result["status"])")
|
||||
|
||||
System.print("\n--- Deleting post ---")
|
||||
result = api.delete("/posts/1")
|
||||
System.print("Delete status: %(result["status"])")</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Save the <code>ApiClient</code> class in a separate file like <code>api_client.wren</code> and import it in your projects for reuse.</p>
|
||||
</div>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<ul>
|
||||
<li>Learn about <a href="../api/http.html">HTTP module</a> features in detail</li>
|
||||
<li>Explore <a href="../api/json.html">JSON module</a> for advanced parsing</li>
|
||||
<li>Build a <a href="websocket-chat.html">WebSocket chat application</a></li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,92 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Tutorials" %}
|
||||
{% set breadcrumb = [{"title": "Tutorials"}] %}
|
||||
{% set prev_page = {"url": "api/math.html", "title": "math"} %}
|
||||
{% set next_page = {"url": "tutorials/http-client.html", "title": "HTTP Client"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>Tutorials</h1>
|
||||
|
||||
<p>Step-by-step tutorials that guide you through building complete applications with Wren-CLI. Each tutorial introduces new concepts and builds upon previous knowledge.</p>
|
||||
|
||||
<div class="card-grid">
|
||||
<div class="card">
|
||||
<h3><a href="http-client.html">Building an HTTP Client</a></h3>
|
||||
<p>Learn to make HTTP requests, parse JSON responses, and handle errors while building a REST API client.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">http</span>
|
||||
<span class="tag">json</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3><a href="websocket-chat.html">WebSocket Chat Application</a></h3>
|
||||
<p>Build a real-time chat application using WebSockets with both client and server components.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">websocket</span>
|
||||
<span class="tag">fibers</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3><a href="database-app.html">Database Application</a></h3>
|
||||
<p>Create a complete CRUD application using SQLite for persistent data storage.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">sqlite</span>
|
||||
<span class="tag">io</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3><a href="template-rendering.html">Template Rendering</a></h3>
|
||||
<p>Use Jinja templates to generate HTML pages, reports, and configuration files.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">jinja</span>
|
||||
<span class="tag">io</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3><a href="cli-tool.html">Building a CLI Tool</a></h3>
|
||||
<p>Create a command-line application with argument parsing, user input, and subprocess management.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">os</span>
|
||||
<span class="tag">subprocess</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3><a href="web-server.html">Building a Web Server</a></h3>
|
||||
<p>Build HTTP servers with routing, sessions, middleware, and REST APIs using the web module.</p>
|
||||
<div class="card-meta">
|
||||
<span class="tag">web</span>
|
||||
<span class="tag">http</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Learning Path</h2>
|
||||
|
||||
<p>If you are new to Wren-CLI, we recommend following the tutorials in this order:</p>
|
||||
|
||||
<ol>
|
||||
<li><strong>HTTP Client</strong> - Introduces async operations and JSON handling</li>
|
||||
<li><strong>Database Application</strong> - Covers data persistence and file I/O</li>
|
||||
<li><strong>Template Rendering</strong> - Learn the Jinja template system</li>
|
||||
<li><strong>WebSocket Chat</strong> - Advanced async patterns with fibers</li>
|
||||
<li><strong>CLI Tool</strong> - Bringing it all together in a real application</li>
|
||||
<li><strong>Web Server</strong> - Build complete web applications with the web module</li>
|
||||
</ol>
|
||||
|
||||
<h2>Prerequisites</h2>
|
||||
|
||||
<p>Before starting the tutorials, you should:</p>
|
||||
|
||||
<ul>
|
||||
<li>Have Wren-CLI <a href="../getting-started/installation.html">installed</a></li>
|
||||
<li>Understand the <a href="../language/index.html">basic syntax</a></li>
|
||||
<li>Be familiar with <a href="../language/classes.html">classes</a> and <a href="../language/methods.html">methods</a></li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,575 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "Template Rendering" %}
|
||||
{% set breadcrumb = [{"url": "tutorials/index.html", "title": "Tutorials"}, {"title": "Template Rendering"}] %}
|
||||
{% set prev_page = {"url": "tutorials/database-app.html", "title": "Database App"} %}
|
||||
{% set next_page = {"url": "tutorials/cli-tool.html", "title": "CLI Tool"} %}
|
||||
|
||||
{% block article %}
|
||||
{% raw %}
|
||||
<h1>Template Rendering</h1>
|
||||
|
||||
<p>In this tutorial, you will learn to use Jinja templates to generate HTML pages, reports, and configuration files. Jinja is a powerful templating engine that separates your presentation logic from your data.</p>
|
||||
|
||||
<h2>What You Will Learn</h2>
|
||||
|
||||
<ul>
|
||||
<li>Basic template syntax (variables, expressions)</li>
|
||||
<li>Control structures (if, for)</li>
|
||||
<li>Template inheritance</li>
|
||||
<li>Filters and macros</li>
|
||||
<li>Loading templates from files</li>
|
||||
</ul>
|
||||
|
||||
<h2>Step 1: Basic Templates</h2>
|
||||
|
||||
<p>Create a file called <code>template_demo.wren</code>:</p>
|
||||
|
||||
<pre><code>import "jinja" for Environment, DictLoader
|
||||
|
||||
var env = Environment.new(DictLoader.new({
|
||||
"greeting": "Hello, {{ name }}!"
|
||||
}))
|
||||
|
||||
var template = env.getTemplate("greeting")
|
||||
var result = template.render({"name": "World"})
|
||||
|
||||
System.print(result) // Hello, World!</code></pre>
|
||||
|
||||
<h2>Step 2: Variables and Expressions</h2>
|
||||
|
||||
<p>Jinja supports various expressions inside <code>{{ }}</code>:</p>
|
||||
|
||||
<pre><code>import "jinja" for Environment, DictLoader
|
||||
|
||||
var templates = {
|
||||
"expressions": "
|
||||
Name: {{ user.name }}
|
||||
Age: {{ user.age }}
|
||||
Adult: {{ user.age >= 18 }}
|
||||
Items: {{ items | length }}
|
||||
First: {{ items[0] }}
|
||||
Upper: {{ user.name | upper }}
|
||||
"
|
||||
}
|
||||
|
||||
var env = Environment.new(DictLoader.new(templates))
|
||||
var template = env.getTemplate("expressions")
|
||||
|
||||
var result = template.render({
|
||||
"user": {"name": "Alice", "age": 25},
|
||||
"items": ["apple", "banana", "cherry"]
|
||||
})
|
||||
|
||||
System.print(result)</code></pre>
|
||||
|
||||
<p>Output:</p>
|
||||
<pre><code>Name: Alice
|
||||
Age: 25
|
||||
Adult: true
|
||||
Items: 3
|
||||
First: apple
|
||||
Upper: ALICE</code></pre>
|
||||
|
||||
<h2>Step 3: Control Structures</h2>
|
||||
|
||||
<h3>Conditionals</h3>
|
||||
|
||||
<pre><code>import "jinja" for Environment, DictLoader
|
||||
|
||||
var templates = {
|
||||
"status": "
|
||||
{% if user.active %}
|
||||
User {{ user.name }} is active.
|
||||
{% elif user.pending %}
|
||||
User {{ user.name }} is pending approval.
|
||||
{% else %}
|
||||
User {{ user.name }} is inactive.
|
||||
{% endif %}
|
||||
"
|
||||
}
|
||||
|
||||
var env = Environment.new(DictLoader.new(templates))
|
||||
var template = env.getTemplate("status")
|
||||
|
||||
System.print(template.render({"user": {"name": "Bob", "active": true}}))
|
||||
System.print(template.render({"user": {"name": "Carol", "pending": true}}))
|
||||
System.print(template.render({"user": {"name": "Dave", "active": false}}))</code></pre>
|
||||
|
||||
<h3>Loops</h3>
|
||||
|
||||
<pre><code>import "jinja" for Environment, DictLoader
|
||||
|
||||
var templates = {
|
||||
"list": "
|
||||
Shopping List:
|
||||
{% for item in items %}
|
||||
- {{ item.name }}: ${{ item.price }}
|
||||
{% endfor %}
|
||||
|
||||
Total items: {{ items | length }}
|
||||
"
|
||||
}
|
||||
|
||||
var env = Environment.new(DictLoader.new(templates))
|
||||
var template = env.getTemplate("list")
|
||||
|
||||
var result = template.render({
|
||||
"items": [
|
||||
{"name": "Apples", "price": 2.99},
|
||||
{"name": "Bread", "price": 3.50},
|
||||
{"name": "Milk", "price": 4.25}
|
||||
]
|
||||
})
|
||||
|
||||
System.print(result)</code></pre>
|
||||
|
||||
<h3>Loop Variables</h3>
|
||||
|
||||
<pre><code>import "jinja" for Environment, DictLoader
|
||||
|
||||
var templates = {
|
||||
"numbered": "
|
||||
{% for item in items %}
|
||||
{{ loop.index }}. {{ item }}{% if loop.first %} (first){% endif %}{% if loop.last %} (last){% endif %}
|
||||
{% endfor %}
|
||||
"
|
||||
}
|
||||
|
||||
var env = Environment.new(DictLoader.new(templates))
|
||||
var template = env.getTemplate("numbered")
|
||||
|
||||
var result = template.render({
|
||||
"items": ["Red", "Green", "Blue"]
|
||||
})
|
||||
|
||||
System.print(result)</code></pre>
|
||||
|
||||
<p>Output:</p>
|
||||
<pre><code>1. Red (first)
|
||||
2. Green
|
||||
3. Blue (last)</code></pre>
|
||||
|
||||
<h2>Step 4: Filters</h2>
|
||||
|
||||
<p>Filters transform values using the pipe (<code>|</code>) syntax:</p>
|
||||
|
||||
<pre><code>import "jinja" for Environment, DictLoader
|
||||
|
||||
var templates = {
|
||||
"filters": "
|
||||
{{ name | upper }}
|
||||
{{ name | lower }}
|
||||
{{ name | capitalize }}
|
||||
{{ name | title }}
|
||||
{{ price | round(2) }}
|
||||
{{ items | join(', ') }}
|
||||
{{ text | truncate(20) }}
|
||||
{{ html | escape }}
|
||||
{{ value | default('N/A') }}
|
||||
"
|
||||
}
|
||||
|
||||
var env = Environment.new(DictLoader.new(templates))
|
||||
var template = env.getTemplate("filters")
|
||||
|
||||
var result = template.render({
|
||||
"name": "hELLo WoRLD",
|
||||
"price": 19.99567,
|
||||
"items": ["a", "b", "c"],
|
||||
"text": "This is a very long string that should be truncated",
|
||||
"html": "<script>alert('xss')</script>",
|
||||
"value": null
|
||||
})
|
||||
|
||||
System.print(result)</code></pre>
|
||||
|
||||
<h2>Step 5: Template Inheritance</h2>
|
||||
|
||||
<p>Template inheritance allows you to build a base template with common structure:</p>
|
||||
|
||||
<pre><code>import "jinja" for Environment, DictLoader
|
||||
|
||||
var templates = {
|
||||
"base.html": "
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>{% block title %}My Site{% endblock %}</title>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<nav>Home | About | Contact</nav>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
Copyright 2024
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
",
|
||||
|
||||
"home.html": "
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block title %}Home - My Site{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Welcome!</h1>
|
||||
<p>This is the home page.</p>
|
||||
{% endblock %}
|
||||
",
|
||||
|
||||
"about.html": "
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block title %}About - My Site{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>About Us</h1>
|
||||
<p>{{ description }}</p>
|
||||
{% endblock %}
|
||||
"
|
||||
}
|
||||
|
||||
var env = Environment.new(DictLoader.new(templates))
|
||||
|
||||
System.print("=== Home Page ===")
|
||||
System.print(env.getTemplate("home.html").render({}))
|
||||
|
||||
System.print("\n=== About Page ===")
|
||||
System.print(env.getTemplate("about.html").render({
|
||||
"description": "We are a software company."
|
||||
}))</code></pre>
|
||||
|
||||
<h2>Step 6: Macros</h2>
|
||||
|
||||
<p>Macros are reusable template functions:</p>
|
||||
|
||||
<pre><code>import "jinja" for Environment, DictLoader
|
||||
|
||||
var templates = {
|
||||
"forms": "
|
||||
{% macro input(name, type='text', value='', placeholder='') %}
|
||||
<input type=\"{{ type }}\" name=\"{{ name }}\" value=\"{{ value }}\" placeholder=\"{{ placeholder }}\">
|
||||
{% endmacro %}
|
||||
|
||||
{% macro button(text, type='button', class='btn') %}
|
||||
<button type=\"{{ type }}\" class=\"{{ class }}\">{{ text }}</button>
|
||||
{% endmacro %}
|
||||
|
||||
<form>
|
||||
{{ input('username', placeholder='Enter username') }}
|
||||
{{ input('password', type='password', placeholder='Enter password') }}
|
||||
{{ button('Login', type='submit', class='btn btn-primary') }}
|
||||
</form>
|
||||
"
|
||||
}
|
||||
|
||||
var env = Environment.new(DictLoader.new(templates))
|
||||
var result = env.getTemplate("forms").render({})
|
||||
|
||||
System.print(result)</code></pre>
|
||||
|
||||
<h2>Step 7: Loading Templates from Files</h2>
|
||||
|
||||
<p>For larger projects, store templates in files:</p>
|
||||
|
||||
<pre><code>import "jinja" for Environment, FileSystemLoader
|
||||
import "io" for File
|
||||
|
||||
File.write("templates/base.html", "
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>{% block title %}{% endblock %}</title>
|
||||
</head>
|
||||
<body>
|
||||
{% block content %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
")
|
||||
|
||||
File.write("templates/page.html", "
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block title %}{{ title }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>{{ title }}</h1>
|
||||
{{ content }}
|
||||
{% endblock %}
|
||||
")
|
||||
|
||||
var env = Environment.new(FileSystemLoader.new("templates"))
|
||||
var template = env.getTemplate("page.html")
|
||||
|
||||
var html = template.render({
|
||||
"title": "My Page",
|
||||
"content": "<p>Hello from a file-based template!</p>"
|
||||
})
|
||||
|
||||
System.print(html)</code></pre>
|
||||
|
||||
<h2>Step 8: Building a Report Generator</h2>
|
||||
|
||||
<p>Let's build a practical example - generating HTML reports:</p>
|
||||
|
||||
<pre><code>import "jinja" for Environment, DictLoader
|
||||
import "io" for File
|
||||
import "sqlite" for Sqlite
|
||||
import "datetime" for DateTime
|
||||
|
||||
class ReportGenerator {
|
||||
construct new() {
|
||||
_env = Environment.new(DictLoader.new({
|
||||
"report": "
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>{{ title }}</title>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; margin: 40px; }
|
||||
h1 { color: #333; }
|
||||
table { border-collapse: collapse; width: 100\%; }
|
||||
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
|
||||
th { background-color: #4CAF50; color: white; }
|
||||
tr:nth-child(even) { background-color: #f2f2f2; }
|
||||
.summary { background: #f9f9f9; padding: 20px; margin: 20px 0; }
|
||||
.footer { margin-top: 40px; color: #666; font-size: 12px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>{{ title }}</h1>
|
||||
<p>Generated: {{ generated_at }}</p>
|
||||
|
||||
<div class=\"summary\">
|
||||
<h2>Summary</h2>
|
||||
<p>Total Records: {{ data | length }}</p>
|
||||
{% if total %}
|
||||
<p>Total Amount: ${{ total | round(2) }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<h2>Details</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
{% for header in headers %}
|
||||
<th>{{ header }}</th>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in data %}
|
||||
<tr>
|
||||
{% for header in headers %}
|
||||
<td>{{ row[header] }}</td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class=\"footer\">
|
||||
Report generated by Wren-CLI Report Generator
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"
|
||||
}))
|
||||
}
|
||||
|
||||
generate(title, headers, data, options) {
|
||||
var template = _env.getTemplate("report")
|
||||
|
||||
var total = null
|
||||
if (options && options["sumColumn"]) {
|
||||
total = 0
|
||||
for (row in data) {
|
||||
total = total + (row[options["sumColumn"]] || 0)
|
||||
}
|
||||
}
|
||||
|
||||
return template.render({
|
||||
"title": title,
|
||||
"headers": headers,
|
||||
"data": data,
|
||||
"total": total,
|
||||
"generated_at": DateTime.now().toString
|
||||
})
|
||||
}
|
||||
|
||||
save(filename, html) {
|
||||
File.write(filename, html)
|
||||
System.print("Report saved to %(filename)")
|
||||
}
|
||||
}
|
||||
|
||||
var generator = ReportGenerator.new()
|
||||
|
||||
var salesData = [
|
||||
{"Product": "Widget A", "Quantity": 150, "Price": 29.99, "Total": 4498.50},
|
||||
{"Product": "Widget B", "Quantity": 75, "Price": 49.99, "Total": 3749.25},
|
||||
{"Product": "Widget C", "Quantity": 200, "Price": 19.99, "Total": 3998.00},
|
||||
{"Product": "Widget D", "Quantity": 50, "Price": 99.99, "Total": 4999.50}
|
||||
]
|
||||
|
||||
var html = generator.generate(
|
||||
"Sales Report Q4 2024",
|
||||
["Product", "Quantity", "Price", "Total"],
|
||||
salesData,
|
||||
{"sumColumn": "Total"}
|
||||
)
|
||||
|
||||
generator.save("sales_report.html", html)
|
||||
System.print("Report generated successfully!")</code></pre>
|
||||
|
||||
<h2>Step 9: Email Templates</h2>
|
||||
|
||||
<p>Create personalized emails with templates:</p>
|
||||
|
||||
<pre><code>import "jinja" for Environment, DictLoader
|
||||
|
||||
class EmailGenerator {
|
||||
construct new() {
|
||||
_env = Environment.new(DictLoader.new({
|
||||
"welcome": "
|
||||
Subject: Welcome to {{ company }}, {{ user.name }}!
|
||||
|
||||
Dear {{ user.name }},
|
||||
|
||||
Thank you for joining {{ company }}! We are excited to have you.
|
||||
|
||||
Your account details:
|
||||
- Username: {{ user.username }}
|
||||
- Email: {{ user.email }}
|
||||
- Plan: {{ user.plan | default('Free') }}
|
||||
|
||||
{% if user.plan == 'Premium' %}
|
||||
As a Premium member, you have access to:
|
||||
{% for feature in premium_features %}
|
||||
- {{ feature }}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
If you have any questions, please contact us at {{ support_email }}.
|
||||
|
||||
Best regards,
|
||||
The {{ company }} Team
|
||||
",
|
||||
|
||||
"order_confirmation": "
|
||||
Subject: Order #{{ order.id }} Confirmed
|
||||
|
||||
Dear {{ customer.name }},
|
||||
|
||||
Thank you for your order!
|
||||
|
||||
Order Details:
|
||||
{% for item in order.items %}
|
||||
- {{ item.name }} x {{ item.quantity }} @ ${{ item.price }} = ${{ item.total }}
|
||||
{% endfor %}
|
||||
|
||||
Subtotal: ${{ order.subtotal | round(2) }}
|
||||
Tax: ${{ order.tax | round(2) }}
|
||||
Total: ${{ order.total | round(2) }}
|
||||
|
||||
Shipping to:
|
||||
{{ customer.address.street }}
|
||||
{{ customer.address.city }}, {{ customer.address.state }} {{ customer.address.zip }}
|
||||
|
||||
Estimated delivery: {{ delivery_date }}
|
||||
|
||||
Thank you for shopping with us!
|
||||
"
|
||||
}))
|
||||
}
|
||||
|
||||
welcome(user, company) {
|
||||
return _env.getTemplate("welcome").render({
|
||||
"user": user,
|
||||
"company": company,
|
||||
"support_email": "support@%(company.lower).com",
|
||||
"premium_features": [
|
||||
"Unlimited storage",
|
||||
"Priority support",
|
||||
"Advanced analytics",
|
||||
"Custom integrations"
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
orderConfirmation(customer, order) {
|
||||
return _env.getTemplate("order_confirmation").render({
|
||||
"customer": customer,
|
||||
"order": order,
|
||||
"delivery_date": "3-5 business days"
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var emails = EmailGenerator.new()
|
||||
|
||||
var welcomeEmail = emails.welcome(
|
||||
{
|
||||
"name": "Alice Smith",
|
||||
"username": "alice",
|
||||
"email": "alice@example.com",
|
||||
"plan": "Premium"
|
||||
},
|
||||
"Acme Corp"
|
||||
)
|
||||
|
||||
System.print(welcomeEmail)
|
||||
|
||||
System.print("\n---\n")
|
||||
|
||||
var orderEmail = emails.orderConfirmation(
|
||||
{
|
||||
"name": "Bob Jones",
|
||||
"address": {
|
||||
"street": "123 Main St",
|
||||
"city": "Springfield",
|
||||
"state": "IL",
|
||||
"zip": "62701"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ORD-12345",
|
||||
"items": [
|
||||
{"name": "Blue Widget", "quantity": 2, "price": 29.99, "total": 59.98},
|
||||
{"name": "Red Gadget", "quantity": 1, "price": 49.99, "total": 49.99}
|
||||
],
|
||||
"subtotal": 109.97,
|
||||
"tax": 9.90,
|
||||
"total": 119.87
|
||||
}
|
||||
)
|
||||
|
||||
System.print(orderEmail)</code></pre>
|
||||
|
||||
<div class="admonition tip">
|
||||
<div class="admonition-title">Tip</div>
|
||||
<p>Use the <code>escape</code> filter on user-provided content to prevent XSS attacks in HTML output: <code>{{ user_input | escape }}</code></p>
|
||||
</div>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>Jinja whitespace can be controlled with <code>{%-</code> and <code>-%}</code> to strip whitespace before or after tags.</p>
|
||||
</div>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<ul>
|
||||
<li>Explore all <a href="../api/jinja.html">Jinja filters and features</a></li>
|
||||
<li>Combine with <a href="database-app.html">database queries</a> for dynamic reports</li>
|
||||
<li>Build a <a href="cli-tool.html">CLI tool</a> for template processing</li>
|
||||
</ul>
|
||||
{% endraw %}
|
||||
{% endblock %}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,526 @@
|
||||
{# retoor <retoor@molodetz.nl> #}
|
||||
{% extends 'page.html' %}
|
||||
|
||||
{% set page_title = "WebSocket Chat Application" %}
|
||||
{% set breadcrumb = [{"url": "tutorials/index.html", "title": "Tutorials"}, {"title": "WebSocket Chat"}] %}
|
||||
{% set prev_page = {"url": "tutorials/http-client.html", "title": "HTTP Client"} %}
|
||||
{% set next_page = {"url": "tutorials/database-app.html", "title": "Database App"} %}
|
||||
|
||||
{% block article %}
|
||||
<h1>WebSocket Chat Application</h1>
|
||||
|
||||
<p>In this tutorial, you will build a real-time chat application using WebSockets. You will create both a server that handles multiple clients and a client that can send and receive messages.</p>
|
||||
|
||||
<h2>What You Will Learn</h2>
|
||||
|
||||
<ul>
|
||||
<li>Creating a WebSocket server</li>
|
||||
<li>Handling multiple client connections</li>
|
||||
<li>Broadcasting messages to all clients</li>
|
||||
<li>Building a WebSocket client</li>
|
||||
<li>Working with fibers for concurrent operations</li>
|
||||
</ul>
|
||||
|
||||
<h2>Part 1: The Chat Server</h2>
|
||||
|
||||
<h3>Step 1: Basic Server Setup</h3>
|
||||
|
||||
<p>Create a file called <code>chat_server.wren</code>:</p>
|
||||
|
||||
<pre><code>import "websocket" for WebSocketServer
|
||||
import "json" for Json
|
||||
|
||||
System.print("Starting chat server on port 8080...")
|
||||
|
||||
var server = WebSocketServer.new("0.0.0.0", 8080)
|
||||
var clients = []
|
||||
|
||||
while (true) {
|
||||
var client = server.accept()
|
||||
System.print("Client connected!")
|
||||
clients.add(client)
|
||||
}</code></pre>
|
||||
|
||||
<h3>Step 2: Handling Client Messages</h3>
|
||||
|
||||
<p>Now let's process messages from clients using fibers:</p>
|
||||
|
||||
<pre><code>import "websocket" for WebSocketServer, WebSocketMessage
|
||||
import "json" for Json
|
||||
|
||||
System.print("Starting chat server on port 8080...")
|
||||
|
||||
var server = WebSocketServer.new("0.0.0.0", 8080)
|
||||
var clients = []
|
||||
|
||||
var handleClient = Fn.new { |client|
|
||||
while (true) {
|
||||
var message = client.receive()
|
||||
|
||||
if (message == null) {
|
||||
System.print("Client disconnected")
|
||||
break
|
||||
}
|
||||
|
||||
if (message.opcode == WebSocketMessage.TEXT) {
|
||||
System.print("Received: %(message.payload)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (true) {
|
||||
var client = server.accept()
|
||||
System.print("Client connected!")
|
||||
clients.add(client)
|
||||
|
||||
var fiber = Fiber.new { handleClient.call(client) }
|
||||
fiber.call()
|
||||
}</code></pre>
|
||||
|
||||
<h3>Step 3: Broadcasting Messages</h3>
|
||||
|
||||
<p>Let's broadcast messages to all connected clients:</p>
|
||||
|
||||
<pre><code>import "websocket" for WebSocketServer, WebSocketMessage
|
||||
import "json" for Json
|
||||
|
||||
System.print("=== Chat Server ===")
|
||||
System.print("Listening on ws://0.0.0.0:8080")
|
||||
|
||||
var server = WebSocketServer.new("0.0.0.0", 8080)
|
||||
var clients = []
|
||||
|
||||
var broadcast = Fn.new { |message, sender|
|
||||
var data = Json.stringify({
|
||||
"type": "message",
|
||||
"from": sender,
|
||||
"text": message
|
||||
})
|
||||
|
||||
for (client in clients) {
|
||||
var fiber = Fiber.new { client.send(data) }
|
||||
fiber.try()
|
||||
}
|
||||
}
|
||||
|
||||
var removeClient = Fn.new { |client|
|
||||
var index = clients.indexOf(client)
|
||||
if (index >= 0) {
|
||||
clients.removeAt(index)
|
||||
}
|
||||
}
|
||||
|
||||
var handleClient = Fn.new { |client, clientId|
|
||||
client.send(Json.stringify({
|
||||
"type": "welcome",
|
||||
"message": "Welcome to the chat!",
|
||||
"clientId": clientId
|
||||
}))
|
||||
|
||||
broadcast.call("%(clientId) joined the chat", "System")
|
||||
|
||||
while (true) {
|
||||
var message = client.receive()
|
||||
|
||||
if (message == null) {
|
||||
System.print("Client %(clientId) disconnected")
|
||||
removeClient.call(client)
|
||||
broadcast.call("%(clientId) left the chat", "System")
|
||||
break
|
||||
}
|
||||
|
||||
if (message.opcode == WebSocketMessage.TEXT) {
|
||||
var data = Json.parse(message.payload)
|
||||
System.print("[%(clientId)] %(data["text"])")
|
||||
broadcast.call(data["text"], clientId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var clientCounter = 0
|
||||
|
||||
while (true) {
|
||||
var client = server.accept()
|
||||
clientCounter = clientCounter + 1
|
||||
var clientId = "User%(clientCounter)"
|
||||
|
||||
System.print("%(clientId) connected")
|
||||
clients.add(client)
|
||||
|
||||
Fiber.new { handleClient.call(client, clientId) }.call()
|
||||
}</code></pre>
|
||||
|
||||
<h2>Part 2: The Chat Client</h2>
|
||||
|
||||
<h3>Step 4: Basic Client</h3>
|
||||
|
||||
<p>Create a file called <code>chat_client.wren</code>:</p>
|
||||
|
||||
<pre><code>import "websocket" for WebSocket, WebSocketMessage
|
||||
import "json" for Json
|
||||
import "io" for Stdin
|
||||
|
||||
System.print("Connecting to chat server...")
|
||||
|
||||
var ws = WebSocket.connect("ws://localhost:8080")
|
||||
System.print("Connected!")
|
||||
|
||||
var receiveMessages = Fn.new {
|
||||
while (true) {
|
||||
var message = ws.receive()
|
||||
|
||||
if (message == null) {
|
||||
System.print("Disconnected from server")
|
||||
break
|
||||
}
|
||||
|
||||
if (message.opcode == WebSocketMessage.TEXT) {
|
||||
var data = Json.parse(message.payload)
|
||||
|
||||
if (data["type"] == "welcome") {
|
||||
System.print("\n%(data["message"])")
|
||||
System.print("You are: %(data["clientId"])\n")
|
||||
} else if (data["type"] == "message") {
|
||||
System.print("[%(data["from"])] %(data["text"])")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Fiber.new { receiveMessages.call() }.call()
|
||||
|
||||
System.print("Type messages and press Enter to send. Type 'quit' to exit.\n")
|
||||
|
||||
while (true) {
|
||||
System.write("> ")
|
||||
var input = Stdin.readLine()
|
||||
|
||||
if (input == "quit") {
|
||||
ws.close()
|
||||
break
|
||||
}
|
||||
|
||||
if (input.count > 0) {
|
||||
ws.send(Json.stringify({"text": input}))
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h2>Part 3: Enhanced Features</h2>
|
||||
|
||||
<h3>Step 5: Private Messages</h3>
|
||||
|
||||
<p>Add support for private messages with the <code>/msg</code> command:</p>
|
||||
|
||||
<pre><code>import "websocket" for WebSocketServer, WebSocketMessage
|
||||
import "json" for Json
|
||||
import "regex" for Regex
|
||||
|
||||
System.print("=== Enhanced Chat Server ===")
|
||||
System.print("Listening on ws://0.0.0.0:8080")
|
||||
|
||||
var server = WebSocketServer.new("0.0.0.0", 8080)
|
||||
var clients = {}
|
||||
|
||||
var broadcast = Fn.new { |type, data|
|
||||
var message = Json.stringify({"type": type}.merge(data))
|
||||
for (id in clients.keys) {
|
||||
var fiber = Fiber.new { clients[id].send(message) }
|
||||
fiber.try()
|
||||
}
|
||||
}
|
||||
|
||||
var sendTo = Fn.new { |clientId, type, data|
|
||||
if (clients.containsKey(clientId)) {
|
||||
var message = Json.stringify({"type": type}.merge(data))
|
||||
clients[clientId].send(message)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var handleCommand = Fn.new { |client, clientId, text|
|
||||
var msgMatch = Regex.new("^/msg (\\w+) (.+)$").match(text)
|
||||
if (msgMatch) {
|
||||
var target = msgMatch.group(1)
|
||||
var message = msgMatch.group(2)
|
||||
|
||||
if (sendTo.call(target, "private", {"from": clientId, "text": message})) {
|
||||
sendTo.call(clientId, "private", {"from": "You -> %(target)", "text": message})
|
||||
} else {
|
||||
sendTo.call(clientId, "error", {"message": "User %(target) not found"})
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
if (text == "/users") {
|
||||
var userList = clients.keys.toList.join(", ")
|
||||
sendTo.call(clientId, "info", {"message": "Online users: %(userList)"})
|
||||
return true
|
||||
}
|
||||
|
||||
if (text == "/help") {
|
||||
sendTo.call(clientId, "info", {
|
||||
"message": "Commands: /msg <user> <message>, /users, /help"
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
var handleClient = Fn.new { |client, clientId|
|
||||
client.send(Json.stringify({
|
||||
"type": "welcome",
|
||||
"clientId": clientId
|
||||
}))
|
||||
|
||||
broadcast.call("join", {"user": clientId})
|
||||
|
||||
while (true) {
|
||||
var message = client.receive()
|
||||
|
||||
if (message == null) {
|
||||
clients.remove(clientId)
|
||||
broadcast.call("leave", {"user": clientId})
|
||||
System.print("%(clientId) disconnected")
|
||||
break
|
||||
}
|
||||
|
||||
if (message.opcode == WebSocketMessage.TEXT) {
|
||||
var data = Json.parse(message.payload)
|
||||
var text = data["text"]
|
||||
|
||||
if (!handleCommand.call(client, clientId, text)) {
|
||||
broadcast.call("message", {"from": clientId, "text": text})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var clientCounter = 0
|
||||
|
||||
while (true) {
|
||||
var client = server.accept()
|
||||
clientCounter = clientCounter + 1
|
||||
var clientId = "User%(clientCounter)"
|
||||
|
||||
System.print("%(clientId) connected")
|
||||
clients[clientId] = client
|
||||
|
||||
Fiber.new { handleClient.call(client, clientId) }.call()
|
||||
}</code></pre>
|
||||
|
||||
<h3>Step 6: Enhanced Client</h3>
|
||||
|
||||
<p>Update the client to handle new message types:</p>
|
||||
|
||||
<pre><code>import "websocket" for WebSocket, WebSocketMessage
|
||||
import "json" for Json
|
||||
import "io" for Stdin
|
||||
|
||||
System.print("Connecting to chat server...")
|
||||
|
||||
var ws = WebSocket.connect("ws://localhost:8080")
|
||||
var myId = ""
|
||||
|
||||
var receiveMessages = Fn.new {
|
||||
while (true) {
|
||||
var message = ws.receive()
|
||||
|
||||
if (message == null) {
|
||||
System.print("\nDisconnected from server")
|
||||
break
|
||||
}
|
||||
|
||||
if (message.opcode == WebSocketMessage.TEXT) {
|
||||
var data = Json.parse(message.payload)
|
||||
|
||||
if (data["type"] == "welcome") {
|
||||
myId = data["clientId"]
|
||||
System.print("Connected as %(myId)")
|
||||
System.print("Type /help for commands\n")
|
||||
} else if (data["type"] == "message") {
|
||||
System.print("[%(data["from"])] %(data["text"])")
|
||||
} else if (data["type"] == "private") {
|
||||
System.print("[PM %(data["from"])] %(data["text"])")
|
||||
} else if (data["type"] == "join") {
|
||||
System.print("* %(data["user"]) joined the chat")
|
||||
} else if (data["type"] == "leave") {
|
||||
System.print("* %(data["user"]) left the chat")
|
||||
} else if (data["type"] == "info") {
|
||||
System.print("INFO: %(data["message"])")
|
||||
} else if (data["type"] == "error") {
|
||||
System.print("ERROR: %(data["message"])")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Fiber.new { receiveMessages.call() }.call()
|
||||
|
||||
while (true) {
|
||||
var input = Stdin.readLine()
|
||||
|
||||
if (input == null || input == "/quit") {
|
||||
ws.close()
|
||||
break
|
||||
}
|
||||
|
||||
if (input.count > 0) {
|
||||
ws.send(Json.stringify({"text": input}))
|
||||
}
|
||||
}</code></pre>
|
||||
|
||||
<h2>Part 4: Running the Application</h2>
|
||||
|
||||
<h3>Starting the Server</h3>
|
||||
|
||||
<pre><code>$ wren_cli chat_server.wren
|
||||
=== Enhanced Chat Server ===
|
||||
Listening on ws://0.0.0.0:8080</code></pre>
|
||||
|
||||
<h3>Connecting Clients</h3>
|
||||
|
||||
<p>Open multiple terminals and run:</p>
|
||||
|
||||
<pre><code>$ wren_cli chat_client.wren
|
||||
Connecting to chat server...
|
||||
Connected as User1
|
||||
Type /help for commands
|
||||
|
||||
> Hello everyone!
|
||||
[User1] Hello everyone!
|
||||
* User2 joined the chat
|
||||
[User2] Hi there!
|
||||
> /msg User2 This is a private message
|
||||
[PM You -> User2] This is a private message</code></pre>
|
||||
|
||||
<h2>Complete Server Code</h2>
|
||||
|
||||
<pre><code>import "websocket" for WebSocketServer, WebSocketMessage
|
||||
import "json" for Json
|
||||
import "regex" for Regex
|
||||
import "datetime" for DateTime
|
||||
|
||||
class ChatServer {
|
||||
construct new(host, port) {
|
||||
_server = WebSocketServer.new(host, port)
|
||||
_clients = {}
|
||||
_messageHistory = []
|
||||
_maxHistory = 100
|
||||
}
|
||||
|
||||
broadcast(type, data) {
|
||||
var message = Json.stringify({"type": type, "timestamp": DateTime.now().toString}.merge(data))
|
||||
for (id in _clients.keys) {
|
||||
var fiber = Fiber.new { _clients[id].send(message) }
|
||||
fiber.try()
|
||||
}
|
||||
}
|
||||
|
||||
sendTo(clientId, type, data) {
|
||||
if (_clients.containsKey(clientId)) {
|
||||
var message = Json.stringify({"type": type}.merge(data))
|
||||
_clients[clientId].send(message)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
handleCommand(client, clientId, text) {
|
||||
if (text.startsWith("/msg ")) {
|
||||
var parts = text[5..-1].split(" ")
|
||||
if (parts.count >= 2) {
|
||||
var target = parts[0]
|
||||
var message = parts[1..-1].join(" ")
|
||||
|
||||
if (sendTo(target, "private", {"from": clientId, "text": message})) {
|
||||
sendTo(clientId, "private", {"from": "You -> %(target)", "text": message})
|
||||
} else {
|
||||
sendTo(clientId, "error", {"message": "User not found"})
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
if (text == "/users") {
|
||||
sendTo(clientId, "info", {"message": "Online: %(_clients.keys.toList.join(", "))"})
|
||||
return true
|
||||
}
|
||||
|
||||
if (text == "/help") {
|
||||
sendTo(clientId, "info", {"message": "/msg <user> <text>, /users, /help, /quit"})
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
handleClient(client, clientId) {
|
||||
_clients[clientId] = client
|
||||
|
||||
sendTo(clientId, "welcome", {"clientId": clientId, "users": _clients.keys.toList})
|
||||
broadcast("join", {"user": clientId})
|
||||
|
||||
while (true) {
|
||||
var message = client.receive()
|
||||
|
||||
if (message == null) {
|
||||
_clients.remove(clientId)
|
||||
broadcast("leave", {"user": clientId})
|
||||
System.print("[%(DateTime.now())] %(clientId) disconnected")
|
||||
break
|
||||
}
|
||||
|
||||
if (message.opcode == WebSocketMessage.TEXT) {
|
||||
var data = Json.parse(message.payload)
|
||||
var text = data["text"]
|
||||
|
||||
if (!handleCommand(client, clientId, text)) {
|
||||
System.print("[%(DateTime.now())] %(clientId): %(text)")
|
||||
broadcast("message", {"from": clientId, "text": text})
|
||||
|
||||
_messageHistory.add({"from": clientId, "text": text, "time": DateTime.now().toString})
|
||||
if (_messageHistory.count > _maxHistory) {
|
||||
_messageHistory.removeAt(0)
|
||||
}
|
||||
}
|
||||
} else if (message.opcode == WebSocketMessage.PING) {
|
||||
client.pong(message.payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
run() {
|
||||
System.print("Chat server running on port 8080")
|
||||
var counter = 0
|
||||
|
||||
while (true) {
|
||||
var client = _server.accept()
|
||||
counter = counter + 1
|
||||
var clientId = "User%(counter)"
|
||||
|
||||
System.print("[%(DateTime.now())] %(clientId) connected")
|
||||
|
||||
Fiber.new { handleClient(client, clientId) }.call()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var server = ChatServer.new("0.0.0.0", 8080)
|
||||
server.run()</code></pre>
|
||||
|
||||
<div class="admonition note">
|
||||
<div class="admonition-title">Note</div>
|
||||
<p>WebSocket connections in Wren-CLI use fibers for concurrent handling. Each client runs in its own fiber, allowing the server to handle multiple connections simultaneously.</p>
|
||||
</div>
|
||||
|
||||
<h2>Next Steps</h2>
|
||||
|
||||
<ul>
|
||||
<li>Add user authentication</li>
|
||||
<li>Store message history in <a href="database-app.html">SQLite</a></li>
|
||||
<li>Create chat rooms</li>
|
||||
<li>See the <a href="../api/websocket.html">WebSocket API reference</a></li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
Reference in New Issue
Block a user