Управление Git-репозиториями средствами JavaScript
Git и JavaScript: практические подходы
Как организовать работу с Git-репозиторием полностью на JavaScript, включая браузер и Node.js?
Основной вариант: isomorphic-git. Это реализация Git на JavaScript, которая не требует установленного git binary. Библиотека предоставляет API в стиле callback/promise, работает с абстракцией файловой системы (fs) и HTTP-клиентом. В Node.js применяется fs, в браузере - LightningFS или другая in-memory/IndexedDB FS.
const git = require('isomorphic-git');
const fs = require('fs');
const http = require('isomorphic-git/http/node');
(async () => {
const dir = './my-repo';
await git.init({ fs, dir });
await fs.promises.writeFile(dir + '/README.md', '# Demo');
await git.add({ fs, dir, filepath: 'README.md' });
const sha = await git.commit({
fs,
dir,
author: { name: 'Dev', email: 'dev@example.com' },
message: 'initial commit'
});
console.log('commit', sha);
})();Git js (git и javascript (например, isomorphic-git))
commit 7f3c... (SHA зависит от содержимого и времени)
Для удаленных операций подключается HTTP-клиент. Публичный clone возможен напрямую, если сервер отдает CORS-заголовки. В браузере часто требуется CORS proxy, например https://cors.isomorphic-git.org.
const git = require('isomorphic-git');
const fs = require('fs');
const http = require('isomorphic-git/http/node');
(async () => {
await git.clone({
fs,
http,
dir: './cloned',
url: 'https://github.com/isomorphic-git/isomorphic-git',
singleBranch: true,
depth: 1
});
const files = await git.listFiles({ fs, dir: './cloned' });
console.log(files.slice(0, 5));
})();
[ '.babelrc', '.editorconfig', '.gitattributes', '.github', '.gitignore' ]
Преимущества: единый код для Node.js и браузера, отсутствие системных зависимостей, тонкий контроль над fs и http. Ограничения: производительность ниже, чем у нативного libgit2 или CLI, часть редких команд отсутствует, для больших репозиториев нужен shallow clone, а браузерный доступ к удаленным репозиториям зависит от CORS.
Как вызвать системный git из Node.js, если нужна полная совместимость с CLI?
Вариант с child_process.spawn. Код запускает установленный git и читает stdout/stderr. Подходит для серверных задач, CI, где git уже есть.
const { spawn } = require('child_process');
const git = spawn('git', ['log', '--oneline', '-5'], { cwd: './repo' });
git.stdout.on('data', data => process.stdout.write(data));
git.stderr.on('data', data => process.stderr.write(data));
git.on('close', code => console.log('exit', code));
a1b2c3d fix: update README e4f5g6h feat: add API exit 0
Типичные ошибки: неверный cwd, отсутствие git в PATH, попадание пользовательских данных в аргументы без проверки. Для безопасности аргументы передаются массивом, без shell: true. На Windows путь к git может отличаться.
Как получить удобную обертку над Git CLI в Node.js?
Библиотека simple-git предоставляет promise-API поверх child_process. Она полезна для скриптов сборки и автоматизации.
const simpleGit = require('simple-git');
const git = simpleGit('./repo');
(async () => {
await git.checkoutLocalBranch('feature/js');
await git.add('./*');
await git.commit('add js files');
const status = await git.status();
console.log(status.current, status.files.length);
})();
feature/js 3
Проблемы: simple-git требует установленный git, ошибки CLI приходят как исключения, а поведение зависит от версии git. Для браузера вариант не подходит.
Как использовать libgit2 через нативные привязки в Node.js?
nodegit дает доступ к libgit2. Производительность выше, чем у чистого JavaScript, но сборка требует нативных инструментов.
const NodeGit = require('nodegit');
(async () => {
const repo = await NodeGit.Repository.open('./repo');
const commit = await repo.getHeadCommit();
console.log(commit.sha(), commit.message().trim());
})();
a1b2c3d... add API
Типичные сложности: ошибки сборки node-gyp, несовпадение версий Node.js, отсутствие готовых бинарников для некоторых платформ. В браузере nodegit не работает.
Как работать с удаленным репозиторием без локального клона?
Подход через REST API GitHub, GitLab или Bitbucket. Операции чтения файлов, коммитов, pull request выполняются HTTP-запросами.
const url = 'https://api.github.com/repos/isomorphic-git/isomorphic-git/contents/README.md';
const res = await fetch(url, { headers: { 'User-Agent': 'js-example' } });
const data = await res.json();
console.log(data.name, data.size);
README.md 14521
Ограничения: API не заменяет локальные операции, лимиты запросов, необходимость токена для приватных репозиториев, различия между провайдерами.
Общие ошибки при работе с Git в JavaScript: CORS при браузерных запросах, неправильный HTTP-клиент, отсутствие polyfill для Buffer и process, смешение Node fs и browser fs, неверная авторизация, блокировка больших клонов, необработанные reject promise, попытки использовать нативные модули в браузере.
Расширенные примеры Git и JavaScript
Клонирование и просмотр истории через isomorphic-git в Node.js
Пример выполняет shallow clone публичного репозитория и выводит последние коммиты. Для Node.js применяется http/node и fs.
const git = require('isomorphic-git');
const fs = require('fs');
const http = require('isomorphic-git/http/node');
(async () => {
const dir = './iso-demo';
await git.clone({ fs, http, dir, url: 'https://github.com/isomorphic-git/isomorphic-git', depth: 1, singleBranch: true });
const log = await git.log({ fs, dir, depth: 3 });
console.log(log.map(c => c.commit.message.trim()).join(' | '));
})();
Initial commit | docs: update readme | ...
Инициализация репозитория в браузере с LightningFS
Код работает в браузере. Файловая система хранится в IndexedDB. Для сборщика требуются polyfill для Buffer и process.
import git from 'isomorphic-git';
import LightningFS from '@isomorphic-git/lightning-fs';
const fs = new LightningFS('demo-fs');
const dir = '/project';
await git.init({ fs, dir });
await fs.promises.writeFile(dir + '/index.js', 'console.log(1)');
await git.add({ fs, dir, filepath: 'index.js' });
const sha = await git.commit({
fs,
dir,
author: { name: 'Browser', email: 'browser@example.com' },
message: 'browser commit'
});
console.log(sha);
4a5b6c... (SHA зависит от содержимого)
Отправка коммита на GitHub с токеном
Пример использует персональный токен. В браузере требуется CORS proxy. Токен не хранится в коде, а берется из переменной окружения или безопасного хранилища.
const git = require('isomorphic-git');
const fs = require('fs');
const http = require('isomorphic-git/http/node');
(async () => {
const dir = './repo-for-push';
await git.add({ fs, dir, filepath: 'README.md' });
await git.commit({
fs,
dir,
author: { name: 'Dev', email: 'dev@example.com' },
message: 'docs: update'
});
const res = await git.push({
fs,
http,
dir,
remote: 'origin',
ref: 'main',
onAuth: () => ({ username: process.env.GIT_TOKEN, password: 'x-oauth-basic' })
});
console.log(res.ok, res.refs);
})();
true { 'refs/heads/main': { ok: true } }
Ветки и слияние с isomorphic-git
Код создает ветку, переключается на нее, делает коммит и выполняет merge в main. Для merge требуется чистый рабочий каталог.
const git = require('isomorphic-git');
const fs = require('fs');
(async () => {
const dir = './merge-demo';
await git.branch({ fs, dir, ref: 'feature' });
await git.checkout({ fs, dir, ref: 'feature' });
await fs.promises.writeFile(dir + '/feature.txt', 'feature');
await git.add({ fs, dir, filepath: 'feature.txt' });
await git.commit({ fs, dir, author: { name: 'Dev', email: 'dev@example.com' }, message: 'feat: add feature' });
await git.checkout({ fs, dir, ref: 'main' });
await git.merge({ fs, dir, ours: 'main', theirs: 'feature', author: { name: 'Dev', email: 'dev@example.com' } });
const files = await git.listFiles({ fs, dir });
console.log(files.includes('feature.txt'));
})();
true
Проверка изменений через statusMatrix
Метод statusMatrix возвращает матрицу состояний файлов. Значения 0, 1, 2, 3 показывают комбинации HEAD, рабочего каталога и индекса.
const git = require('isomorphic-git');
const fs = require('fs');
(async () => {
const dir = './status-demo';
const matrix = await git.statusMatrix({ fs, dir });
for (const row of matrix) {
console.log(row.join(' '));
}
})();
README.md 1 2 1 new-file.js 0 2 0
Обертка simple-git для CI-скрипта
Библиотека simple-git упрощает последовательность команд. Пример клонирует репозиторий, создает ветку и отправляет изменения.
const simpleGit = require('simple-git');
(async () => {
const git = simpleGit();
await git.clone('https://github.com/example/repo.git', './ci-repo');
const repo = simpleGit('./ci-repo');
await repo.checkoutLocalBranch('ci/update');
await repo.add('./*');
await repo.commit('ci: update files');
await repo.push('origin', 'ci/update');
console.log(await repo.branchLocal());
})();
{ current: 'ci/update', all: [ 'ci/update', 'main' ] }
Разбор вывода git diff через child_process
Подход полезен, когда требуется точное поведение CLI. Код получает список измененных файлов в формате JSON.
const { execFile } = require('child_process');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);
(async () => {
const { stdout } = await execFileAsync('git', ['diff', '--name-only', 'HEAD~1', 'HEAD'], { cwd: './repo' });
const files = stdout.trim().split(String.fromCharCode(10)).filter(Boolean);
console.log(files);
})();
[ 'src/index.js', 'src/new.js' ]
Чтение файла из GitHub без клонирования
REST API возвращает содержимое файла в base64. Пример декодирует данные в Node.js.
const url = 'https://api.github.com/repos/isomorphic-git/isomorphic-git/contents/package.json';
const res = await fetch(url, { headers: { 'User-Agent': 'git-js-example' } });
const data = await res.json();
const text = Buffer.from(data.content, 'base64').toString('utf8');
console.log(JSON.parse(text).name);
isomorphic-git
Создание коммита через nodegit
nodegit открывает репозиторий и создает коммит в индексе. Пример требует нативной сборки.
const NodeGit = require('nodegit');
(async () => {
const repo = await NodeGit.Repository.open('./native-repo');
const index = await repo.refreshIndex();
await index.addByPath('README.md');
await index.write();
const treeOid = await index.writeTree();
const parent = await repo.getHeadCommit();
const author = NodeGit.Signature.now('Dev', 'dev@example.com');
const commit = await repo.createCommit('HEAD', author, author, 'docs: update', treeOid, [parent]);
console.log(commit.tid().toString());
})();
b7c8d9e... (идентификатор нового коммита)
Клонирование с прогрессом и отменой через isomorphic-git
Callback onProgress позволяет показывать состояние загрузки. AbortController останавливает операцию.
const git = require('isomorphic-git');
const fs = require('fs');
const http = require('isomorphic-git/http/node');
const controller = new AbortController();
(async () => {
await git.clone({
fs,
http,
dir: './big-repo',
url: 'https://github.com/example/big-repo',
depth: 1,
onProgress: p => console.log(p.phase, p.loaded, p.total),
signal: controller.signal
});
})();
Receiving objects 120 500 Receiving objects 500 500 Resolving deltas 50 50