ensure_lines_in_file
Manages specific lines in remote files by adding or removing them as needed, ensuring configuration consistency across SSH-connected servers.
Instructions
Ensures specific lines are present or absent in a file
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| sessionId | Yes | SSH session ID | |
| path | Yes | File path | |
| lines | Yes | Lines to manage | |
| state | Yes | Desired state |
Implementation Reference
- src/ensure.ts:234-324 (handler)The handler function `ensureLinesInFile` which verifies existence of lines in a file and appends them if they are missing.
export async function ensureLinesInFile( sessionId: string, filePath: string, lines: string[], createIfMissing: boolean = true, sudoPassword?: string ): Promise<LinesInFileResult> { logger.debug('Ensuring lines in file', { sessionId, filePath, lineCount: lines.length }); try { const osInfo = await sessionManager.getOSInfo(sessionId); let fileContent = ''; let fileExists = false; // Check if file exists and read its content if (await pathExists(sessionId, filePath)) { fileExists = true; fileContent = await readFile(sessionId, filePath); } else if (!createIfMissing) { throw createFilesystemError( `File ${filePath} does not exist and createIfMissing is false` ); } // Check which lines are missing const existingLines = fileContent.split('\n'); const missingLines: string[] = []; for (const line of lines) { if (!existingLines.includes(line)) { missingLines.push(line); } } if (missingLines.length === 0) { logger.info('All lines already exist in file', { sessionId, filePath }); return { ok: true, added: 0 }; } // Add missing lines const newContent = fileExists ? fileContent + '\n' + missingLines.join('\n') : missingLines.join('\n'); // Write file (may need sudo) try { await writeFile(sessionId, filePath, newContent); } catch (error) { if (sudoPassword) { // Try with sudo by writing to temp file and moving const tempDir = resolveRemoteTempDir(osInfo); const baseTempDir = tempDir.replace(/\/+$/, ''); const tempFile = `${baseTempDir}/ssh-mcp-${Date.now()}.tmp`; await writeFile(sessionId, tempFile, newContent); const moveResult = await execSudo( sessionId, `mv ${tempFile} ${filePath}`, sudoPassword ); if (moveResult.code !== 0) { throw createFilesystemError( `Failed to move temporary file to ${filePath}`, 'Check file permissions and sudo access' ); } } else { throw error; } } logger.info('Lines added to file successfully', { sessionId, filePath, added: missingLines.length }); return { ok: true, added: missingLines.length }; } catch (error) { logger.error('Failed to ensure lines in file', { sessionId, filePath, error }); throw error; } }