Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Foy
https://github.com/zaaack/foy
Admin
Foy is a simple, light-weight and modern task runner for general purpose.
Tokens:
28,564
Snippets:
249
Trust Score:
8.7
License:
MIT
Update:
4 months ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install Foy Globally Source: https://github.com/zaaack/foy/blob/main/README.md Install Foy globally on your system for command-line access. ```sh yarn add -g foy # or npm i -g foy ``` -------------------------------- ### Basic Foyfile.js Example Source: https://github.com/zaaack/foy/blob/main/README.md A minimal Foyfile.js defining a 'build' task that executes 'tsc'. ```js // Foyfile.js const { task } = require('foy') task('build', async ctx => { await ctx.exec('tsc') }) ``` -------------------------------- ### Running Foy with Custom Compilers Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html Provides examples for executing Foy tasks using custom compilers like TypeScript or CoffeeScript via command-line flags. ```bash # Write Foyfile in ts, enabled by default foy -r ts-node/register -c ./some/Foyfile.ts build # Write Foyfile in coffee foy -r coffeescript/register -c ./some/Foyfile.coffee build ``` -------------------------------- ### Set Theme and Initialize App Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/setOption.html Applies a theme from local storage and conditionally displays the application or removes a display:none style after a delay. This snippet is typically used for initial application setup. ```typescript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Install Foy with Yarn or npm Source: https://github.com/zaaack/foy/blob/main/README.md Install Foy as a development dependency using either Yarn or npm. ```sh yarn add -D foy # or npm i -D foy ``` -------------------------------- ### Watch Directory (Simple) Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Starts watching a directory for changes. This version takes the directory path and a callback handler. ```typescript watchDir(dir: string, cb: [WatchDirHandler](../types/WatchDirHandler.html)): _fs.FSWatcher | _fs.FSWatcher[] ``` -------------------------------- ### Using Built-in fs and exec API Source: https://github.com/zaaack/foy/blob/main/docs/index.html Example of using Foy's built-in promised-based API for file system operations and environment variable manipulation. ```javascript import { fs, task } from 'foy' task('some task', async ctx => { await fs.rmrf('/some/dir/or/file') // Remove directory or file await fs.copy('/src', '/dist') // Copy folder or file let json = await fs.readJson('./xx.json') await ctx .env('NODE_ENV', 'production') ``` -------------------------------- ### Watch Directory (with Options) Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Starts watching a directory for changes with custom options. This version takes the directory path, an options object, and a callback handler. ```typescript watchDir(dir: string, options: [WatchDirOptions](../types/WatchDirOptions.html), cb: [WatchDirHandler](../types/WatchDirHandler.html)): _fs.FSWatcher | _fs.FSWatcher[] ``` -------------------------------- ### before(fn) Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/before.html The 'before' function is designed to execute a given function after a delay, potentially showing a page or removing a display style. It's often used for initialization or setup tasks. ```APIDOC ## before(fn) ### Description Executes a provided function `fn` after a short delay. This is typically used for initialization tasks, such as showing a page or applying display styles. ### Parameters #### Parameters - **fn** ((t: [Task](../interfaces/Task.html)<any>) => void | Promise<void>) - The function to execute. It receives a `Task` object as an argument. - **t** ([Task](../interfaces/Task.html)<any>) - A Task object passed to the function. ### Returns - **void** - This function does not return a meaningful value. ### Defined in - src/task.ts:88 ``` -------------------------------- ### Add Before Lifecycle Hook Source: https://github.com/zaaack/foy/blob/main/docs/index.html Execute a function before all tasks in the Foyfile start. This is useful for setup operations that need to run once at the beginning. ```typescript import { before, after, onerror } from 'foy' before(() => { // do something before all tasks tree start // ... }) ``` -------------------------------- ### Monitor Directory for File Changes Source: https://github.com/zaaack/foy/blob/main/docs/api/classes/ShellContext.html Starts monitoring a directory for file changes and restarts specified processes. Supports single commands, arrays of commands, or asynchronous functions for process management. ```typescript ctx.monitor('./src', 'tsc') ctx.monitor('./src', 'webpack') ctx.monitor('./src', 'foy watch') ctx.monitor('./src', ['rm -rf dist', 'foy watch']) ctx.monitor('./src', async p => { await fs.rmrf('dist') p.current = ctx.exec('webpack serve') }) ``` -------------------------------- ### Using Lifecycle Hooks in Foy Source: https://github.com/zaaack/foy/blob/main/README.md Implement `before`, `after`, and `onerror` hooks to execute custom logic before all tasks start, after all tasks finish, or when an error occurs. ```typescript import { before, after, onerror } from 'foy' before(() => { // do something before all tasks tree start // ... }) after(() => { // do something after all tasks tree finished // ... }) onerror((err) => { // do something when error happens // ... }) ``` -------------------------------- ### Execute multiple shell commands Source: https://github.com/zaaack/foy/blob/main/docs/api/classes/ShellContext.html Execute multiple shell commands by providing them as a single multi-line string. Commands will be executed sequentially. This example includes a sleep command. ```typescript await ctx.exec(` echo 1 sleep 1 echo 2`) ``` -------------------------------- ### mkdirpSync Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Synchronously creates a directory and any necessary parent directories, similar to the `mkdir -p` command. ```APIDOC ## mkdirpSync ### Description Make directory with parents, like `mkdir -p`. ### Method Synchronous function call. ### Parameters #### Path Parameters * **dir** (string) - Required - The directory path to create. ### Returns void ``` -------------------------------- ### mkdirp Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Asynchronously creates a directory, including any necessary parent directories. ```APIDOC ## mkdirp ### Description Asynchronously creates a directory, including any necessary parent directories. ### Method `mkdirp(dir: string): Promise<void>` ### Parameters #### Path Parameters - **dir** (string) - Required - The directory path to create. ``` -------------------------------- ### Basic Foy Task with File System Operations Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html Demonstrates basic file system operations like removing directories/files, copying, and reading JSON files within a Foy task. Also shows environment variable setting, changing directories, and executing shell commands. ```javascript import { fs, task } from 'foy' task('some task', async ctx => { await fs.rmrf('/some/dir/or/file') // Remove directory or file await fs.copy('/src', '/dist') // Copy folder or file let json = await fs.readJson('./xx.json') await ctx .env('NODE_ENV', 'production') .env('NODE_ENV=production') .cd('./src') .exec('some command') // Execute an command let { stdout } = await ctx.exec('ls', { stdio: 'pipe' }) // Get the stdout, default is empty because it's redirected to current process via `stdio: 'inherit'`. }) ``` -------------------------------- ### mkdirpSync Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Synchronously creates a directory, including any necessary parent directories. ```APIDOC ## mkdirpSync ### Description Synchronously creates a directory, including any necessary parent directories. ### Method `mkdirpSync(dir: string): void` ### Parameters #### Path Parameters - **dir** (string) - Required - The directory path to create. ``` -------------------------------- ### Generate a Basic Foyfile.js Source: https://github.com/zaaack/foy/blob/main/README.md Create a default Foyfile.js in the current directory using the foy CLI. ```sh foy --init ``` -------------------------------- ### mkdirp Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Recursively creates a directory and any necessary parent directories, similar to the `mkdir -p` command. ```APIDOC ## mkdirp ### Description Make directory with parents, like `mkdir -p`. ### Method Asynchronous function call. ### Parameters #### Path Parameters * **dir** (string) - Required - The directory path to create. ### Returns Promise<void> ``` -------------------------------- ### Watch and Build with File Monitoring Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html Shows how to set up file monitoring to automatically execute a build script when changes are detected in source files. ```typescript task('build', async ctx => { /* build your project */ }) let p = null task('watch', async ctx => { ctx.monitor('./src', async ()=> { ctx.exec('node ./src/server.ts') }) }) ``` -------------------------------- ### File System Operations with Foy Source: https://github.com/zaaack/foy/blob/main/docs/index.html Demonstrates various asynchronous file system operations using Foy's promise-based API, including reading, copying, watching, creating directories, and writing files. ```javascript import { fs } from 'foy' task('build', async ctx => { let f = await fs.readFileSync('./assets/someFile') // copy file or directory await fs.copy('./fromPath', './toPath') // watch a directory await fs.watchDir('./src', (event, filename) => { logger.info(event, filename) }) // make directory with parent directories await fs.mkdirp('./some/directory/with/parents/not/exists') // write file will auto create missing parent directories await fs.outputFile('./some/file/with/parents/not/exists', 'file data') // write json file will auto create missing parent directories await fs.outputJson('./some/file/with/parents/not/exists', {text: 'json data'}) let file = await fs.readJson('./some/jsonFile') // iterate directory tree await fs.iter('./src', async (path, stat) => { if (stat.isDirectory()) { logger.info('directory:', path) // skip scan node_modules if (path.endsWith('node_modules')) { return true } } else if (stat.isFile()) { logger.warn('file:', path) } }) }) ``` -------------------------------- ### Define and Run Namespaced Tasks Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/namespace.html Use the namespace function to create distinct task scopes. This is useful for organizing tasks, especially in larger projects. The example shows how to define 'client' and 'server' namespaces, each with a 'run' task. ```typescript namespace('client', ns => { task('run', async ctx => { logger.log(ns) // 'client' await ctx.exec('<run cmd>') }) }) namespace('server', ns => { task('run', async ctx => { logger.log(ns) // 'server' await ctx.exec('<run cmd>') }) }) ``` ```bash $ yarn foy client:run $ yarn foy server:run ``` -------------------------------- ### Run Task with Watch Option Source: https://github.com/zaaack/foy/blob/main/README.md Execute the 'build' task with the watch flag enabled. ```sh foy build -w ``` -------------------------------- ### exec(cmd, options?) Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/exec.html Executes a command with optional settings. It takes a command string and an optional options object, returning a promise that resolves with the result. ```APIDOC ## exec(cmd, options?) ### Description Executes a command with optional settings. It takes a command string and an optional options object, returning a promise that resolves with the result. ### Parameters #### Path Parameters * **cmd** (string) - Required - The command to execute. * **options** (Options) - Optional - Configuration options for the command execution. ### Returns ResultPromise<Options> ### Source Defined in [src/exec.ts:49](https://github.com/zaaack/foy/blob/c4dd6882eb817f63329120259ac861120d6c168e/src/exec.ts#L49) ``` -------------------------------- ### Foyfile with Task Description and Options Source: https://github.com/zaaack/foy/blob/main/README.md Define a task with a description and a watch option, using strict option validation. ```ts import { task, desc, option, strict } from 'foy' desc('Build ts files with tsc') option('-w, --watch', 'watch file changes') strict() // This will throw an error if you passed some options that doesn't defined via `option()` task('build', async ctx => { await ctx.exec(`tsc ${ctx.options.watch ? '-w' : ''}`) }) ``` -------------------------------- ### option(rawName, description, config?) Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/option.html Defines a task CLI option with a raw name, description, and optional configuration. ```APIDOC ## option(rawName, description, config?) ### Description Define a task cli option. ### Parameters #### Path Parameters * **rawName** (string) - Required - The raw name of the option. * **description** (string) - Required - The description of the option. * **config** (OptionConfig) - Optional - Configuration object for the option. ### Returns void ### Defined in [src/task.ts:118](https://github.com/zaaack/foy/blob/c4dd6882eb817f63329120259ac861120d6c168e/src/task.ts#L118) ``` -------------------------------- ### Run a Foy Task Source: https://github.com/zaaack/foy/blob/main/README.md Execute a task defined in your Foyfile, such as 'build'. ```sh foy build ``` -------------------------------- ### Use Foy's Promise-Based File System Utilities Source: https://github.com/zaaack/foy/blob/main/README.md Leverage Foy's enhanced fs module for asynchronous file operations like reading, copying, watching, and directory manipulation. ```typescript import { fs } from 'foy' task('build', async ctx => { let f = await fs.readFileSync('./assets/someFile') // copy file or directory await fs.copy('./fromPath', './toPath') // watch a directory await fs.watchDir('./src', (event, filename) => { logger.info(event, filename) }) // make directory with parent directories await fs.mkdirp('./some/directory/with/parents/not/exists') // write file will auto create missing parent directories await fs.outputFile('./some/file/with/parents/not/exists', 'file data') // write json file will auto create missing parent directories await fs.outputJson('./some/file/with/parents/not/exists', {text: 'json data'}) let file = await fs.readJson('./some/jsonFile') // iterate directory tree await fs.iter('./src', async (path, stat) => { if (stat.isDirectory()) { logger.info('directory:', path) // skip scan node_modules if (path.endsWith('node_modules')) { return true } } else if (stat.isFile()) { logger.warn('file:', path) } }) }) ``` -------------------------------- ### Watch Files and Rebuild Project Source: https://github.com/zaaack/foy/blob/main/README.md Set up file monitoring using `ctx.monitor` to automatically execute commands, such as rebuilding a project, when changes are detected in specified directories. ```typescript task('build', async ctx => { /* build your project */ }) let p = null task('watch', async ctx => { ctx.monitor('./src', async ()=> { ctx.exec('node ./src/server.ts') }) }) ``` -------------------------------- ### Register Foyfile with CoffeeScript Source: https://github.com/zaaack/foy/blob/main/docs/index.html Use the `-r coffeescript/register` flag to execute Foyfiles written in CoffeeScript. This allows you to leverage CoffeeScript syntax for your build automation. ```bash # Write Foyfile in coffee foy -r coffeescript/register -c ./some/Foyfile.coffee build ``` -------------------------------- ### Monitor Directory for Changes and Execute Command Source: https://github.com/zaaack/foy/blob/main/docs/index.html Use `ctx.monitor` to watch a directory for file changes and execute a command. The first argument is the directory to watch, and the second is the command to run. ```typescript ctx.monitor('./src', 'node ./dist') ``` -------------------------------- ### Using Built-in Promised-based API in a Task Source: https://github.com/zaaack/foy/blob/main/README.md Demonstrates using Foy's built-in fs module for file operations and ctx.exec for commands. ```ts import { fs, task } from 'foy' task('some task', async ctx => { await fs.rmrf('/some/dir/or/file') // Remove directory or file await fs.copy('/src', '/dist') // Copy folder or file let json = await fs.readJson('./xx.json') await ctx .env('NODE_ENV', 'production') .env('NODE_ENV=production') .cd('./src') .exec('some command') // Execute an command let { stdout } = await ctx.exec('ls', { stdio: 'pipe' }) // Get the stdout, default is empty because it's redirected to current process via `stdio: 'inherit'`. }) ``` -------------------------------- ### $<NewOptionsType>(file, options?) Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/_.html Executes a script from a specified file with optional options, returning a promise that resolves to a ResultPromise. This overload is a concise way to execute script files with custom options. ```APIDOC ## $<NewOptionsType>(file, options?) ### Description Executes a script from a specified file with optional options, returning a promise that resolves to a ResultPromise. This overload is a concise way to execute script files with custom options. ### Method Not specified (likely a function call in a JavaScript SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **file** (string | URL) - The path to the script file. * **options** (NewOptionsType) - Optional options for script execution. ### Request Example ```json { "example": "file and options" } ``` ### Response #### Success Response * **ResultPromise<StricterOptions<Options & NewOptionsType, Options>>[]** - A promise resolving to an array of ResultPromise objects with stricter options. #### Response Example ```json { "example": "ResultPromise array with stricter options" } ``` ``` -------------------------------- ### Generate a Foyfile.ts Source: https://github.com/zaaack/foy/blob/main/README.md Create a Foyfile.ts using the foy CLI, useful for TypeScript projects. ```sh foy --init ts ``` -------------------------------- ### $<NewOptionsType>(file, arguments?, options?) Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/_.html Executes a script from a specified file with optional arguments and options, returning a promise that resolves to a ResultPromise. This overload is suitable for executing script files. ```APIDOC ## $<NewOptionsType>(file, arguments?, options?) ### Description Executes a script from a specified file with optional arguments and options, returning a promise that resolves to a ResultPromise. This overload is suitable for executing script files. ### Method Not specified (likely a function call in a JavaScript SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **file** (string | URL) - The path to the script file. * **arguments** (readonly string[]) - Optional arguments to pass to the script. * **options** (NewOptionsType) - Optional options for script execution. ### Request Example ```json { "example": "file, arguments, and options" } ``` ### Response #### Success Response * **ResultPromise<StricterOptions<Options & NewOptionsType, Options>>[]** - A promise resolving to an array of ResultPromise objects with stricter options. #### Response Example ```json { "example": "ResultPromise array with stricter options" } ``` ``` -------------------------------- ### Logging with Foy Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html Shows how to use Foy's built-in logger for different log levels (debug, info, warn, error). Each log level can optionally include additional data, such as objects. ```javascript import { logger } from 'foy' task('build', async ctx => { logger.debug('debug', { aa: 1}) logger.info('info') logger.warn('warn') logger.error('error') }) ``` -------------------------------- ### Foy Namespaced Tasks Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html Demonstrates organizing tasks into namespaces ('client', 'server') and nested namespaces ('client:proj1') to prevent name collisions. Includes before, after, and onerror hooks within namespaces. ```javascript import { task, namespace } from 'foy' namespace('client', ns => { before(() => { logger.info('before') }) after(() => { logger.info('after') }) onerror(() => { logger.info('onerror') }) task('start', async ctx => { /* ... */ }) // client:start task('build', async ctx => { /* ... */ }) // client:build task('watch', async ctx => { /* ... */ }) // client:watch namespace('proj1', ns => { // nested namespace onerror(() => { logger.info('onerror', ns) }) task('start', async ctx => { /* ... */ }) // client:proj1:start }) }) namespace('server', ns => { task('build', async ctx => { /* ... */ }) task('start', async ctx => { /* ... */ }) task('watch', async ctx => { /* ... */ }) }) task('start', [dep('client:start').async(), dep('server:start').async()]) // start // foy start // foy client:build ``` -------------------------------- ### Running Tasks within Tasks Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html Illustrates how to execute one Foy task from within another using `ctx.run`, allowing for sequential task execution with pre/post logic. ```typescript task('task1', async ctx => { /* ... */ }) task('task2', async ctx => { // do things before task1 // run task1 manually, so we can // do things before or after it await ctx.run('task1') // do things after task1 }) ``` -------------------------------- ### Executing Shell Commands with ctx.$ Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html Demonstrates using Foy's `ctx.$` tagged template literal for executing shell commands, including variable interpolation and passing options. Variables are automatically escaped for safe shell execution. ```javascript task('build', async ctx => { // Using ctx.$ (same as standalone $) await ctx.$`tsc` await ctx.$`node ./test.js` // Variable interpolation - values are automatically escaped const file = 'my file.txt' // note the space in filename await ctx.$`cat ${file}` // safely escapes to: cat 'my file.txt' const count = 5 await ctx.$`echo ${count}` // outputs: 5 // Using with options const { stdout } = await ctx.$`ls -la` console.log(stdout) // Complex example with multiple variables const src = './src' const dest = './dist' await ctx.$`cp -r ${src} ${dest}` }) ``` -------------------------------- ### ShellContext Constructor Source: https://github.com/zaaack/foy/blob/main/docs/api/classes/ShellContext.html Initializes a new instance of the ShellContext class. ```APIDOC ## constructor ### Description Initializes a new instance of the ShellContext class. ### Method constructor ### Returns - [ShellContext](ShellContext.html) ``` -------------------------------- ### Execute Multiple Commands Concurrently with ctx.exec and Promise.all Source: https://github.com/zaaack/foy/blob/main/docs/index.html Execute several commands in parallel using `Promise.all` with `ctx.exec`. This is ideal for independent tasks like linting, compiling, and generating documentation. ```typescript await Promise.all([ ctx.exec('eslint'), ctx.exec('tsc'), ctx.exec('typedoc'), ]) ``` -------------------------------- ### Set Up Watch Mode for Development Source: https://github.com/zaaack/foy/blob/main/docs/index.html Implement a watch task that monitors source files and automatically rebuilds or restarts the application on changes. This is crucial for efficient development workflows. ```typescript task('build', async ctx => { /* build your project */ }) let p = null task('watch', async ctx => { ctx.monitor('./src', async ()=> { ctx.exec('node ./src/server.ts') }) }) ``` -------------------------------- ### outputFile Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Asynchronously writes data to a file, creating the file if it does not exist. Supports options. ```APIDOC ## outputFile ### Description Asynchronously writes data to a file, creating the file if it does not exist. Supports options. ### Method `outputFile(path: string, data: any, options?: WriteOptions): Promise<void>` ### Parameters #### Path Parameters - **path** (string) - Required - The file path to write to. - **data** (any) - Required - The data to write to the file. #### Request Body - **options** (WriteOptions) - Optional - Options for writing the file. ``` -------------------------------- ### Highlight.js Initialization Source: https://github.com/zaaack/foy/blob/main/docs-src/index.html Initializes Highlight.js for syntax highlighting on code blocks, specifically targeting TypeScript and shell scripts. ```javascript document.querySelectorAll('pre code').forEach(function(block) { if (block.classList.contains('language-ts')){ block.className = ('typescript') } if (block.className === 'language-sh') { block.className = 'bash' } hljs.highlightBlock(block); }); ``` -------------------------------- ### outputFile Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Asynchronously writes data to a file, creating the file if it does not exist. Supports optional write options. ```APIDOC ## outputFile ### Description Writes data to a file asynchronously. ### Method Asynchronous function call. ### Parameters #### Path Parameters * **path** (string) - Required - The path to the file. * **data** (any) - Required - The data to write to the file. * **options** (WriteOptions) - Optional - Options for writing the file. ### Returns Promise<void> ``` -------------------------------- ### Foy Task with Prioritized Async Dependencies Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html Defines a 'publish:patch' task where async dependencies 'test' and 'build' are prioritized. 'build' (priority 1) runs before 'test' (priority 0). ```javascript import { task, dep } from 'foy' /*Priority for async tasksDefault is 0, higher values will be run earlier; so, in this next example, `build` will be run before `test`.(Note: If you have multiple async dependencies with same priority, they will be executed in parallel.)*/ task( 'publish:patch', [ dep('test').async(0).force(), dep('build').async(1).force() ], async ctx => { await ctx.exec('npm version patch') await ctx.exec('npm publish') } ) ``` -------------------------------- ### Monitor Directory for Changes and Execute Multiple Commands Source: https://github.com/zaaack/foy/blob/main/docs/index.html Watch a directory and execute a series of commands when changes are detected. This allows for complex build or restart processes triggered by file modifications. ```typescript ctx.monitor('./src', ['rm -rf dist', 'tsc', 'node dist']) ``` -------------------------------- ### exec command ($) Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html A simple wrapper for the 'execa' module, providing a tagged template literal syntax for executing shell commands. ```APIDOC ## exec command ($) ### Description Executes shell commands using a tagged template literal syntax (`ctx.$` or standalone `$`), offering automatic variable escaping and returning the result from the `execa` module. ### Method Template Literal Tagged Function (`ctx.$` or `$`) ### Endpoint N/A (Function Call) ### Parameters #### Template Literal Arguments - **`command`** (string) - The shell command to execute. - **`${variable}`** (any) - Variables to interpolate into the command string. These are automatically escaped for safe shell execution. ### Options `ctx.$` (or `$`) accepts an optional options object, similar to `execa`. ### Returns An `execa` result object containing properties like `stdout`, `stderr`, and `exitCode`. ### Request Example ```javascript task('build', async ctx => { await ctx.$`tsc` const file = 'my file.txt' await ctx.$`cat ${file}` const { stdout } = await ctx.$`ls -la` console.log(stdout) }) ``` ### Key Features - **Automatic Escaping**: Safely interpolates variables into shell commands. - **Template Literal Syntax**: Provides a readable, shell-like syntax. - **Returns Execa Result**: Full access to `stdout`, `stderr`, `exitCode`, etc. - **Default Options**: `stdio: 'inherit'` and `shell: true` are set by default. ``` -------------------------------- ### outputFileSync Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Synchronously writes data to a file, creating the file if it does not exist. Supports optional write options. ```APIDOC ## outputFileSync ### Description Writes data to a file synchronously. ### Method Synchronous function call. ### Parameters #### Path Parameters * **path** (string) - Required - The path to the file. * **data** (any) - Required - The data to write to the file. * **options** (WriteOptions) - Optional - Options for writing the file. ### Returns void ``` -------------------------------- ### exec command (ctx.exec) Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html A string-based wrapper for executing shell commands, suitable for multiline commands but without automatic variable escaping. ```APIDOC ## exec command (ctx.exec) ### Description Executes shell commands provided as a string. This method is useful for multiline commands but does not automatically escape variables, requiring manual handling of special characters. ### Method `ctx.exec(commandString)` ### Endpoint N/A (Function Call) ### Parameters #### Command String - **`commandString`** (string) - The shell command(s) to execute. Can be multiline. ### Returns An `execa` result object containing properties like `stdout`, `stderr`, and `exitCode`. ### Request Example ```javascript task('deploy', async ctx => { await ctx.exec(` echo "Deploying version 1.0" ./scripts/deploy.sh echo "Deployment complete" `) }) ``` ### Differences from `ctx.$` - **Syntax**: Uses standard string syntax instead of template literals. - **Escaping**: Does not perform automatic variable escaping; requires manual sanitization if user input is included. - **Multiline Commands**: Supports multiline commands directly within the string. ``` -------------------------------- ### $<NewOptionsType>(options) Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/_.html Executes a script with provided options and returns a promise that resolves to an ExecaScriptMethod. This overload is useful for advanced script execution scenarios. ```APIDOC ## $<NewOptionsType>(options) ### Description Executes a script with provided options and returns a promise that resolves to an ExecaScriptMethod. This overload is useful for advanced script execution scenarios. ### Method Not specified (likely a function call in a JavaScript SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (NewOptionsType) - Description of options parameter ### Request Example ```json { "example": "options object" } ``` ### Response #### Success Response * **ExecaScriptMethod<Options & NewOptionsType>** - A promise resolving to an ExecaScriptMethod. #### Response Example ```json { "example": "ExecaScriptMethod object" } ``` ``` -------------------------------- ### Foy Task with Parallel Dependencies and Options Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html Configures a 'publish:patch' task with dependencies ('test', 'build') that run in parallel and are forced to rerun. This version uses the sugar syntax for defining dependencies. ```javascript import { task, dep } from 'foy' task( 'publish:patch', [ { name: 'test', async: true, // run test parallelly force: true, // force rerun test whether it has been executed before or not. }, { name: 'build', async: true, force: true, }, ], async ctx => { await ctx.exec('npm version patch') await ctx.exec('npm publish') } ) /* Sugar version */ task( 'publish:patch', [ dep('test').async().force(), dep('build').async().force() ], async ctx => { await ctx.exec('npm version patch') await ctx.exec('npm publish') } ) ``` -------------------------------- ### Foy Task with Axios Integration Source: https://github.com/zaaack/foy/blob/main/docs/api/index.html Shows how to use a Foy task to fetch data from a remote API using the Axios package and log the response data. ```javascript import { task, logger } from 'foy' import * as axios from 'axios' task('build', async ctx => { let res = await axios.get('https://your.server/data.json') logger.info(res.data) }) ``` -------------------------------- ### outputFileSync Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Synchronously writes data to a file, creating the file if it does not exist. Supports options. ```APIDOC ## outputFileSync ### Description Synchronously writes data to a file, creating the file if it does not exist. Supports options. ### Method `outputFileSync(path: string, data: any, options?: WriteOptions): void` ### Parameters #### Path Parameters - **path** (string) - Required - The file path to write to. - **data** (any) - Required - The data to write to the file. #### Request Body - **options** (WriteOptions) - Optional - Options for writing the file. ``` -------------------------------- ### task(name, dependencies, fn?) Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/task-1.html Defines a task with a name, an array of dependencies, and an optional function to execute. This overload allows for specifying task dependencies. ```APIDOC ## task(name, dependencies, fn?) ### Description Defines a task with a name, an array of dependencies, and an optional function to execute. This overload is used when tasks have explicit dependencies that must be resolved before execution. ### Method N/A (SDK Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters * **name**: string - The name of the task. * **dependencies**: [Dependency](../types/Dependency.html)[] - An array of dependencies for this task. * **fn**: [TaskFn](../types/TaskFn.html)<[O](task-1.html#task-1.O-1), any> (Optional) - The function to execute for this task. ### Returns * [Task](../interfaces/Task.html)<[O](task-1.html#task-1.O-1) ### Example ```typescript const dependency1 = task('dep1', () => {}); const dependency2 = task('dep2', () => {}); task('myTaskWithDeps', [dependency1, dependency2], () => { // task logic that depends on dep1 and dep2 }); ``` ``` -------------------------------- ### Define Tasks with Dependencies Source: https://github.com/zaaack/foy/blob/main/README.md Define tasks and their dependencies. Dependencies run serially by default. ```typescript import { task, dep } from 'foy' import * as axios from 'axios' task('test', async ctx => { await ctx.exec('mocha') }) task('build', async ctx => { let res = await axios.get('https://your.server/data.json') console.log(res.data) await ctx.exec('build my awesome project') }) task( 'publish:patch', ['test', 'build'], // Run test and build before publish async ctx => { await ctx.exec('npm version patch') await ctx.exec('npm publish') } ) ``` -------------------------------- ### ShellContext Methods Source: https://github.com/zaaack/foy/blob/main/docs/api/classes/ShellContext.html Details the methods available on the ShellContext class for interacting with the shell environment. ```APIDOC ## Methods ### cd - **Description**: Changes the current working directory. - **Parameters**: - **dir** (string) - The directory to change to. - **Returns**: [ShellContext](ShellContext.html) ### env - **Description**: Sets, gets, or deletes environment variables. - **Parameters**: - **key** (string) - The environment variable key. - **val** (undefined | string) - The value to set for the environment variable. If undefined, the variable is deleted. - **Returns**: this ### exec - **Description**: Executes a shell command. - **Parameters**: - **command** (string) - The command to execute. - **options** (Options) - Optional execution options. - **Returns**: ResultPromise<Options> - **Example**: ```javascript await ctx.exec('echo 1') await ctx.exec(` echo 1 sleep 1 echo 2`) ``` ### monitor - **Description**: Monitors shell commands (details not provided in source). ### popd - **Description**: Pops a directory from the directory stack (details not provided in source). ### pushd - **Description**: Pushes a directory onto the directory stack (details not provided in source). ### resetEnv - **Description**: Resets environment variables (details not provided in source). ``` -------------------------------- ### iter Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Asynchronously iterates over the contents of a directory, with an option to skip files. ```APIDOC ## iter ### Description Asynchronously iterates over the contents of a directory, with an option to skip files. ### Method `iter(dir: string, skip: ((path: string, stat: Stats) => boolean | void | Promise<boolean | void>)): Promise<void>` ### Parameters #### Path Parameters - **dir** (string) - Required - The directory to iterate over. #### Request Body - **skip** (function) - Required - A function to determine if a file should be skipped during iteration. It receives the file path and its stats, and can return a boolean or a promise resolving to a boolean. ``` -------------------------------- ### Execute Multiple Commands Synchronously with ctx.exec Source: https://github.com/zaaack/foy/blob/main/docs/index.html Run multiple commands sequentially within a single `ctx.exec` call by using newline characters. This is useful for build steps that depend on each other. ```typescript await ctx.exec(` tsc --outDir ./lib tsc --module es6 --outDir ./es `) ``` -------------------------------- ### shell Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/shell.html Executes a shell command with a given context and returns a promise with the results. The callback function receives a ShellContext object. ```APIDOC ## shell(callback) ### Description Executes a shell command with a given context and returns a promise with the results. The callback function receives a ShellContext object. ### Method (Implicitly a function call, not an HTTP method) ### Parameters #### Path Parameters (Not applicable) #### Query Parameters (Not applicable) #### Request Body (Not applicable) ### Parameters * **callback**: ((ctx: ShellContext) => Promise<any>) * This parameter is a function that accepts a `ShellContext` object and returns a Promise of any type. ### Returns * **Promise<any * A Promise that resolves with the result of the shell command execution. ``` -------------------------------- ### Execute Shell Commands with ctx.exec Source: https://github.com/zaaack/foy/blob/main/README.md Use `ctx.exec` to run shell commands as strings. It supports running multiple commands synchronously or concurrently, and can be used with file monitoring. ```typescript import { logger, $ } from 'foy' task('build', async ctx => { await ctx.exec('tsc') // run multiple commands synchronously await ctx.exec(` tsc --outDir ./lib tsc --module es6 --outDir ./es `) // run multiple commands concurrently await Promise.all([ ctx.exec('eslint'), ctx.exec('tsc'), ctx.exec('typedoc'), ]) // restart process when file changes ctx.monitor('./src', 'node ./dist') ctx.monitor('./src', ['rm -rf dist', 'tsc', 'node dist']) ctx.monitor('./src', async () => { await ctx.run('build:server') await ctx.exec('node ./dist') // auth detect long-running process when using ctx.exec }) ctx.monitor('./src', async (p) => { // manually point out the process need to be killed when restart p.current = require('child_process').exec('node dist') }) }) ``` -------------------------------- ### desc(desc): void Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/desc.html Defines a task description. This function takes a string as input and returns void. ```APIDOC ## desc(desc): void ### Description Defines a task description. ### Parameters #### Parameters * **desc** (string) - Description of the task. ### Returns void This function does not return a value. ``` -------------------------------- ### Pass Running Options to Dependencies Source: https://github.com/zaaack/foy/blob/main/README.md Configure dependencies to run asynchronously and with forced reruns. Higher priority values run earlier. ```typescript import { task, dep } from 'foy' task( 'publish:patch', [{ name: 'test', async: true, // run test parallelly force: true, // force rerun test whether it has been executed before or not. }, { name: 'build', async: true, force: true, },], async ctx => { await ctx.exec('npm version patch') await ctx.exec('npm publish') } ) /* Sugar version */ task( 'publish:patch', [ dep('test').async().force(), dep('build').async().force() ], async ctx => { await ctx.exec('npm version patch') await ctx.exec('npm publish') } ) /* Priority for async tasks Default is 0, higher values will be run earlier; so, in this next example, `build` will be run before `test`. (Note: If you have multiple async dependencies with same priority, they will be executed in parallel.) */ task( 'publish:patch', [ dep('test').async(0).force(), dep('build').async(1).force() ], async ctx => { await ctx.exec('npm version patch') await ctx.exec('npm publish') } ) ``` -------------------------------- ### Enable Bash Auto Completion Source: https://github.com/zaaack/foy/blob/main/docs/index.html Add Foy's auto-completion to your Bash shell by sourcing the completion profile. This provides command-line suggestions and speeds up task execution. ```bash # for bash foy --completion-profile >> ~/.bashrc ``` -------------------------------- ### copyFile Source: https://github.com/zaaack/foy/blob/main/docs/api/variables/fs.html Asynchronously copies a file from a source path to a destination path. Overload for different signature. ```APIDOC ## copyFile ### Description Asynchronously copies a file from a source path to a destination path. This method has an overload for different signature. ### Method `copyFile(src: PathLike, dst: PathLike, mode?: number): Promise<void>` or `copyFile(src: PathLike, dist: PathLike): Promise<unknown>` ### Parameters #### Path Parameters - **src** (PathLike) - Required - The source file path. - **dst** (PathLike) - Required - The destination file path. - **dist** (PathLike) - Required - The destination file path. - **mode** (number) - Optional - The file mode for the destination file. ``` -------------------------------- ### EJS Template Variables Source: https://github.com/zaaack/foy/blob/main/docs-src/index.html Demonstrates the use of EJS template variables for dynamic content rendering, such as project name, description, and URLs. ```html <%= name %> <%= name %> ========== <%= desc %> ---------- [View on GitHub](<%= githubUrl %>) [Manual](<%= apiUrl %>) <%- content %> [<%= name %>](<%= githubUrl %>) is maintained by [<%= author %>](<%= authorUrl %>). ``` -------------------------------- ### Compare ctx.$ and ctx.exec for Command Execution Source: https://github.com/zaaack/foy/blob/main/README.md Illustrates the difference between `ctx.$` (template literal, auto-escaping) and `ctx.exec` (string, no auto-escaping) for handling user input safely. `ctx.exec` also supports multiline commands. ```typescript // ctx.$ - template literal syntax, auto-escaping await ctx.$`echo ${userInput}` // safely escapes special characters // ctx.exec - string syntax, no auto-escaping await ctx.exec(`echo ${userInput}`) // be careful with special characters! // ctx.exec supports multiline commands await ctx.exec(` echo "step 1" echo "step 2" echo "step 3" `) ``` -------------------------------- ### setGlobalOptions Source: https://github.com/zaaack/foy/blob/main/docs/api/functions/setGlobalOptions.html Sets global options for all tasks. This function configures theme settings and controls the initial display of the application, ensuring the search index is ready before showing the page. ```APIDOC ## setGlobalOptions(options) ### Description Sets global options for all tasks. This function configures theme settings and controls the initial display of the application, ensuring the search index is ready before showing the page. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Method * Not applicable (this is a function call) ### Endpoint * Not applicable (this is a function call) ### Request Example ```javascript // Example usage: // Assuming GlobalOptions is defined elsewhere // setGlobalOptions({ theme: 'dark' }); ``` ### Response #### Success Response * **Returns**: void #### Response Example * No specific response body is returned as the function returns void. ``` -------------------------------- ### Enable Shell Auto Completion Source: https://github.com/zaaack/foy/blob/main/README.md Add auto-completion for Foy commands in your shell (bash or zsh) by appending the output of `foy --completion-profile` to your shell's configuration file. ```sh # for bash foy --completion-profile >> ~/.bashrc # for zsh foy --completion-profile >> ~/.zshrc ``` -------------------------------- ### WriteOptions Interface Source: https://github.com/zaaack/foy/blob/main/docs/api/interfaces/WriteOptions.html The WriteOptions interface specifies optional parameters that can be provided when writing to a file. These options allow customization of the writing process, such as specifying the character encoding, the file flag (e.g., 'w' for write, 'a' for append), and the file mode (permissions). ```APIDOC ## Interface: WriteOptions ### Description An interface that defines optional parameters for file writing operations. It allows users to specify encoding, file flags, and file modes. ### Properties #### `encoding` - **Type**: `BufferEncoding` - **Optional**: true - **Description**: Specifies the character encoding to use when writing the file. Defaults to 'utf8' if not provided. #### `flag` - **Type**: `string` - **Optional**: true - **Description**: Specifies the file system flag that determines how the file should be opened. Common flags include 'w' (write), 'a' (append), 'wx' (write exclusively). #### `mode` - **Type**: `string | number` - **Optional**: true - **Description**: Specifies the file mode (permissions) for the file. This can be represented as a string (e.g., '0o666') or a number. The default mode depends on the operating system and the file flag used. ``` -------------------------------- ### Navigate Directory Stack (pushd) Source: https://github.com/zaaack/foy/blob/main/docs/api/classes/ShellContext.html Changes the current working directory to the specified directory, similar to the 'pushd' shell command. Returns the ShellContext for chaining. ```typescript ctx.pushd('new/directory') ``` -------------------------------- ### Comparing ctx.$ and ctx.exec Source: https://github.com/zaaack/foy/blob/main/docs/index.html Highlights the differences between Foy's `ctx.$` template literal syntax with auto-escaping and `ctx.exec` string syntax without auto-escaping. ```javascript // ctx.$ - template literal syntax, auto-escaping await ctx.$`echo ${userInput}` // safely escapes special characters // ctx.exec - string syntax, no auto-escaping await ctx.exec(`echo ${userInput}`) // be careful with special characters! // ctx.exec supports multiline commands await ctx.exec( ` echo "step 1" echo "step 2" echo "step 3" ` ) ``` -------------------------------- ### Execute Single Command with ctx.exec Source: https://github.com/zaaack/foy/blob/main/docs/index.html Use `ctx.exec` to run a single command like `tsc`. Ensure `tsc` is available in your PATH. ```typescript import { logger, $ } from 'foy' task('build', async ctx => { await ctx.exec('tsc') }) ``` -------------------------------- ### Enable Zsh Auto Completion Source: https://github.com/zaaack/foy/blob/main/docs/index.html Add Foy's auto-completion to your Zsh shell by sourcing the completion profile. This enhances your command-line experience with intelligent suggestions. ```bash # for zsh foy --completion-profile >> ~/.zshrc ```