Tutorials & Guides
How to Build a Local CLI Tool with Grok 2 and Node.js to Auto-Generate READMEs from Git Diffs
Stop writing tedious documentation by hand. Build a lightweight local command-line interface that pipes your unstaged changes straight to Grok 2 for instant, accurate project READMEs.
Updated 10/30/2026
Stop Writing READMEs From Scratch
Let’s be honest: writing documentation is rarely the highlight of a developer's day. We build beautiful, elegant codebases, only to lose momentum when it comes to explaining how they actually work. Sure, you could copy and paste your code into a browser-based AI assistant, but that interrupts your terminal workflow and introduces unnecessary context switching.
Instead, you can build a lightweight, local Command-Line Interface (CLI) that scans your project's active Git diff, analyses what makes your system tick, and updates or generates a comprehensive, context-aware README.md automatically.
By leveraging the newly released Grok 2 model via API, we can get crisp, highly technical documentation without the fluffy corporate waffle that older LLMs are prone to generating. Here is how to build your own local node CLI tool that hooks directly into your Git workflow.
Which AI should I use for this?
Tickd is independent and not affiliated with any AI company.
Why Grok 2 for Dev Tooling?
While we frequently praise engines like /platforms/claude for browser-based prototyping, xAI’s Grok 2 has quietly become a highly efficient powerhouse for system-level programming and shell-adjacent tooling. It has a sharp, concise coding voice and is excellent at parsing messy system diffs without getting confused by deleted files or refactored imports. If you run into issues configuring your credentials, you can check our dedicated guide on /platforms/grok/articles.
Prerequisites
Before we write any JavaScript, make sure you have the following ready:
- Node.js (v18 or higher recommended)
- An xAI Console account and a valid Grok API key
- A local development project with a Git repository initialized
Let's get cracking.
Step 1: Initialise the Project
First, create a new directory for your CLI tool, or set it up directly inside your global system bin. For this tutorial, we will build it as a standalone package that you can link globally.
`bash
mkdir grok-readme-cli
cd grok-readme-cli
npm init -y
`
Next, install the required packages. We will use dotenv for managing our secret keys, commander for handling terminal arguments, and the official xAI SDK (or a lightweight HTTP client like axios to avoid bloated dependencies).
`bash
npm install dotenv commander axios
`
Now, open your package.json file and add a bin property. This tells Node that your script is meant to be run directly from the shell:
`json
{
"name": "grok-readme",
"version": "1.0.0",
"type": "module",
"bin": {
"grok-readme": "./index.js"
},
"dependencies": {
"axios": "^1.6.0",
"commander": "^11.1.0",
"dotenv": "^16.3.1"
}
}
`
Create a .env file in the root directory to store your API token securely:
`env
XAI_API_KEY=your_actual_grok_api_key_here
`
Step 2: Grab the Git Diff Programmatically
Our CLI needs to inspect what changes have been made to our codebase so it can accurately document them. We can achieve this by spawning a child process to run git diff inside the user's terminal.
Create a file named index.js and start with the core Git execution logic:
`javascript
#!/usr/bin/env node
import { execSync } from 'child_process'; import fs from 'fs'; import path from 'path'; import { Command } from 'commander'; import axios from 'axios'; import dotenv from 'dotenv';
dotenv.config();
const program = new Command();
function getGitDiff() {
try {
// Get both staged and unstaged changes to understand full scope
const diff = execSync('git diff HEAD', { encoding: 'utf8' });
return diff.trim();
} catch (error) {
console.error('Error: Is this a Git repository? Make sure you have commits and Git installed.');
process.exit(1);
}
}
`
If the repository is completely clean, git diff HEAD will return an empty string. We should handle this scenario gracefully by falling back to reading key files like package.json or scanning the project directory structure to give Grok 2 something to work with.
Step 3: Constructing the Grok 2 Prompt
To prevent the AI from generating generic filler paragraphs, we need to construct a robust system prompt. Let's head over to our standard prompt guidelines at /prompts for inspiration, or use the tailored prompt block below. We want Grok 2 to behave like an elite technical writer who values developer reading time above all else.
`javascript
const SYSTEM_PROMPT = `You are a Senior Technical Writer. Your task is to generate a clean, highly accurate, and engaging README.md file based on a provided Git diff.
Rules:
1. Keep it concise. No fluff, no obvious statements like "This is a Node.js project."
2. Focus on installation, basic usage, and a clear breakdown of the architecture shown in the diff.
3. Include code examples where appropriate.
4. Do not mention the Git diff itself. Write as if this is the definitive documentation for the codebase.
5. Output valid, raw Markdown. Do not wrap the entire response in extra Markdown block quotes.`;
`
Step 4: Hooking Up the xAI API Client
Now we write the main logic to pipe our diff to the /platforms/grok. We will use a standard POST request targeting https://api.x.ai/v1/chat/completions:
`javascript
async function generateReadme(diffContent, projectPath) {
const apiKey = process.env.XAI_API_KEY;
if (!apiKey) {
console.error('Error: XAI_API_KEY is not set in your .env file.');
process.exit(1);
}
let userPrompt = Here is the Git diff representing recent development on this project:\n\n${diffContent}\n\nPlease generate a professional README.md file based on these changes.;
// If the diff is empty, read package.json to guide the model
if (!diffContent) {
const pkgPath = path.join(projectPath, 'package.json');
if (fs.existsSync(pkgPath)) {
const pkgJson = fs.readFileSync(pkgPath, 'utf8');
userPrompt = The working tree is clean. Here is the project's package.json to help you generate a comprehensive README.md:\n\n${pkgJson};
} else {
userPrompt = This is an empty project directory. Generate a skeleton README.md structure with best practices.;
}
}
console.log('Sending project data to Grok 2... 🚀');
try {
const response = await axios.post(
'https://api.x.ai/v1/chat/completions',
{
model: 'grok-2-1212', // Using the stable Grok 2 production endpoint
messages: [
{ role: 'system', content: SYSTEM_PROMPT },
{ role: 'user', content: userPrompt }
],
temperature: 0.2 // Lower temp for precise, technical layout
},
{
headers: {
'Authorization': Bearer ${apiKey},
'Content-Type': 'application/json'
}
}
);
return response.data.choices[0].message.content;
} catch (error) {
console.error('Failed to communicate with Grok 2:', error.response?.data || error.message);
process.exit(1);
}
}
`
Step 5: Tying the CLI Together
Finally, we set up the Commander entry point to read user arguments and write the generated content to a file. Add the execution flow at the end of index.js:
`javascript
program
.version('1.0.0')
.description('Generate a README.md automatically using Grok 2')
.option('-o, --output <filename>', 'Output file name', 'README.md')
.option('-f, --force', 'Overwrite existing README.md without asking')
.action(async (options) => {
const targetPath = process.cwd();
const outputPath = path.join(targetPath, options.output);
if (fs.existsSync(outputPath) && !options.force) {
console.log(Warning: ${options.output} already exists. Run with --force or -f to overwrite.);
process.exit(0);
}
const diff = getGitDiff(); const markdownContent = await generateReadme(diff, targetPath);
fs.writeFileSync(outputPath, markdownContent, 'utf8');
console.log(Success! Written to ${outputPath} 🎉);
});
program.parse(process.argv);
`
Step 6: Testing and Global Linking
To run your new tool locally without using relative file paths, you can link it globally to your machine's bin directory:
`bash
npm link
`
Now, navigate to any project with uncommitted changes or active commits, and simply run:
`bash
grok-readme
`
Your CLI will run silently in the background, parse your local Git status, package it up, and generate a highly accurate, clean, production-grade README.md in less than five seconds. No browser tabs, no copy-pasting, and absolutely no corporate fluff.
Keep going
Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.