### Setup with custom Git and environment Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Example demonstrating how to provide a custom base environment alongside specific overrides. ```typescript import { setupEnvironment } from 'dugite' // Setup with custom Git and environment const { env, gitLocation } = setupEnvironment( { 'GIT_HTTP_USER_AGENT': 'MyApp/1.0' }, { ...process.env, 'LOCAL_GIT_DIRECTORY': '/opt/git-custom' } ) console.log('Using custom git at:', gitLocation) ``` -------------------------------- ### Configure HTTPS_PROXY for installation Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md Example of setting an authenticated HTTPS proxy before running the installation command. ```bash # Corporate proxy with authentication export HTTPS_PROXY=https://user:pass@proxy.corp:8443 npm install dugite ``` -------------------------------- ### Setup with custom environment variables Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Example showing how to pass custom environment variables to the setupEnvironment function. ```typescript import { setupEnvironment } from 'dugite' // Setup with custom env vars const { env, gitLocation } = setupEnvironment({ 'GIT_HTTP_USER_AGENT': 'MyApp/1.0', 'GIT_TRACE': '1', 'LANG': 'en_US.UTF-8' }) // env now contains merged variables ``` -------------------------------- ### Basic setup with embedded Git Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md A basic usage example of setupEnvironment using the default embedded Git configuration. ```typescript import { setupEnvironment } from 'dugite' // Basic setup with embedded Git const { env, gitLocation } = setupEnvironment({}) console.log('Git location:', gitLocation) console.log('GIT_EXEC_PATH:', env.GIT_EXEC_PATH) ``` -------------------------------- ### 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 ``` -------------------------------- ### Configure GIT_EXEC_PATH Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md Example of setting the GIT_EXEC_PATH to a specific version directory. ```typescript process.env.GIT_EXEC_PATH = '/opt/git-2.45/libexec/git-core' ``` -------------------------------- ### Initialize Repository with Templates Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md Example of initializing a repository which utilizes the configured GIT_TEMPLATE_DIR. ```typescript import { exec } from 'dugite' const result = await exec(['init'], '/new/repo') // Uses dugite's git templates (hooks, descriptions, etc.) ``` -------------------------------- ### resolveGitDir() usage examples Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Examples showing how to resolve the Git directory path for both embedded and custom Git installations. ```typescript import { resolveGitDir } from 'dugite' // Embedded Git const dir = resolveGitDir() // Returns path like: /home/user/node_modules/dugite/git // Custom Git const customDir = resolveGitDir('/opt/git-2.45') // Returns: /opt/git-2.45 ``` -------------------------------- ### Minimal Setup with exec Source: https://github.com/desktop/dugite/blob/main/_autodocs/09-export-summary.md Basic usage of the exec function to run a git command in a repository. ```typescript import { exec } from 'dugite' const result = await exec(['status'], '/repo') ``` -------------------------------- ### Using External Git Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Configures an external Git installation path and initializes the environment. ```typescript import { resolveGitBinary, setupEnvironment } from 'dugite' // Point to external Git installation process.env.LOCAL_GIT_DIRECTORY = '/usr/local' const gitBinary = resolveGitBinary() console.log('Using git at:', gitBinary) const { env, gitLocation } = setupEnvironment({}) console.log('Git location:', gitLocation) ``` -------------------------------- ### resolveGitBinary() usage examples Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Examples showing how to resolve the Git binary path using the default embedded Git or a custom directory. ```typescript import { resolveGitBinary } from 'dugite' // Use embedded Git const gitPath = resolveGitBinary() console.log(gitPath) // Windows: C:\...\node_modules\dugite\git\cmd\git.exe // Unix: /home/.../node_modules/dugite/git/bin/git // Use custom Git directory const customGit = resolveGitBinary('/usr/local') console.log(customGit) // Windows: /usr/local\cmd\git.exe // Unix: /usr/local/bin/git ``` -------------------------------- ### IGitExecutionOptions Usage Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md Demonstrates configuring execution options including environment variables, stdin, and buffer limits. ```typescript import { exec, IGitExecutionOptions } from 'dugite' const options: IGitExecutionOptions = { env: { 'GIT_TRACE': '1' }, stdin: 'commit message', encoding: 'utf8', maxBuffer: 1024 * 1024 * 10 // 10MB } const result = await exec(['commit', '-F', '-'], '/repo', options) ``` -------------------------------- ### resolveGitExecPath() usage example Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Example showing how to import and call resolveGitExecPath to retrieve the Git libexec path. ```typescript import { resolveGitExecPath } from 'dugite' const execPath = resolveGitExecPath() // Unix: /home/user/node_modules/dugite/git/libexec/git-core // Win: C:\...\git\mingw64\libexec\git-core ``` -------------------------------- ### resolveEmbeddedGitDir() usage example Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Example showing how to call resolveEmbeddedGitDir and handle potential errors for unsupported platforms. ```typescript import { resolveEmbeddedGitDir } from 'dugite' try { const dir = resolveEmbeddedGitDir() console.log(dir) } catch (error) { console.error('Platform not supported:', error.message) } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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) } }) }) ``` -------------------------------- ### 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() ``` ``` -------------------------------- ### IGitSpawnOptions Usage Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md Demonstrates how to pass environment variables to the spawn function using IGitSpawnOptions. ```typescript import { spawn, IGitSpawnOptions } from 'dugite' const options: IGitSpawnOptions = { env: { 'GIT_TRACE': '1' } } const process = spawn(['log', '--oneline'], '/repo', options) ``` -------------------------------- ### Example: git apply Source: https://github.com/desktop/dugite/blob/main/_autodocs/07-stream-utilities.md Shows how to use the suppression logic with a git apply command to avoid EPIPE errors when writing to stdin. ```typescript const process = spawn(['apply', '--check'], '/repo') // Write a small, invalid patch process.stdin.write('not a valid patch') process.stdin.end() // git apply closes stdin after reading header // Without suppression: EPIPE error thrown // With suppression: Error handled, exit code checked instead ``` -------------------------------- ### IGitStringResult Usage Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md Demonstrates using the exec function with explicit string encoding options. ```typescript import { exec, IGitStringExecutionOptions } from 'dugite' const options: IGitStringExecutionOptions = { encoding: 'utf8' // Explicit (also default) } const result = await exec(['log', '--oneline'], '/repo', options) // result.stdout is string, result.stderr is string const lines = result.stdout.split('\n') ``` -------------------------------- ### Configure Custom Git Build Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md Use a custom-compiled Git installation by pointing LOCAL_GIT_DIRECTORY to the custom directory path. ```typescript import { exec } from 'dugite' // Use custom-compiled Git process.env.LOCAL_GIT_DIRECTORY = '/opt/git-custom' const result = await exec(['status'], '/repo') // Uses /opt/git-custom/bin/git ``` -------------------------------- ### EnvMap Usage Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md Shows how EnvMap handles case-insensitive lookups on Windows while preserving original casing for iteration. ```typescript import { EnvMap } from 'dugite' const envMap = new EnvMap([ ['PATH', '/usr/bin'], ['GIT_TRACE', '1'] ]) // On Windows, case-insensitive envMap.set('path', '/opt/bin') // Updates existing PATH envMap.get('PATH') // Returns '/opt/bin' envMap.get('path') // Returns '/opt/bin' (Windows only) // Iterate with original casing for (const [key, value] of envMap) { console.log(`${key}=${value}`) } ``` -------------------------------- ### Development Setup with Tracing Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md Configures Dugite for development by enabling Git tracing and verbose CURL output via environment variables. ```typescript import { exec } from 'dugite' // Development with tracing const result = await exec(['clone', 'https://...'], '/dest', { env: { 'GIT_HTTP_USER_AGENT': 'DugiteDevApp/1.0', 'GIT_TRACE': '1', 'GIT_CURL_VERBOSE': '1' } }) ``` -------------------------------- ### IGitResult Usage Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md Demonstrates using the exec function, which returns an IGitResult by default. ```typescript import { exec } from 'dugite' const result = await exec(['status'], '/repo') // result is IGitResult with string stdout/stderr (default) const exitCode: number = result.exitCode const output: string = result.stdout ``` -------------------------------- ### Real-Time Data Streaming Source: https://github.com/desktop/dugite/blob/main/_autodocs/07-stream-utilities.md Example of streaming data line by line to a spawned process while handling potential EPIPE errors. ```typescript import { spawn } from 'dugite' const process = spawn(['apply'], '/repo') process.stdin.on('error', err => { if (err.code !== 'EPIPE') { console.error('Unexpected error:', err) } }) // Stream patch data line by line lineReader.on('line', line => { process.stdin.write(line + '\n') }) // If git closes stdin, EPIPE is suppressed ``` -------------------------------- ### IGitStringExecutionOptions Usage Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md Demonstrates using IGitStringExecutionOptions to ensure the command result stdout is treated as a string. ```typescript import { exec, IGitStringExecutionOptions } from 'dugite' const options: IGitStringExecutionOptions = { encoding: 'utf8' } const result = await exec(['log', '--oneline'], '/repo', options) // TypeScript knows result.stdout is string ``` -------------------------------- ### IGitBufferResult Usage Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md Demonstrates executing a git command with encoding set to 'buffer' to retrieve binary data. ```typescript import { exec, IGitBufferExecutionOptions } from 'dugite' const options: IGitBufferExecutionOptions = { encoding: 'buffer' } const result = await exec( ['show', 'HEAD:image.png'], '/repo', options ) // result.stdout is Buffer const buffer: Buffer = result.stdout const byteSize = buffer.length ``` -------------------------------- ### Handling Malformed Input Source: https://github.com/desktop/dugite/blob/main/_autodocs/07-stream-utilities.md Example of using exec() where Git rejects input early and closes stdin. ```typescript import { exec } from 'dugite' // Git rejects input early and closes stdin const result = await exec( ['hash-object', '-w', '--stdin'], '/repo', { stdin: '' } // Empty, might be rejected ) // EPIPE from early closure is suppressed ``` -------------------------------- ### CI/CD Setup with Identity Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md Configures Dugite for CI/CD environments by setting author and committer identity variables. ```typescript import { exec } from 'dugite' // CI with identity and SSL verification const result = await exec(['clone', 'https://...'], '/dest', { env: { 'GIT_AUTHOR_NAME': 'CI Bot', 'GIT_AUTHOR_EMAIL': 'ci@example.com', 'GIT_COMMITTER_NAME': 'CI Bot', 'GIT_COMMITTER_EMAIL': 'ci@example.com', 'GIT_HTTP_USER_AGENT': 'CIBot/1.0' } }) ``` -------------------------------- ### Use Custom Git Installation Source: https://github.com/desktop/dugite/blob/main/_autodocs/10-usage-patterns.md Overrides the default embedded Git by setting the LOCAL_GIT_DIRECTORY environment variable before resolving the binary path. ```typescript import { exec, resolveGitBinary } from 'dugite' // Use system git instead of embedded process.env.LOCAL_GIT_DIRECTORY = '/usr/local' const gitPath = resolveGitBinary() console.log('Using git from:', gitPath) const result = await exec(['--version'], '.') console.log(result.stdout) ``` -------------------------------- ### setupEnvironment() Source: https://github.com/desktop/dugite/blob/main/_autodocs/09-export-summary.md Configures the process environment for git execution. ```APIDOC ## setupEnvironment(environmentVariables: Record, processEnv?: Record) ### Description Prepares the environment variables required for executing git commands. ### Parameters - **environmentVariables** (Record) - Required - The base environment variables. - **processEnv** (Record) - Optional - The current process environment. ### Returns - **{ env: Record, gitLocation: string }** - The configured environment and git location. ``` -------------------------------- ### GitErrorRegexes Pattern Examples Source: https://github.com/desktop/dugite/blob/main/_autodocs/06-error-utilities.md Examples of regex patterns mapped to their corresponding GitError enum values. ```javascript // Example patterns (actual patterns may differ) "fatal: bad (?:numeric|boolean) config value '(.+)' for '(.+)'" → GitError.BadConfigValue "fatal: Authentication failed" → GitError.SSHAuthenticationFailed "(Merge conflict|Automatic merge failed.*)" → GitError.MergeConflicts "fatal: refusing to merge unrelated histories" → GitError.CannotMergeUnrelatedHistories "error: GH006: Protected branch update failed" → GitError.ProtectedBranchRequiresReview ``` -------------------------------- ### setupEnvironment(options) Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Configures the environment for Git execution, merging custom variables like GIT_HTTP_USER_AGENT or GIT_TRACE with internal defaults. ```APIDOC ## setupEnvironment(options) ### Description Prepares the environment object required for executing Git commands. It merges provided custom environment variables with internal defaults such as GIT_EXEC_PATH and GIT_CONFIG_SYSTEM. ### Parameters - **options** (Object) - Required - A map of environment variable keys and values to be merged into the process environment. ### Response - **env** (Object) - The resulting environment object. - **gitLocation** (String) - The resolved path to the Git binary. ``` -------------------------------- ### parseBadConfigValueErrorInfo() Usage Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/03-error-types.md Example showing how to parse a stderr string containing a bad numeric config value. ```typescript const stderr = "fatal: bad numeric config value '999999' for 'core.preloadindex'" const info = parseBadConfigValueErrorInfo(stderr) // { key: 'core.preloadindex', value: '999999' } ``` -------------------------------- ### setupEnvironment() Function Source: https://github.com/desktop/dugite/blob/main/_autodocs/09-export-summary.md Configures the process environment for git execution. ```typescript function setupEnvironment( environmentVariables: Record, processEnv?: Record ): { env: Record gitLocation: string } ``` -------------------------------- ### Set DUGITE_CACHE_DIR during installation Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md Sets the cache directory for downloading embedded Git binaries during the npm install process. ```bash DUGITE_CACHE_DIR=/path/to/cache npm install dugite ``` -------------------------------- ### Integration with exec() Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Demonstrates how exec() automatically calls setupEnvironment() and merges provided environment options. ```typescript import { exec } from 'dugite' // This internally: // 1. Calls setupEnvironment() with your env options // 2. Merges GIT_EXEC_PATH, GIT_CONFIG_SYSTEM, etc. // 3. Spawns git with the configured environment const result = await exec(['status'], '/path/to/repo', { env: { 'GIT_HTTP_USER_AGENT': 'MyApp/1.0' } }) ``` -------------------------------- ### Execute Git Commands with exec and spawn Source: https://github.com/desktop/dugite/blob/main/_autodocs/00-index.md Demonstrates how to use exec for buffered output and spawn for streaming large output from Git commands. ```typescript import { exec, spawn } from 'dugite' // Buffer output (use for small output) const result = await exec(['status'], '/repo') // Stream output (use for large output) const process = spawn(['log', '--all'], '/repo') process.stdout?.pipe(process.stdout) ``` -------------------------------- ### Configuration Patterns for Environment Variables Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md Demonstrates two approaches for setting environment variables: merging with process.env or using IGitExecutionOptions. ```typescript // Merge approach const env = { ...process.env, 'GIT_TRACE': '1' } // Or use IGitExecutionOptions const options: IGitExecutionOptions = { env: { 'GIT_TRACE': '1' } } ``` -------------------------------- ### Override LOCAL_GIT_DIRECTORY Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Sets the environment variable to override the location of the Git installation. ```typescript process.env.LOCAL_GIT_DIRECTORY = '/opt/git-2.45' // Git executable will be resolved from this directory // Windows: /opt/git-2.45\cmd\git.exe // Unix: /opt/git-2.45/bin/git ``` -------------------------------- ### spawn(args, path, options) Source: https://github.com/desktop/dugite/blob/main/_autodocs/00-index.md Spawns a Git process and returns a streamable interface. This is suitable for commands that produce large amounts of output. ```APIDOC ## spawn(args, path, options) ### Description Spawns a Git process and returns a child process object for streaming output. ### Parameters - **args** (string[]) - Required - Array of Git command arguments. - **path** (string) - Required - The working directory for the Git command. - **options** (object) - Optional - Configuration options. ### Example ```typescript const process = spawn(['log', '--all'], '/repo') process.stdout?.pipe(process.stdout) ``` ``` -------------------------------- ### Configuring Multiple Custom Variables Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Uses setupEnvironment to prepare multiple environment variables for use with exec or spawn. ```typescript import { setupEnvironment } from 'dugite' const { env, gitLocation } = setupEnvironment({ 'GIT_HTTP_USER_AGENT': 'MyApp/1.0', 'GIT_TRACE': '1', 'GIT_CURL_VERBOSE': '1', 'GIT_AUTHOR_NAME': 'CI Bot', 'GIT_AUTHOR_EMAIL': 'ci@example.com', 'GIT_COMMITTER_NAME': 'CI Bot', 'GIT_COMMITTER_EMAIL': 'ci@example.com' }) // env is now ready to pass to exec/spawn ``` -------------------------------- ### Get Repository Status Source: https://github.com/desktop/dugite/blob/main/_autodocs/00-index.md Retrieves the status of the repository in porcelain format for machine-readable output. ```typescript import { exec } from 'dugite' const result = await exec(['status', '--porcelain'], '/repo') const files = result.stdout.split('\n').filter(line => line) files.forEach(file => console.log(file)) ``` -------------------------------- ### Configure Git Environment Source: https://github.com/desktop/dugite/blob/main/_autodocs/00-index.md Illustrates how to set a custom Git binary directory and pass environment variables to Git commands. ```typescript import { exec, resolveGitBinary } from 'dugite' // Use custom Git installation process.env.LOCAL_GIT_DIRECTORY = '/usr/local' // Run git commands with custom env const result = await exec(['clone', 'https://...'], '/dest', { env: { 'GIT_HTTP_USER_AGENT': 'MyApp/1.0', 'GIT_AUTHOR_NAME': 'Bot' } }) ``` -------------------------------- ### Detect External Git Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md Programmatically detect an external Git installation and configure LOCAL_GIT_DIRECTORY accordingly. ```typescript import { resolveGitBinary } from 'dugite' // Find Git using external tool const findGit = require('find-git-exec') let git try { git = await findGit() } catch { // Use embedded Git } if (git?.path) { const path = require('path') process.env.LOCAL_GIT_DIRECTORY = path.dirname(path.dirname(git.path)) } const gitBinary = resolveGitBinary() console.log('Using git at:', gitBinary) ``` -------------------------------- ### Basic Streaming Usage Source: https://github.com/desktop/dugite/blob/main/_autodocs/02-spawn.md Demonstrates how to spawn a git log process and listen to its stdout, stderr, and close events. ```typescript import { spawn } from 'dugite' const process = spawn(['log', '--oneline'], '/path/to/repo') process.stdout!.on('data', (chunk: Buffer) => { console.log(chunk.toString('utf8')) }) process.stderr!.on('data', (chunk: Buffer) => { console.error(chunk.toString('utf8')) }) process.on('close', (code) => { console.log(`git log exited with code ${code}`) }) ``` -------------------------------- ### IGitBufferExecutionOptions Usage Example Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md Demonstrates using IGitBufferExecutionOptions to ensure the command result stdout is treated as a Buffer. ```typescript import { exec, IGitBufferExecutionOptions } from 'dugite' const options: IGitBufferExecutionOptions = { encoding: 'buffer' } const result = await exec(['show', 'HEAD:binary.dat'], '/repo', options) // TypeScript knows result.stdout is Buffer ``` -------------------------------- ### Configure System Git Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md Use a system-installed Git by pointing LOCAL_GIT_DIRECTORY to the system root directory. ```typescript import { exec } from 'dugite' // Use system-installed Git process.env.LOCAL_GIT_DIRECTORY = '/usr' const result = await exec(['status'], '/repo') // Uses /usr/bin/git (macOS/Linux) or /usr\cmd\git.exe (Windows) ``` -------------------------------- ### setupEnvironment(environmentVariables, processEnv) Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Configures the process environment for Git execution by merging custom environment variables with the base environment and resolving the Git executable location. ```APIDOC ## setupEnvironment(environmentVariables, processEnv) ### Description Configures the process environment for Git execution. It merges custom environment variables with the provided base environment (or process.env) and resolves the path to the Git executable. ### Parameters - **environmentVariables** (Record) - Required - Custom environment variables to merge (override process.env). - **processEnv** (Record) - Optional - Base environment to use (defaults to process.env). ### Return Value - **env** (Record) - Complete environment object for subprocess. - **gitLocation** (string) - Resolved path to git executable. ### Usage Example ```typescript import { setupEnvironment } from 'dugite' const { env, gitLocation } = setupEnvironment({ 'GIT_HTTP_USER_AGENT': 'MyApp/1.0' }) ``` ``` -------------------------------- ### spawn() Source: https://github.com/desktop/dugite/blob/main/_autodocs/09-export-summary.md Executes a git command and returns a streaming ChildProcess. ```APIDOC ## spawn(args: string[], path: string, opts?: IGitSpawnOptions) ### Description Execute a git command and return a streaming ChildProcess for handling output asynchronously. ### Parameters - **args** (string[]) - Required - The arguments to pass to the git command. - **path** (string) - Required - The working directory path for the git command. - **opts** (IGitSpawnOptions) - Optional - Spawn configuration options. ### Returns - **ChildProcess** - The spawned child process. ``` -------------------------------- ### 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 ``` -------------------------------- ### Advanced Configuration with IGitExecutionOptions Source: https://github.com/desktop/dugite/blob/main/_autodocs/09-export-summary.md Configuring execution with environment variables and abort signals. ```typescript import { exec, IGitExecutionOptions, resolveGitBinary, setupEnvironment } from 'dugite' const options: IGitExecutionOptions = { env: { 'GIT_TRACE': '1' }, signal: AbortSignal.timeout(30000) } const result = await exec(['clone', '...'], '/dest', options) ``` -------------------------------- ### Timeout Handling Source: https://github.com/desktop/dugite/blob/main/_autodocs/02-spawn.md Demonstrates how to implement a timeout for a git process using setTimeout and process.kill. ```typescript import { spawn } from 'dugite' const process = spawn(['fetch', 'origin'], '/path/to/repo') const timeout = setTimeout(() => { process.kill('SIGTERM') }, 30000) // 30 second timeout process.on('close', () => { clearTimeout(timeout) }) ``` -------------------------------- ### parseError() usage with if-else Source: https://github.com/desktop/dugite/blob/main/_autodocs/06-error-utilities.md Example of using parseError to handle specific git error cases after a failed command execution. ```typescript import { exec, parseError, GitError } from 'dugite' const result = await exec(['pull', 'origin', 'main'], '/repo') if (result.exitCode !== 0) { const error = parseError(result.stderr) if (error === null) { console.log('Unknown git error') console.log(result.stderr) } else if (error === GitError.MergeConflicts) { console.log('Merge has conflicts') } else if (error === GitError.PushNotFastForward) { console.log('Push rejected (need to pull first)') } else { console.log(`Git error code: ${error}`) } } ``` -------------------------------- ### setupEnvironment return value structure Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md The structure of the object returned by setupEnvironment, containing the environment map and the resolved Git path. ```typescript { env: Record gitLocation: string } ``` -------------------------------- ### Get Current Branch with rev-parse Source: https://github.com/desktop/dugite/blob/main/_autodocs/10-usage-patterns.md Retrieves the current branch name by executing 'git rev-parse --abbrev-ref HEAD'. ```typescript import { exec } from 'dugite' async function getCurrentBranch(repoPath: string): Promise { const result = await exec(['rev-parse', '--abbrev-ref', 'HEAD'], repoPath) if (result.exitCode !== 0) { throw new Error('Failed to get current branch') } return result.stdout.trim() } const branch = await getCurrentBranch('/repo') // 'main' ``` -------------------------------- ### Configure persistent DUGITE_CACHE_DIR for Docker Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md Example of exporting the cache directory variable to persist Git downloads across container builds. ```bash # Use persistent cache for Docker builds export DUGITE_CACHE_DIR=/build/cache npm install dugite # Cache persists across container builds ``` -------------------------------- ### Configure Repository Settings Source: https://github.com/desktop/dugite/blob/main/_autodocs/10-usage-patterns.md Iterates through an array of key-value pairs to apply Git configurations to a specific repository path using the exec function. ```typescript import { exec } from 'dugite' async function configureRepository(repoPath: string) { const configs = [ ['user.name', 'CI Bot'], ['user.email', 'ci@example.com'], ['core.autocrlf', 'input'], ['pull.rebase', 'true'] ] for (const [key, value] of configs) { const result = await exec( ['config', key, value], repoPath ) if (result.exitCode !== 0) { console.error(`Failed to set ${key}: ${result.stderr}`) } else { console.log(`Set ${key} = ${value}`) } } } await configureRepository('/repo') ``` -------------------------------- ### Handling Large stdin Data Source: https://github.com/desktop/dugite/blob/main/_autodocs/07-stream-utilities.md Example of using exec() with large input data where Git might close stdin early. ```typescript import { exec } from 'dugite' // Git might close stdin after reading first chunk const largeData = fs.readFileSync('large.patch', 'utf8') const result = await exec( ['apply'], '/repo', { stdin: largeData } ) // ignoreClosedInputStream prevents EPIPE even if git closes stdin ``` -------------------------------- ### IGitSpawnOptions Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md Configuration interface for the spawn() command, allowing for the definition of custom environment variables. ```APIDOC ## IGitSpawnOptions ### Description Configuration interface used to define environment variables when executing Git commands via the spawn() function. ### Properties - **env** (Record) - Optional - Environment variables to merge into the process environment. ### Example ```typescript import { spawn, IGitSpawnOptions } from 'dugite' const options: IGitSpawnOptions = { env: { 'GIT_TRACE': '1' } } const process = spawn(['log', '--oneline'], '/repo', options) ``` ``` -------------------------------- ### Handle BadConfigValue error in execution flow Source: https://github.com/desktop/dugite/blob/main/_autodocs/06-error-utilities.md Example of checking for a BadConfigValue error after executing a git command and extracting the error details. ```typescript import { exec, parseError, parseBadConfigValueErrorInfo, GitError } from 'dugite' const result = await exec(['config', '--list'], '/repo') if (result.exitCode !== 0) { const error = parseError(result.stderr) if (error === GitError.BadConfigValue) { const info = parseBadConfigValueErrorInfo(result.stderr) if (info) { console.error(`Invalid config: '${info.value}' for key '${info.key}'`) console.error(`Expected type: boolean or numeric`) console.error(`Please fix your .git/config or global ~/.gitconfig`) } else { console.error('BadConfigValue error but could not parse details') console.error(result.stderr) } } } ``` -------------------------------- ### exec(args, path, options) Source: https://github.com/desktop/dugite/blob/main/_autodocs/01-exec.md Executes a Git command with the provided arguments in the specified working directory. ```APIDOC ## exec(args, path, options) ### Description Executes a Git command and captures the output with automatic environment setup. Supports returning results as strings or buffers based on the provided options. ### Parameters - **args** (string[]) - Required - Array of Git command arguments (e.g., ['status']) - **path** (string) - Required - Working directory path for Git execution - **options** (IGitExecutionOptions) - Optional - Execution configuration ### Options (IGitExecutionOptions) - **env** (Record) - Optional - Environment variables to merge with process environment - **stdin** (string | Buffer) - Optional - Data to write to git process stdin - **stdinEncoding** (BufferEncoding) - Optional - Encoding for stdin if passed as string - **encoding** (BufferEncoding | 'buffer') - Optional - Output encoding: standard BufferEncoding for string output, 'buffer' for Buffer output (Default: 'utf8') - **maxBuffer** (number) - Optional - Maximum bytes allowed on stdout/stderr before process termination (Default: Infinity) - **processCallback** ((process: ChildProcess) => void) - Optional - Callback invoked after process spawning - **signal** (AbortSignal) - Optional - Abort signal for process cancellation - **killSignal** (ExecFileOptions['killSignal']) - Optional - Signal sent to process on abort (Default: 'SIGTERM') ``` -------------------------------- ### Choose between exec and spawn for output handling Source: https://github.com/desktop/dugite/blob/main/_autodocs/00-index.md Use exec for small outputs that require automatic buffering and spawn for large outputs that require manual streaming. ```typescript // Small output — use exec() const result = await exec(['log', '-1'], '/repo') // Large output — use spawn() const process = spawn(['log', '--all'], '/repo') process.stdout?.pipe(destination) ``` -------------------------------- ### Perform Manual Cancellation Source: https://github.com/desktop/dugite/blob/main/_autodocs/10-usage-patterns.md Uses AbortController to manually trigger cancellation of a Git clone operation, for example, based on a user-defined timeout or action. ```typescript import { exec } from 'dugite' async function performCloneWithCancel(url: string, dest: string) { const controller = new AbortController() // Cancel after user action or timeout const userCancelButton = setTimeout(() => { console.log('User cancelled') controller.abort() }, 60000) try { const result = await exec( ['clone', url, dest], '.', { signal: controller.signal } ) if (result.exitCode === 0) { console.log('Clone complete') } } catch (error) { console.error('Clone cancelled or failed') } finally { clearTimeout(userCancelButton) } } ``` -------------------------------- ### Using ignoreClosedInputStream with a child process Source: https://github.com/desktop/dugite/blob/main/_autodocs/07-stream-utilities.md Example showing how to use ignoreClosedInputStream to prevent unhandled errors when a child process closes stdin early. ```typescript import { ChildProcess } from 'child_process' import { ignoreClosedInputStream } from 'dugite' const process: ChildProcess = spawn(...) // Prevent unhandled errors when git closes stdin early ignoreClosedInputStream(process) // Now this won't throw even if git closes stdin process.stdin?.write('some data') ``` -------------------------------- ### parseError() usage with switch statement Source: https://github.com/desktop/dugite/blob/main/_autodocs/06-error-utilities.md Example of using parseError within a handler function to manage git failures via a switch statement. ```typescript import { exec, parseError, GitError } from 'dugite' async function handleGitFailure( stderr: string, operation: string ): Promise { const error = parseError(stderr) switch (error) { case GitError.NotAGitRepository: console.error(`${operation} failed: not a git repository`) break case GitError.LocalChangesOverwritten: console.error(`${operation} failed: commit your changes first`) break case GitError.AuthenticationFailed: console.error(`${operation} failed: check your credentials`) break case null: console.error(`${operation} failed (unknown error):`) console.error(stderr) break default: console.error(`${operation} failed with error code ${error}`) } } const result = await exec(['checkout', 'main'], '/repo') if (result.exitCode !== 0) { await handleGitFailure(result.stderr, 'checkout') } ``` -------------------------------- ### spawn(args: string[], path: string, opts?: IGitSpawnOptions): ChildProcess Source: https://github.com/desktop/dugite/blob/main/_autodocs/02-spawn.md Executes a Git command and returns a streaming ChildProcess for manual I/O handling. ```APIDOC ## spawn(args, path, opts) ### Description Executes a Git command and returns a streaming ChildProcess for manual I/O handling. The function synchronously throws if the Git executable cannot be found or if there are permission issues. ### Signature `spawn(args: string[], path: string, opts?: IGitSpawnOptions): ChildProcess` ### Parameters - **args** (`string[]`) - Required - Array of Git command arguments. - **path** (`string`) - Required - Working directory for Git execution. - **opts** (`IGitSpawnOptions`) - Optional - Configuration options. #### IGitSpawnOptions - **env** (`Record`) - Optional - Environment variables merged with the current process. ### Return Type Returns a standard Node.js `child_process.ChildProcess` with access to `stdout`, `stderr`, `stdin`, `pid`, and `kill()` methods, as well as standard process events ('close', 'error', 'exit', 'disconnect', 'message'). ``` -------------------------------- ### setupEnvironment function signature Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md The function signature for configuring the Git environment, accepting custom variables and an optional base environment. ```typescript export function setupEnvironment( environmentVariables: Record, processEnv?: Record ): { env: Record gitLocation: string } ``` -------------------------------- ### EnvMap Source: https://github.com/desktop/dugite/blob/main/_autodocs/05-types.md A platform-aware Map implementation for environment variables that handles case-insensitivity on Windows. ```APIDOC ## EnvMap ### Description A Map-like class for managing environment variables. On Windows, key lookups are case-insensitive while preserving original casing for iteration. ### Methods - **get(key: string)**: Returns the value associated with the key. - **set(key: string, value: string | undefined)**: Sets a value for the key and returns the instance for chaining. - **has(key: string)**: Returns true if the key exists. - **delete(key: string)**: Removes the entry for the key. - **clear()**: Removes all entries. ### Properties - **size** (number) - The number of entries in the map. ### Example ```typescript import { EnvMap } from 'dugite' const envMap = new EnvMap([['PATH', '/usr/bin']]) envMap.set('path', '/opt/bin') console.log(envMap.get('PATH')) // '/opt/bin' ``` ``` -------------------------------- ### Proxy configuration format Source: https://github.com/desktop/dugite/blob/main/_autodocs/08-configuration.md The expected format for proxy environment variables. ```text protocol://[username:password@]host[:port] ``` -------------------------------- ### Writing to stdin Source: https://github.com/desktop/dugite/blob/main/_autodocs/02-spawn.md Shows how to write data to the stdin of a spawned git process. ```typescript import { spawn } from 'dugite' const process = spawn( ['hash-object', '-w', '--stdin'], '/path/to/repo' ) process.stdin!.write('Hello, git!\n') process.stdin!.end() let hash = '' process.stdout!.on('data', (chunk: Buffer) => { hash += chunk.toString('utf8').trim() }) process.on('close', () => { console.log(`Object hash: ${hash}`) }) ``` -------------------------------- ### Enable Git Tracing Source: https://github.com/desktop/dugite/blob/main/_autodocs/10-usage-patterns.md Passes environment variables to the exec options to enable detailed Git tracing, performance logging, and verbose CURL output. ```typescript import { exec } from 'dugite' async function debugGitOperation(args: string[], repoPath: string) { const result = await exec(args, repoPath, { env: { 'GIT_TRACE': '1', 'GIT_TRACE_PERFORMANCE': '1', 'GIT_CURL_VERBOSE': '1' } }) console.log('=== STDOUT ===') console.log(result.stdout) console.log('\n=== STDERR (includes trace) ===') console.log(result.stderr) console.log('\n=== EXIT CODE ===') console.log(result.exitCode) return result } await debugGitOperation(['clone', 'https://...', '/dest'], '.') ``` -------------------------------- ### exec() Source: https://github.com/desktop/dugite/blob/main/_autodocs/09-export-summary.md Executes a git command and buffers the output. Returns a promise that resolves to a result object containing the command output. ```APIDOC ## exec(args: string[], path: string, options?: IGitExecutionOptions) ### Description Execute a git command and buffer the output. Supports string, buffer, or generic result types based on the provided options. ### Parameters - **args** (string[]) - Required - The arguments to pass to the git command. - **path** (string) - Required - The working directory path for the git command. - **options** (IGitExecutionOptions) - Optional - Execution configuration options. ### Returns - **Promise** - A promise resolving to the command execution result. ``` -------------------------------- ### Scenario: Early stdin Closure Source: https://github.com/desktop/dugite/blob/main/_autodocs/07-stream-utilities.md Demonstrates the difference between unhandled EPIPE errors and suppressed errors when git closes stdin prematurely. ```javascript // Without ignoreClosedInputStream: process.stdin.write('large data...') // Git closes stdin // UnhandledError: EPIPE (Broken pipe) // With ignoreClosedInputStream: process.stdin.write('large data...') // Git closes stdin // Error is suppressed, process exits cleanly ``` -------------------------------- ### Create Custom Commits with stdin Source: https://github.com/desktop/dugite/blob/main/_autodocs/10-usage-patterns.md Demonstrates how to pass a commit message via stdin using the -F - flag and how to set custom environment variables for author information. ```typescript import { exec } from 'dugite' async function createCommitWithMessage( repoPath: string, message: string, author?: { name: string; email: string } ) { const env: Record = {} if (author) { env['GIT_AUTHOR_NAME'] = author.name env['GIT_AUTHOR_EMAIL'] = author.email env['GIT_COMMITTER_NAME'] = author.name env['GIT_COMMITTER_EMAIL'] = author.email } // Stage all changes await exec(['add', '.'], repoPath) // Create commit with message from stdin const result = await exec( ['commit', '-F', '-'], repoPath, { stdin: message, env } ) if (result.exitCode !== 0) { const stderr = result.stderr as string if (stderr.includes('nothing to commit')) { throw new Error('No changes to commit') } throw new Error(`Commit failed: ${stderr}`) } return result.stdout } await createCommitWithMessage( '/repo', 'Fix: resolve merge conflicts', { name: 'CI Bot', email: 'ci@example.com' } ) ``` -------------------------------- ### resolveGitBinary() Source: https://github.com/desktop/dugite/blob/main/_autodocs/04-git-environment.md Resolves the path to the Git binary based on the current environment configuration. ```APIDOC ## resolveGitBinary() ### Description Returns the absolute path to the Git binary. It respects the LOCAL_GIT_DIRECTORY environment variable if set. ``` -------------------------------- ### Batch Process Multiple Repositories Sequentially Source: https://github.com/desktop/dugite/blob/main/_autodocs/10-usage-patterns.md Iterates through a list of repository paths to execute a fetch command on each. Uses AbortSignal.timeout to enforce a 30-second limit per operation and captures exit codes and stderr for error reporting. ```typescript import { exec } from 'dugite' async function fetchAllRepositories(repoPaths: string[]) { const results: Map = new Map() for (const repoPath of repoPaths) { try { const result = await exec(['fetch', 'origin'], repoPath, { signal: AbortSignal.timeout(30000) }) if (result.exitCode === 0) { results.set(repoPath, { success: true }) } else { results.set(repoPath, { success: false, error: (result.stderr as string).slice(0, 100) }) } } catch (error) { results.set(repoPath, { success: false, error: error instanceof Error ? error.message : 'Unknown error' }) } } return results } const repos = ['/repo1', '/repo2', '/repo3'] const fetchResults = await fetchAllRepositories(repos) for (const [repo, result] of fetchResults) { if (result.success) { console.log(`✓ ${repo}`) } else { console.log(`✗ ${repo}: ${result.error}`) } } ``` -------------------------------- ### Error Handling with parseError and ExecError Source: https://github.com/desktop/dugite/blob/main/_autodocs/09-export-summary.md Demonstrates how to handle git command exit codes and execution failures using parseError and ExecError. ```typescript import { exec, parseError, GitError, ExecError } from 'dugite' try { const result = await exec(['pull'], '/repo') if (result.exitCode !== 0) { const error = parseError(result.stderr) // Handle error } } catch (error) { if (error instanceof ExecError) { // Handle launch failure } } ``` -------------------------------- ### Handling ExecError Launch Failures Source: https://github.com/desktop/dugite/blob/main/_autodocs/03-error-types.md Wrap exec calls in a try-catch block to catch ExecError instances, which indicate failures to launch the git binary itself, such as missing files or permission issues. ```typescript import { exec, ExecError } from 'dugite' try { const result = await exec(['status'], '/path/to/repo') } catch (error) { if (error instanceof ExecError) { if (error.code === 'ENOENT') { console.error('Git executable not found') } else if (error.code === 'EACCES') { console.error('Permission denied on git binary') } else { console.error(`Launch failed: ${error.message}`) } } else { throw error } } ```