### Install Project Dependencies Source: https://github.com/desktop/dugite/blob/main/docs/setup.md Run this command to install all project dependencies, compile the library, and execute tests. ```sh yarn ``` -------------------------------- ### Get Git Binary Location Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/environment.md Use `setupEnvironment` to get the path to the Git binary and configure the environment. This is useful for direct process execution. ```typescript import { setupEnvironment } from 'dugite' const { env, gitLocation } = setupEnvironment({}) console.log('Git binary location:', gitLocation) // Windows: C:\path\to\git\cmd\git.exe // macOS/Linux: /path/to/git/bin/git ``` -------------------------------- ### Execute Git Command with Automatic Environment Setup Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/environment.md Use `exec` for typical Git operations where environment setup is handled internally. This example shows setting a custom `GIT_HTTP_USER_AGENT`. ```typescript import { exec } from 'dugite' // This internally calls setupEnvironment const result = await exec(['status'], '/path/to/repo', { env: { GIT_HTTP_USER_AGENT: 'my-app/1.0' } }) ``` -------------------------------- ### Environment Setup Functions Source: https://github.com/desktop/dugite/blob/main/_autodocs/_FILE_MANIFEST.txt Functions for setting up and resolving the Git environment, including `setupEnvironment()`, `resolveGitBinary()`, `resolveGitDir()`, `resolveGitExecPath()`, and `resolveEmbeddedGitDir()`. ```APIDOC ## Environment Setup Functions ### Description Provides utilities for configuring and locating the Git executable and its associated directories. ### Functions - `setupEnvironment(options: EnvMap): void` - `resolveGitBinary(): string` - `resolveGitDir(): string` - `resolveGitExecPath(): string` - `resolveEmbeddedGitDir(): string ``` -------------------------------- ### Complete Configuration Example for exec() Source: https://github.com/desktop/dugite/blob/main/_autodocs/configuration.md Demonstrates how to configure environment variables, output settings, process callbacks for monitoring, and cancellation signals when using the `exec()` function. ```typescript import { exec } from 'dugite' const result = await exec( ['clone', '--depth', '1', 'https://github.com/example/repo.git', '.'], '/destination', { // Custom environment env: { GIT_HTTP_USER_AGENT: 'my-app/1.0', GIT_HTTP_TIMEOUT: '60', GIT_SSH_COMMAND: 'ssh -i ~/.ssh/deploy_key' }, // Output configuration encoding: 'utf8', maxBuffer: 10 * 1024 * 1024, // 10MB // Process monitoring processCallback(process) { process.stderr.on('data', chunk => { const line = chunk.toString() if (line.includes('Receiving')) { console.log('Receiving objects...') } }) }, // Cancellation signal: abortController.signal } ) ``` -------------------------------- ### Environment Source: https://github.com/desktop/dugite/blob/main/_autodocs/README.md Functions for git binary location and environment setup. These functions assist in configuring the environment for Git execution. ```APIDOC ## Environment ### Description Functions for git binary location and environment setup. These functions assist in configuring the environment for Git execution. ### Method Not specified (assumed to be function calls within Node.js) ### Endpoint Not applicable (Node.js library functions) ### Parameters Refer to the [Environment](./api-reference/environment.md) documentation for detailed parameter information. ### Request Example Refer to the [Environment](./api-reference/environment.md) documentation for request examples. ### Response Refer to the [Environment](./api-reference/environment.md) documentation for response details. ``` -------------------------------- ### Manual Environment Setup and Git Execution Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/environment.md Use `setupEnvironment` for direct control over the environment and Git binary path. This allows custom environment variables to be passed to `child_process.execFile`. ```typescript import { setupEnvironment } from 'dugite' import { execFile } from 'child_process' const { env, gitLocation } = setupEnvironment({ GIT_HTTP_USER_AGENT: 'my-app/1.0' }) execFile(gitLocation, ['status'], { cwd: '/path/to/repo', env }, (err, stdout) => { console.log(stdout) }) ``` -------------------------------- ### Example Usage of IGitSpawnOptions Source: https://github.com/desktop/dugite/blob/main/_autodocs/types.md Illustrates how to use IGitSpawnOptions to pass environment variables when spawning a Git process. ```typescript const options: IGitSpawnOptions = { env: { GIT_TRACE: '1' } } const process = spawn(['fetch', 'origin'], '/path/to/repo', options) ``` -------------------------------- ### Dugite Exec Function Example (Buffer Output) Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/exec.md Example demonstrating the exec function for retrieving a list of files as null-terminated buffers. The output is processed to extract file names. ```typescript import { exec } from 'dugite' const { exitCode, stdout, stderr } = await exec( ['ls-files', '-z'], '/path/to/repo', { encoding: 'buffer' } ) if (exitCode === 0) { // stdout contains null-terminated file list as bytes const files = stdout.toString('utf8').split('\0').filter(Boolean) console.log('Files:', files) } ``` -------------------------------- ### Basic `exec` Example Source: https://github.com/desktop/dugite/blob/main/docs/api/exec.md Demonstrates how to use the `exec` function to pull changes from a Git repository, including setting custom environment variables and a `processCallback` for stderr logging. ```APIDOC ## Example Usage ### Basic Execution ```ts import { exec, IGitExecutionOptions } from 'dugite' const path = 'C:/path/to/repo/' const options: IGitExecutionOptions = { env: { 'GIT_HTTP_USER_AGENT': 'dugite/3.0.0', 'GIT_TRACE': '1', 'GIT_CURL_VERBOSE': '1' }, processCallback: (process) => { // Example: Log stderr line by line // byline(process.stderr).on('data', (chunk: string) => { // console.log('stderr line:', chunk) // }) } } async function runExec() { try { const result = await exec([ 'pull', 'origin' ], path, options) console.log('stdout:', result.stdout) console.log('stderr:', result.stderr) console.log('exitCode:', result.exitCode) } catch (error) { console.error('Execution failed:', error) } } runExec() ``` ``` -------------------------------- ### Example Usage of IGitStringExecutionOptions Source: https://github.com/desktop/dugite/blob/main/_autodocs/types.md Demonstrates how to configure options for string output, including encoding, environment variables, stdin data, and max buffer size when executing a Git command. ```typescript const options: IGitStringExecutionOptions = { encoding: 'utf8', env: { GIT_HTTP_USER_AGENT: 'my-app/1.0' }, stdin: 'commit message', maxBuffer: 5 * 1024 * 1024 } const result = await exec(['commit', '-F', '-'], '/path/to/repo', options) ``` -------------------------------- ### Install Dugite with npm Source: https://github.com/desktop/dugite/blob/main/README.md Add Dugite to your project using npm. ```bash > npm install dugite ``` -------------------------------- ### Install Dugite with Yarn Source: https://github.com/desktop/dugite/blob/main/README.md Add Dugite to your project using Yarn. ```bash > yarn add dugite ``` -------------------------------- ### Example Usage of IGitBufferExecutionOptions Source: https://github.com/desktop/dugite/blob/main/_autodocs/types.md Shows how to configure options for buffer output, specifying the encoding as 'buffer' and setting a maximum buffer size for executing a Git command. ```typescript const options: IGitBufferExecutionOptions = { encoding: 'buffer', maxBuffer: 50 * 1024 * 1024 } const result = await exec(['archive', '--format=zip', 'HEAD'], '/path/to/repo', options) ``` -------------------------------- ### exec() Example: Small Output Source: https://github.com/desktop/dugite/blob/main/_autodocs/comparison-exec-spawn.md Use `exec()` for commands with small, bounded output, such as listing branches. It buffers the entire output into memory. ```typescript import { exec } from 'dugite' // Good use of exec - output is small and bounded const result = await exec(['branch', '-a'], '/path/to/repo') const branches = result.stdout.split('\n').filter(Boolean) console.log('Branches:', branches) ``` -------------------------------- ### Spawn Git Command and Handle Output Source: https://github.com/desktop/dugite/blob/main/docs/api/spawn.md This example demonstrates how to use `spawn` to execute a Git command and handle its output. It mimics a Promise-based API by resolving with the command's output on success or rejecting on failure. Ensure the `directory` variable is defined in your scope. ```typescript import { spawn } from 'dugite' return new Promise((resolve, reject) => { const process = spawn([ 'status', '--porcelain=v2', '--untracked-files=all' ], directory) const output = new Array() process.stdout.on('data', (chunk) => { if (chunk instanceof Buffer) { output.push(chunk) } else { output.push(Buffer.from(chunk)) } }) process.on('exit', (code, signal) => { if (code !== 0) { reject(`process returned exit code '${code}' and signal '${signal}`) } else { const buffer = Buffer.concat(output) const text = buffer.toString('utf-8') resolve(text) } }) }) ``` -------------------------------- ### Dugite Exec Function Example (String Output) Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/exec.md Example of how to use the exec function to get Git repository status as a string. It checks the exit code to determine success or failure. ```typescript import { exec } from 'dugite' const { exitCode, stdout, stderr } = await exec( ['status'], '/path/to/repo' ) if (exitCode === 0) { console.log('Repository status:', stdout) } else { console.error('Error:', stderr) } ``` -------------------------------- ### Spawn ChildProcess Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/types.md Demonstrates how to use the spawn function to execute a child process and attach listeners to its standard output, standard error, and exit events. Ensure the 'dugite' module is imported. ```typescript import { spawn } from 'dugite' const process = spawn(['log', '--oneline'], '/path/to/repo') // Attach listeners process.stdout.on('data', chunk => console.log(chunk.toString())) process.stderr.on('error', err => console.error(err)) process.on('exit', (code) => console.log(`Exited with code ${code}`)) ``` -------------------------------- ### resolveGitDir Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/environment.md Locates the Git installation directory. It can use an environment variable or an overridden path to find the directory. ```APIDOC ## Function: resolveGitDir ### Description Locates the Git installation directory. It can use an environment variable or an overridden path to find the directory. ### Signature ```typescript export function resolveGitDir( localGitDir?: string ): string ``` ### Parameters #### Path Parameters - **localGitDir** (string) - Optional - Override path to custom Git installation. Defaults to `process.env.LOCAL_GIT_DIRECTORY`. ### Return Type `string` Absolute path to the Git directory (the folder containing `bin/git` or `cmd/git.exe`). ### Example ```typescript import { resolveGitDir } from 'dugite' const gitDir = resolveGitDir() console.log('Git directory:', gitDir) // Override with custom Git installation const customGitDir = resolveGitDir('/opt/custom-git') ``` ``` -------------------------------- ### Example Usage of IGitStringResult Source: https://github.com/desktop/dugite/blob/main/_autodocs/types.md Shows how to use IGitStringResult, where stdout is directly accessible as a string without needing conversion. ```typescript const result: IGitStringResult = await exec(['log', '--oneline'], '/path/to/repo') console.log(result.stdout) // string, no need to convert ``` -------------------------------- ### Example Usage of IGitBufferResult Source: https://github.com/desktop/dugite/blob/main/_autodocs/types.md Demonstrates using IGitBufferResult to handle binary output, such as image data, directly as a Buffer. ```typescript const result: IGitBufferResult = await exec( ['show', 'HEAD:binary-file.png'], '/path/to/repo', { encoding: 'buffer' } ) console.log(result.stdout) // Buffer ``` -------------------------------- ### Spawning a Git Process with Custom Environment Variables Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/spawn.md Example of using the `spawn` function to execute a Git command with custom environment variables. This is useful for setting specific Git configurations like user agent or SSL verification. ```typescript import { spawn } from 'dugite' const process = spawn( ['status'], '/path/to/repo', { env: { GIT_HTTP_USER_AGENT: 'my-app/1.0.0', GIT_SSL_NO_VERIFY: '1' } } ) ``` -------------------------------- ### Hybrid Git Operation with exec() and spawn() Source: https://github.com/desktop/dugite/blob/main/_autodocs/comparison-exec-spawn.md This example demonstrates a hybrid approach using both exec() for small, synchronous output and spawn() for potentially large, streaming output in a Git operation. It checks the repository status with exec() and then performs a diff with spawn() if changes are detected. ```typescript import { exec, spawn } from 'dugite' async function gitOperation(repoPath) { // Use exec for simple status check const statusResult = await exec(['status', '--short'], repoPath) if (statusResult.exitCode !== 0) { throw new Error('Not a git repository') } // Parse small output const isDirty = statusResult.stdout.trim().length > 0 if (isDirty) { // Use spawn for potentially large diff output const diffProcess = spawn(['diff', '--cached'], repoPath) let diffSize = 0 diffProcess.stdout.on('data', chunk => { diffSize += chunk.length process.stdout.write(chunk) }) return new Promise((resolve, reject) => { diffProcess.on('exit', code => { if (code === 0) { resolve({ isDirty, diffSize }) } else { reject(new Error(`Diff failed with code ${code}`)) } }) diffProcess.on('error', reject) }) } return { isDirty: false } } ``` -------------------------------- ### Clone Repository with Progress Updates Source: https://github.com/desktop/dugite/blob/main/_autodocs/quick-start.md Implement a function to clone a Git repository and display progress updates in real-time. This example utilizes the `processCallback` option to capture and parse stderr output for progress percentage. ```typescript import { exec, ExecError } from 'dugite' async function cloneWithProgress(url, destination) { console.log(`Cloning ${url} to ${destination}...`) const controller = new AbortController() try { const result = await exec( ['clone', '--progress', url, destination], '/', { signal: controller.signal, processCallback(process) { let lastUpdate = Date.now() process.stderr.on('data', chunk => { const now = Date.now() if (now - lastUpdate > 500) { // Update every 500ms const output = chunk.toString() const match = output.match(/(\d+)%/) if (match) { console.log(`Progress: ${match[1]}%`) lastUpdate = now } } }) } } ) if (result.exitCode === 0) { console.log('Clone complete!') return { success: true } } else { return { success: false, error: result.stderr } } } catch (error) { if (error instanceof ExecError) { return { success: false, error: error.message, code: error.code } } throw error } } // Usage const result = await cloneWithProgress( 'https://github.com/nodejs/node.git', '/tmp/node-repo' ) if (result.success) { console.log('Done!') } else { console.error('Failed:', result.error) } ``` -------------------------------- ### exec() Example: Risk of Large Output Source: https://github.com/desktop/dugite/blob/main/_autodocs/comparison-exec-spawn.md Avoid using `exec()` for commands that may produce large or unbounded output, like extensive git logs, as it can consume significant memory by buffering the entire output. ```typescript import { exec } from 'dugite' // WARNING: Could use lots of memory const result = await exec( ['log', '--all', '--patch'], '/path/to/large/repo' // With large repo, this loads entire output into memory ) ``` -------------------------------- ### EnvMap Class Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/environment.md Demonstrates the usage of the EnvMap class for managing environment variables. This class provides platform-specific case sensitivity for environment variable lookups and modifications. It behaves as a case-insensitive, case-preserving map on Windows and a standard case-sensitive map on other platforms. ```typescript import { EnvMap } from 'dugite' const env = new EnvMap([ ['PATH', '/usr/bin'], ['HOME', '/home/user'] ]) // Get (case-insensitive on Windows, case-sensitive elsewhere) console.log(env.get('PATH')) // Set preserves the case you provide env.set('MY_VAR', 'value') // Iterate for (const [key, value] of env.entries()) { console.log(`${key}=${value}`) } ``` -------------------------------- ### Complete Git Error Handling Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/error-parsing.md Demonstrates a complete error handling strategy for Git commands using Dugite's `exec`, `parseError`, and `parseBadConfigValueErrorInfo` functions. Handles both command execution failures and specific Git errors like bad configuration values and merge conflicts. ```typescript import { exec, parseError, parseBadConfigValueErrorInfo, GitError, ExecError } from 'dugite' async function safeGitCommand(args, repo) { try { const result = await exec(args, repo) if (result.exitCode === 0) { return { success: true, output: result.stdout } } // Process failed but launched successfully const error = parseError(result.stderr) if (error === GitError.BadConfigValue) { const info = parseBadConfigValueErrorInfo(result.stderr) return { success: false, error: `Invalid config: ${info?.key} = ${info?.value}` } } if (error === GitError.MergeConflicts) { return { success: false, error: 'Merge produced conflicts', errorCode: error } } return { success: false, error: result.stderr, errorCode: error } } catch (err) { if (err instanceof ExecError) { // Process failed to launch return { success: false, error: `Execution failed: ${err.message}`, code: err.code } } throw err } } ``` -------------------------------- ### Handling Spawn and Execution Errors Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/spawn.md This snippet demonstrates how to handle both spawn failures (process never starts) and process execution failures (non-zero exit code). It listens for 'error' events for spawn issues and 'exit' events for execution status, also capturing stderr for detailed error messages. ```typescript import { spawn } from 'dugite' const process = spawn(['invalid-command'], '/path/to/repo') process.on('error', err => { // Spawn failed, e.g., git binary not found console.error('Spawn failed:', err.message) }) process.on('exit', (code, signal) => { if (code !== 0) { // Command failed, read stderr for details console.error(`Command failed with code ${code}`) } if (signal) { // Process was killed by signal console.error(`Process killed by signal ${signal}`) } }) process.stderr.on('data', chunk => { // Read error messages as they arrive console.error(chunk.toString()) }) ``` -------------------------------- ### Resolve Embedded Git Directory Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/environment.md Use this function to get the path to the Git distribution bundled with dugite. This is useful when a local Git installation is not available or configured. ```typescript import { resolveEmbeddedGitDir } from 'dugite' const embeddedGitDir = resolveEmbeddedGitDir() console.log('Embedded Git directory:', embeddedGitDir) ``` -------------------------------- ### Resolve Git Installation Directory Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/environment.md Locates the Git installation directory. It uses the LOCAL_GIT_DIRECTORY environment variable if set, otherwise returns the embedded Git directory. Useful for finding the base path of your Git installation. ```typescript import { resolveGitDir } from 'dugite' const gitDir = resolveGitDir() console.log('Git directory:', gitDir) // Override with custom Git installation const customGitDir = resolveGitDir('/opt/custom-git') ``` -------------------------------- ### setupEnvironment Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/environment.md Configures the environment for a Git process and locates the Git binary. It prepares environment variables for Git execution, handling platform-specific paths and settings. This function can be used directly for custom process launching. ```APIDOC ## Function: setupEnvironment ### Description Configures the environment for a Git process and locates the Git binary. It prepares environment variables for Git execution, handling platform-specific paths and settings. This function can be used directly for custom process launching. ### Signature ```typescript export function setupEnvironment( environmentVariables: Record, processEnv?: Record ): { env: Record gitLocation: string } ``` ### Parameters #### Parameters - **environmentVariables** (Record) - Required - Additional environment variables to set for the process. These override variables from processEnv. - **processEnv** (Record) - Optional - Base environment object to extend. Defaults to current process.env. ### Return Type `{ env: Record, gitLocation: string }` Returns an object containing the configured environment dictionary and the resolved path to the Git binary. ### Example: Getting git binary location ```typescript import { setupEnvironment } from 'dugite' const { env, gitLocation } = setupEnvironment({}) console.log('Git binary location:', gitLocation) // Windows: C:\path\to\git\cmd\git.exe // macOS/Linux: /path/to/git/bin/git ``` ### Example: Setting custom environment variables ```typescript import { setupEnvironment } from 'dugite' const { env, gitLocation } = setupEnvironment({ GIT_HTTP_USER_AGENT: 'my-app/1.0.0', GIT_SSH_COMMAND: 'ssh -i ~/.ssh/custom_key' }) // env now includes git's required paths plus custom variables ``` ### Example: Using with custom process spawn ```typescript import { setupEnvironment } from 'dugite' import { execFile } from 'child_process' const { env, gitLocation } = setupEnvironment({}) execFile(gitLocation, ['status'], { cwd: '/path/to/repo', env }, (err, stdout, stderr) => { if (err) { console.error('Git error:', err) } else { console.log(stdout) } }) ``` ``` -------------------------------- ### Parse Git Error Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/types.md Example of how to use the parseError function to identify specific GitError conditions. Requires importing parseError and GitError from 'dugite'. ```typescript import { parseError, GitError } from 'dugite' const error = parseError(result.stderr) if (error === GitError.MergeConflicts) { // Handle merge conflicts } ``` -------------------------------- ### Override Git Installation Directory Source: https://github.com/desktop/dugite/blob/main/_autodocs/configuration.md Use a custom or system Git installation instead of the embedded Git by setting the LOCAL_GIT_DIRECTORY environment variable. The path should point to the Git root directory. ```bash # Use system Git instead of embedded Git export LOCAL_GIT_DIRECTORY=/usr/local ``` ```bash # Or on Windows set LOCAL_GIT_DIRECTORY=C:\Program Files\Git ``` -------------------------------- ### Execute Git Command with Custom Environment Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/environment.md Integrate `setupEnvironment` with Node.js's `child_process.execFile` to run Git commands using the configured environment and Git binary path. This allows for fine-grained control over Git execution. ```typescript import { setupEnvironment } from 'dugite' import { execFile } from 'child_process' const { env, gitLocation } = setupEnvironment({}) execFile(gitLocation, ['status'], { cwd: '/path/to/repo', env }, (err, stdout, stderr) => { if (err) { console.error('Git error:', err) } else { console.log(stdout) } }) ``` -------------------------------- ### Configure Git Command Options Source: https://github.com/desktop/dugite/blob/main/_autodocs/00-START-HERE.md Shows how to pass configuration options to `exec()`, such as environment variables (`env`), standard input (`stdin`), and buffer size limits (`maxBuffer`). ```typescript // Pass options const result = await exec(args, path, { env: { GIT_SSH_COMMAND: '...' }, stdin: 'commit message', maxBuffer: 10 * 1024 * 1024 }) ``` -------------------------------- ### Install Dugite with npm or Yarn Source: https://github.com/desktop/dugite/blob/main/_autodocs/quick-start.md Use npm or yarn to add dugite to your project dependencies. ```bash npm install dugite # or yarn add dugite ``` -------------------------------- ### IGitSpawnOptions Source: https://github.com/desktop/dugite/blob/main/_autodocs/types.md Minimal options for the `spawn()` command, primarily used for setting environment variables for the spawned process. ```APIDOC ## Interface IGitSpawnOptions ### Description Provides minimal options for the `spawn()` function, allowing the configuration of environment variables for the child process. ### Fields - **env** (Record) - Optional - Environment variables to pass to the process. ### Example ```typescript const options: IGitSpawnOptions = { env: { GIT_TRACE: '1' } } const process = spawn(['fetch', 'origin'], '/path/to/repo', options) ``` ``` -------------------------------- ### Environment Variable Configuration for spawn() Source: https://github.com/desktop/dugite/blob/main/_autodocs/configuration.md Shows how to configure environment variables for the `spawn()` function, using `GIT_TRACE` to enable debug output. ```typescript import { spawn } from 'dugite' const process = spawn( ['log', '--oneline', '-100'], '/path/to/repo', { env: { GIT_TRACE: '1' // Enable git debug output } } ) ``` -------------------------------- ### resolveEmbeddedGitDir Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/environment.md Locates the embedded Git directory that is packed with dugite. This function is called when no custom Git installation directory is set. ```APIDOC ## Function: resolveEmbeddedGitDir ### Description Locates the embedded Git directory (packed with dugite). Returns the path to the embedded Git distribution that comes with dugite. This is only called if `LOCAL_GIT_DIRECTORY` is not set. ### Signature ```typescript export function resolveEmbeddedGitDir(): string ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Return Type `string` - Absolute path to the embedded git directory. ### Example ```typescript import { resolveEmbeddedGitDir } from 'dugite' const embeddedGitDir = resolveEmbeddedGitDir() console.log('Embedded Git directory:', embeddedGitDir) ``` ### Throws - `Error` - If the current platform is not supported (Windows, macOS, Linux, Android) ``` -------------------------------- ### IGitExecutionOptions Source: https://github.com/desktop/dugite/blob/main/_autodocs/types.md Full configuration interface for `exec()` and `spawn()` commands. It allows customization of environment variables, stdin, output encoding, buffer limits, process callbacks, cancellation signals, and kill signals. ```APIDOC ## Interface IGitExecutionOptions ### Description Provides a comprehensive set of options for configuring the execution of Git commands, including environment variables, standard input, output encoding, buffer limits, process callbacks, cancellation signals, and kill signals. ### Fields - **env** (Record) - Optional - Environment variables to pass to the process. - **stdin** (string | Buffer) - Optional - Data to write to stdin. - **stdinEncoding** (BufferEncoding) - Optional - Encoding for string stdin. Defaults to 'utf8'. - **encoding** (BufferEncoding | 'buffer') - Optional - Output encoding. Defaults to 'utf8'. - **maxBuffer** (number) - Optional - Maximum bytes for stdout/stderr combined. Defaults to Infinity. - **processCallback** ((process: ChildProcess) => void) - Optional - Callback with the spawned process. - **signal** (AbortSignal) - Optional - Signal for cancellation. - **killSignal** (ExecFileOptions['killSignal']) - Optional - Signal to send when killing. Defaults to 'SIGTERM'. ``` -------------------------------- ### Execute Git Status Source: https://github.com/desktop/dugite/blob/main/_autodocs/README.md Execute a git command and get the full output. Use this for simple commands where the output is not excessively large. ```typescript import { exec } from 'dugite' const result = await exec(['status'], '/path/to/repo') if (result.exitCode === 0) { console.log('Repository status:', result.stdout) } else { console.error('Error:', result.stderr) } ``` -------------------------------- ### Executing Git Commands Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/exec.md Demonstrates how to execute a Git command using the `exec` function and handle both successful execution with potential Git errors and process launch failures. ```APIDOC ## exec ### Description Executes a Git command and returns the result. This function can throw an `ExecError` if the process fails to launch. ### Method `exec(args: string[], repoPath: string, options?: IGitStringExecutionOptions | IGitBufferExecutionOptions): Promise exec(args: string[], repoPath: string, options: IGitStringExecutionOptions): Promise exec(args: string[], repoPath: string, options: IGitBufferExecutionOptions): Promise ### Parameters #### Path Parameters - **repoPath** (string) - Required - The path to the Git repository. #### Query Parameters - **args** (string[]) - Required - An array of strings representing the Git command and its arguments. - **options** (IGitStringExecutionOptions | IGitBufferExecutionOptions) - Optional - Options for controlling the execution, such as output encoding. ### Request Example ```typescript import { exec, ExecError } from 'dugite' try { const result = await exec(['status'], '/path/to/repo') if (result.exitCode !== 0) { // Git ran but reported an error console.error('Git error:', result.stderr) } } catch (error) { if (error instanceof ExecError) { // Process failed to launch or system-level error console.error('Exec failed:', error.message) console.error('Code:', error.code) // e.g., 'ENOENT' console.error('Stdout:', error.stdout) console.error('Stderr:', error.stderr) } } ``` ### Response #### Success Response (200) - **IGitResult** - An object containing the result of the Git command execution. - **exitCode** (number) - The exit code of the Git process. - **stdout** (string | Buffer) - The standard output of the Git process. - **stderr** (string | Buffer) - The standard error of the Git process. #### Error Response - **ExecError** - Thrown when the Git process fails to launch or encounters a system-level error. - **message** (string) - The error message. - **code** (string) - The system error code (e.g., 'ENOENT'). - **stdout** (string | Buffer) - The standard output captured before the error. - **stderr** (string | Buffer) - The standard error captured before the error. ``` -------------------------------- ### Example Usage of IGitResult Source: https://github.com/desktop/dugite/blob/main/_autodocs/types.md Demonstrates how to use the IGitResult type after executing a git command. Checks the exit code and converts stdout to a string if successful. ```typescript const result: IGitResult = await exec(['status'], '/path/to/repo') if (result.exitCode === 0) { const output = result.stdout.toString() } ``` -------------------------------- ### Format Code Source: https://github.com/desktop/dugite/blob/main/docs/setup.md Execute this command to automatically format your code to match the project's style before committing. ```sh yarn prettify ``` -------------------------------- ### Commit with Message via Stdin Source: https://github.com/desktop/dugite/blob/main/_autodocs/00-START-HERE.md Example of creating a Git commit with a message provided via standard input. This is useful for automated commit processes. ```typescript import { exec } from 'dugite' const message = 'feat: add feature\n\nDescription' await exec(['commit', '-F', '-'], '/path/to/repo', { stdin: message }) ``` -------------------------------- ### Use System Git with Environment Variable Source: https://github.com/desktop/dugite/blob/main/_autodocs/configuration.md Configure Dugite to use your system's Git installation by setting the LOCAL_GIT_DIRECTORY environment variable before calling exec. ```typescript import { exec } from 'dugite' // Option 1: Environment variable before calling exec process.env.LOCAL_GIT_DIRECTORY = '/usr/local' const result = await exec(['status'], '/path/to/repo') ``` -------------------------------- ### Basic Spawn Usage Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/spawn.md Execute a Git command and listen to its standard output and exit events. Useful for simple command execution where real-time output is desired. ```typescript import { spawn } from 'dugite' const process = spawn(['log', '--oneline', '-20'], '/path/to/repo') process.stdout.on('data', chunk => { console.log('Line:', chunk.toString()) }) process.on('error', err => { console.error('Failed to spawn:', err) }) process.on('exit', (code, signal) => { console.log(`Process exited with code ${code} and signal ${signal}`) }) ``` -------------------------------- ### Use System Git with Manual Path Resolution Source: https://github.com/desktop/dugite/blob/main/_autodocs/configuration.md Alternatively, resolve the Git binary path manually and set up the environment for child_process.execFile. ```typescript import { resolveGitBinary, setupEnvironment } from 'dugite' const gitLocation = resolveGitBinary('/usr/local') const { env } = setupEnvironment({}, process.env) // Now use with child_process.execFile(gitLocation, args, { env, cwd }) ``` -------------------------------- ### Executing Git Commands and Handling Errors Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/exec.md Demonstrates how to execute a git command using `exec` and handle potential errors. It shows how to check the `exitCode` for command-specific errors and catch `ExecError` for process launch failures. ```typescript import { exec, ExecError } from 'dugite' try { const result = await exec(['status'], '/path/to/repo') if (result.exitCode !== 0) { // Git ran but reported an error console.error('Git error:', result.stderr) } } catch (error) { if (error instanceof ExecError) { // Process failed to launch or system-level error console.error('Exec failed:', error.message) console.error('Code:', error.code) // e.g., 'ENOENT' console.error('Stdout:', error.stdout) console.error('Stderr:', error.stderr) } } ``` -------------------------------- ### Handle Git Config Errors Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/error-parsing.md Example of executing a git config command and handling potential errors, specifically checking for `GitError.BadConfigValue` and using `parseBadConfigValueErrorInfo` to log details. ```typescript import { exec, parseError, parseBadConfigValueErrorInfo, GitError } from 'dugite' async function configSet(repo, key, value) { const result = await exec( ['config', key, value], repo ) if (result.exitCode !== 0) { const error = parseError(result.stderr) if (error === GitError.BadConfigValue) { const info = parseBadConfigValueErrorInfo(result.stderr) if (info) { console.error( `Config key '${info.key}' rejected value '${info.value}'` ) } } } } ``` -------------------------------- ### Basic Error Catching with ExecError Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/exec-error.md Demonstrates how to use a try-catch block to handle potential ExecError exceptions during Git command execution. This snippet shows how to differentiate between a successful execution (exitCode 0) and an error. ```typescript import { exec, ExecError } from 'dugite' try { const result = await exec(['status'], '/path/to/repo') if (result.exitCode === 0) { console.log('Status:', result.stdout) } else { console.error('Git error:', result.stderr) } } catch (error) { if (error instanceof ExecError) { console.error('Execution failed:', error.message) console.error('Code:', error.code) console.error('Stdout:', error.stdout) console.error('Stderr:', error.stderr) } } ``` -------------------------------- ### Set Dugite Cache Directory Source: https://github.com/desktop/dugite/blob/main/_autodocs/configuration.md Specify a custom directory for caching downloaded Git binaries during installation. This is useful for build servers to cache Git across multiple builds. ```bash DUGITE_CACHE_DIR=/var/cache/dugite npm install ``` ```bash # Build server CI export DUGITE_CACHE_DIR=/builds/cache yarn install ``` -------------------------------- ### Get Current Git Branch Name Source: https://github.com/desktop/dugite/blob/main/_autodocs/README.md Use `exec` to run `branch --show-current` to retrieve the name of the current branch. The output is trimmed to remove leading/trailing whitespace. ```typescript import { exec } from 'dugite' async function getCurrentBranch(path: string): Promise { const result = await exec(['branch', '--show-current'], path) return result.stdout.trim() } ``` -------------------------------- ### Spawn Function Source: https://github.com/desktop/dugite/blob/main/_autodocs/_FILE_MANIFEST.txt Documentation for the `spawn()` function, used for spawning Git processes. This is useful for long-running commands or when more control over the process is needed. ```APIDOC ## spawn() ### Description Spawns a Git process, allowing for more granular control over input, output, and lifecycle. Useful for long-running operations or interactive commands. ### Method `spawn(command: string, args?: string[], options?: IGitSpawnOptions): ChildProcess ``` -------------------------------- ### Use System Git Source: https://github.com/desktop/dugite/blob/main/_autodocs/quick-start.md Configure Dugite to use the system's Git installation by setting the LOCAL_GIT_DIRECTORY environment variable. This is useful when you need to ensure consistency with your system's Git version. ```typescript import { exec } from 'dugite' // Use system Git instead of embedded Git process.env.LOCAL_GIT_DIRECTORY = '/usr/local' const result = await exec(['status'], '/path/to/repo') ``` -------------------------------- ### Typical Workflow for Spawning a Process Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/spawn.md This snippet shows a common pattern for using the spawn function, specifically for a 'git pull' operation. It includes setting up listeners for stdout and stderr to capture command output and errors, and handling the 'exit' event to determine success or failure. ```typescript import { spawn } from 'dugite' const process = spawn(['pull', 'origin', 'main'], '/path/to/repo') const handleData = (chunk) => { console.log(chunk.toString()) } const handleError = (chunk) => { console.error(chunk.toString()) } process.stdout.on('data', handleData) process.stderr.on('data', handleError) process.on('exit', (code) => { if (code === 0) { console.log('Pull completed successfully') } else { console.log(`Pull failed with exit code ${code}`) } }) // Handle spawn failures process.on('error', (err) => { console.error('Failed to spawn process:', err) }) ``` -------------------------------- ### Classes Source: https://github.com/desktop/dugite/blob/main/_autodocs/_FILE_MANIFEST.txt Documentation for the `ExecError` and `EnvMap` classes. ```APIDOC ## Classes ### ExecError Represents an error that occurred during Git command execution. ### EnvMap A map-like structure for environment variables. ``` -------------------------------- ### Handling Large Binary Output Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/exec.md Demonstrates how to configure `encoding` to 'buffer' and set `maxBuffer` to handle large binary outputs, such as image files, from git commands. This prevents errors due to exceeding default buffer limits. ```typescript import { exec } from 'dugite' const result = await exec( ['show', 'HEAD:image.png'], '/path/to/repo', { encoding: 'buffer', maxBuffer: 10 * 1024 * 1024 } // 10MB limit ) if (result.exitCode === 0) { // result.stdout is Buffer containing image bytes const imageData = result.stdout } ``` -------------------------------- ### Override Git Internal Programs Path Source: https://github.com/desktop/dugite/blob/main/_autodocs/configuration.md Specify a custom path for Git's internal programs (libexec/git-core) using the GIT_EXEC_PATH environment variable. This is useful if Git subprograms are installed in a non-standard location. ```bash export GIT_EXEC_PATH=/opt/git/libexec/git-core ``` -------------------------------- ### spawn Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/spawn.md Execute a git command and return the raw child process immediately without waiting for completion. This is useful for streaming operations or when you need to read from stdout/stderr in real-time. ```APIDOC ## Function: spawn ```typescript export function spawn( args: string[], path: string, opts?: IGitSpawnOptions ): ChildProcess ``` ### Description Execute a git command and return the raw child process immediately without waiting for completion. This is useful for streaming operations or when you need to read from stdout/stderr in real-time. ### Parameters #### Path Parameters - **args** (string[]) - Required - Array of git command arguments, e.g., `['log', '--oneline']` - **path** (string) - Required - Working directory path where git command executes - **opts** (IGitSpawnOptions) - Optional - Configuration options for spawning ### Return Type `ChildProcess` Returns the spawned child process immediately. No promise is returned—the process is already running. ### Example: Basic usage ```typescript import { spawn } from 'dugite' const process = spawn(['log', '--oneline', '-20'], '/path/to/repo') process.stdout.on('data', chunk => { console.log('Line:', chunk.toString()) }) process.on('error', err => { console.error('Failed to spawn:', err) }) process.on('exit', (code, signal) => { console.log(`Process exited with code ${code} and signal ${signal}`) }) ``` ### Example: Piping output to another process ```typescript import { spawn } from 'dugite' import { createWriteStream } from 'fs' const gitProcess = spawn(['cat-file', '-p', 'HEAD~100:large-file.bin'], '/path/to/repo') const fileStream = createWriteStream('/tmp/output.bin') gitProcess.stdout.pipe(fileStream) gitProcess.on('error', err => { console.error('Error:', err) }) ``` ### Example: Line-by-line processing ```typescript import { spawn } from 'dugite' import { createInterface } from 'readline' const process = spawn(['log', '--oneline'], '/path/to/repo') const rl = createInterface({ input: process.stdout, crlfDelay: Infinity }) rl.on('line', line => { const [hash, ...message] = line.split(' ') console.log(`Commit ${hash}: ${message.join(' ')}`) }) process.on('exit', code => { console.log(`Done. Exit code: ${code}`) }) ``` ### Example: Error handling ```typescript import { spawn } from 'dugite' const process = spawn(['fetch', 'origin'], '/path/to/repo') process.stdout.on('data', chunk => { console.log(chunk.toString()) }) process.stderr.on('data', chunk => { console.error('Error output:', chunk.toString()) }) process.on('error', err => { // Emitted when spawn itself fails (e.g., git binary not found) console.error('Spawn error:', err) }) process.on('exit', (code, signal) => { if (code !== 0) { console.error(`Git command failed with exit code ${code}`) } }) ``` ``` -------------------------------- ### exec (Buffer Output) Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/exec.md Executes a Git command and returns stdout and stderr as Buffers. This is useful for handling binary data or large outputs efficiently. ```APIDOC ## exec (Buffer Output) ### Description Executes a Git command with buffer output. Returns the exit code, stdout, and stderr as Buffers. ### Method `exec` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Function Parameters - **args** (string[]) - Required - Array of git command arguments - **path** (string) - Required - Working directory path where git command executes - **options** (IGitBufferExecutionOptions) - Optional - Configuration options; must include `encoding: 'buffer'` ### Request Example ```typescript import { exec } from 'dugite' const { exitCode, stdout, stderr } = await exec( ['ls-files', '-z'], '/path/to/repo', { encoding: 'buffer' } ) if (exitCode === 0) { // stdout contains null-terminated file list as bytes const files = stdout.toString('utf8').split('\0').filter(Boolean) console.log('Files:', files) } ``` ### Response #### Success Response - **stdout** (Buffer) - Standard output of the Git command as a Buffer. - **stderr** (Buffer) - Standard error of the Git command as a Buffer. - **exitCode** (number) - The exit code of the Git process. #### Response Example ```json { "stdout": Buffer.from([97, 108, 111, 0]), // Example Buffer for 'alo\0' "stderr": Buffer.from([]), "exitCode": 0 } ``` ``` -------------------------------- ### spawn() Basic Usage and Process Control Source: https://github.com/desktop/dugite/blob/main/_autodocs/comparison-exec-spawn.md spawn() offers a simpler option set for running commands and provides direct access to the ChildProcess for advanced control, suitable for large or unbounded outputs. ```typescript // spawn has simpler options const process = spawn(args, path, { env: { /* custom variables */ } }) // For advanced control, manipulate the returned ChildProcess process.stdin.write('data') process.kill('SIGTERM') ``` -------------------------------- ### Execute Git Command with Custom Git Path Source: https://github.com/desktop/dugite/blob/main/_autodocs/configuration.md Execute Git commands using a custom Git installation by setting the LOCAL_GIT_DIRECTORY environment variable in your Node.js process. This ensures dugite uses the specified Git binary. ```typescript import { exec } from 'dugite' // Use system Git process.env.LOCAL_GIT_DIRECTORY = '/usr/local' const result = await exec(['status'], '/path/to/repo') ``` -------------------------------- ### Handling Specific Error Codes with ExecError Source: https://github.com/desktop/dugite/blob/main/_autodocs/api-reference/exec-error.md Provides an example of handling specific error codes within an ExecError. This function checks for common error codes like 'ENOENT', 'EACCES', and 'ABORT_ERR', re-throwing them with more user-friendly messages. ```typescript import { exec, ExecError } from 'dugite' async function executeGit(args, path) { try { return await exec(args, path) } catch (error) { if (error instanceof ExecError) { switch (error.code) { case 'ENOENT': throw new Error('Git binary not found. Is dugite installed correctly?') case 'EACCES': throw new Error('Git binary exists but is not executable') case 'ABORT_ERR': throw new Error('Git command was cancelled') default: throw error } } throw error } } ```