acpgram 1.26.0 → 1.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,112 @@
1
+ // Аккаунты Git пользователей и то, что из них получает агент.
2
+ //
3
+ // Токен доступа хранится в базе бота и по умолчанию агенту не передаётся: клонирование, получение и отправку делает
4
+ // бот по кнопкам в /git, а агент работает с репозиторием локально. Администратор может выбрать другой режим —
5
+ // GIT_AGENT_AUTH=1: тогда вход передаётся и процессу агента (через его окружение), и агент сам тянет и отправляет
6
+ // изменения. Это удобнее, но токен становится виден агенту, а значит может попасть в запрос к модели.
7
+ import { db } from './ctx.mjs';
8
+ import { configEnv, gitAvailable } from './git.mjs';
9
+ import { authConfig, customHost, gitHosts, hostById, hostOfUrl } from './gitHosts.mjs';
10
+
11
+ /** Режим «вход у агента»: токены пользователя передаются процессу его агента. По умолчанию выключен. */
12
+ export const GIT_AGENT_AUTH = process.env.GIT_AGENT_AUTH?.trim() === '1';
13
+
14
+ // ---- свои серверы (GitLab, GitHub Enterprise), добавленные администратором в /git ----
15
+
16
+ const HOSTS_KEY = 'git:hosts';
17
+
18
+ /** Свои серверы, добавленные администратором: [{kind, url, name}]. */
19
+ export function customHosts() {
20
+ try {
21
+ const list = JSON.parse(db.getSetting(HOSTS_KEY) || '[]');
22
+ return Array.isArray(list) ? list.filter((x) => x && typeof x.url === 'string') : [];
23
+ } catch {
24
+ return [];
25
+ }
26
+ }
27
+
28
+ /** Все сервисы этой установки: GitHub, GitLab.com, серверы из настроек и добавленные администратором. */
29
+ export const hosts = () => gitHosts(process.env, customHosts());
30
+ /** Сервис по id или null. */
31
+ export const findHost = (id) => hostById(id, hosts());
32
+ /** Сервис, которому принадлежит адрес репозитория, или null. */
33
+ export const hostFor = (url) => hostOfUrl(url, hosts());
34
+
35
+ /**
36
+ * Добавляет свой сервер. @returns {{host: object} | {error: 'bad'|'exists'}} bad — адрес не подходит (нужен https,
37
+ * не github.com и не gitlab.com), exists — такой сервер уже есть.
38
+ */
39
+ export function addCustomHost(kind, url, name = '') {
40
+ const host = customHost(kind, url, name);
41
+ if (!host) return { error: 'bad' };
42
+ if (hosts().some((h) => h.web === host.web)) return { error: 'exists' };
43
+ db.setSetting(HOSTS_KEY, JSON.stringify([...customHosts(), { kind, url: host.web, name: String(name ?? '').trim() }]));
44
+ return { host };
45
+ }
46
+
47
+ /** Меняет название своего сервера (для кнопок). Возвращает false, если сервера нет или он задан в настройках. */
48
+ export function renameCustomHost(id, name) {
49
+ const list = customHosts();
50
+ const i = list.findIndex((x) => customHost(x.kind, x.url)?.id === id);
51
+ if (i < 0) return false;
52
+ list[i] = { ...list[i], name: String(name ?? '').trim().slice(0, 40) };
53
+ db.setSetting(HOSTS_KEY, JSON.stringify(list));
54
+ return true;
55
+ }
56
+
57
+ /**
58
+ * Убирает свой сервер вместе с подключёнными к нему аккаунтами всех пользователей (их токены удаляются).
59
+ * @returns {number|null} сколько аккаунтов удалено; null — сервера нет или он задан в настройках
60
+ */
61
+ export function removeCustomHost(id) {
62
+ const list = customHosts();
63
+ const rest = list.filter((x) => customHost(x.kind, x.url)?.id !== id);
64
+ if (rest.length === list.length) return null;
65
+ db.setSetting(HOSTS_KEY, JSON.stringify(rest));
66
+ return db.deleteGitAccountsByHost(id);
67
+ }
68
+
69
+ /** Подключённые аккаунты пользователя вместе с их сервисами: [{host, account}] (аккаунты убранных сервисов пропускаются). */
70
+ export function accountsOf(userId, list = hosts()) {
71
+ return db.listGitAccounts(userId).map((account) => ({ host: hostById(account.host, list), account })).filter((x) => x.host);
72
+ }
73
+
74
+ /** Автор коммитов по аккаунту: {name, email}. */
75
+ export const identityOf = (account) => (account ? { name: account.name || account.login, email: account.email } : null);
76
+
77
+ /**
78
+ * Переменные окружения процесса агента: автор коммитов (чтобы коммиты агента были от имени пользователя) и, в режиме
79
+ * GIT_AGENT_AUTH, вход в сервисы. Без подключённых аккаунтов — пусто: агент работает с git как раньше.
80
+ */
81
+ export function agentGitEnv(userId, { agentAuth = GIT_AGENT_AUTH, base = process.env } = {}) {
82
+ const list = accountsOf(userId);
83
+ if (!list.length) return {};
84
+ const who = identityOf(list[0].account);
85
+ // Автор — настройкой git (user.name / user.email), а не переменными GIT_AUTHOR_*: она действует как значение по
86
+ // умолчанию и уступает явному выбору автора (ключ -c, переменные GIT_AUTHOR_*), которым пользуются скрипты коммитов.
87
+ const entries = [['user.name', who.name], ['user.email', who.email]];
88
+ if (agentAuth) entries.push(...list.flatMap(({ host, account }) => authConfig(host, account.token)));
89
+ // нумерация продолжает настройки, уже заданные в окружении бота: они тоже достаются агенту
90
+ const env = configEnv(entries, base.GIT_CONFIG_COUNT ? { GIT_CONFIG_COUNT: base.GIT_CONFIG_COUNT } : {});
91
+ return agentAuth ? { ...env, GIT_TERMINAL_PROMPT: '0' } : env;
92
+ }
93
+
94
+ /**
95
+ * Подсказка агенту о git (служебный текст — на английском). Без входа: не пытаться получать и отправлять, а направлять
96
+ * пользователя в /git. Со входом (GIT_AGENT_AUTH): работать можно, показывать вход нельзя. Нет git на сервере — null.
97
+ */
98
+ export function gitNote(userId, { agentAuth = GIT_AGENT_AUTH } = {}) {
99
+ if (!gitAvailable()) return null;
100
+ const connected = db.listGitAccounts(userId).length > 0;
101
+ if (agentAuth && connected) {
102
+ return (
103
+ '[AcpGram] Git: the user\'s sign-in for their Git hosting is provided to git through your environment, so fetch, pull and push work. ' +
104
+ 'Never print, echo or store these credentials (do not show `env` or `git config --list` output). Never commit files with secrets (.env, keys).'
105
+ );
106
+ }
107
+ return (
108
+ '[AcpGram] Git: use git locally as usual (status, diff, add, commit, branches, merge). You have no credentials for the remote: ' +
109
+ 'do not try to fetch, pull, push or clone private repositories and do not ask the user for tokens or passwords. ' +
110
+ 'When changes must be received or sent, tell the user to use the /git command of this bot (buttons to pull and push). Never commit files with secrets (.env, keys).'
111
+ );
112
+ }
@@ -0,0 +1,195 @@
1
+ // Сервисы Git: GitHub, GitLab.com и свои серверы — GitLab и GitHub Enterprise, которые добавляет администратор в /git
2
+ // (или задаёт в настройках: GITLAB_URL, GITHUB_URL). Профиль и репозитории пользователя по его токену доступа и вход
3
+ // для команд git. Только встроенный fetch — без зависимостей.
4
+ //
5
+ // Вход git не пишется ни в настройки репозитория, ни в адрес: он передаётся процессу git через окружение
6
+ // (GIT_CONFIG_*: заголовок Authorization только для адреса своего сервиса) на время одной операции.
7
+
8
+ const TIMEOUT_MS = 15_000;
9
+
10
+ /**
11
+ * Адрес своего сервера из текста администратора: «https://git.example.com» или с путём («https://host/gitlab»).
12
+ * Только https; завершающие «/», запрос и якорь отбрасываются. Не подходит — null.
13
+ */
14
+ export function normalizeHostUrl(input) {
15
+ let u;
16
+ try {
17
+ u = new URL(String(input ?? '').trim());
18
+ } catch {
19
+ return null;
20
+ }
21
+ if (u.protocol !== 'https:' || !u.hostname.includes('.') || u.username || u.password) return null;
22
+ return `https://${u.host.toLowerCase()}${u.pathname.replace(/\/+$/, '')}`;
23
+ }
24
+
25
+ /** Id своего сервера: вид и адрес («gitlab-git-example-com») — одинаковый, откуда бы сервер ни был задан. */
26
+ const hostId = (kind, web) => `${kind}-${web.replace(/^https:\/\//, '')}`.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+$/, '').slice(0, 40);
27
+
28
+ const githubHost = (id, label, web, api) => ({ id, kind: 'github', label, web, api, tokenUrl: `${web}/settings/tokens`, user: 'x-access-token', scopes: 'repo' });
29
+ const gitlabHost = (id, label, web) => ({ id, kind: 'gitlab', label, web, api: `${web}/api/v4`, tokenUrl: `${web}/-/user_settings/personal_access_tokens`, user: 'oauth2', scopes: 'read_api, read_repository, write_repository' });
30
+
31
+ /**
32
+ * Свой сервер: GitLab или GitHub Enterprise по адресу. name — название для кнопок (по умолчанию — имя сервера).
33
+ * @param {'gitlab'|'github'} kind
34
+ * @returns {object|null} null — адрес не подходит или это общий сервис (github.com, gitlab.com)
35
+ */
36
+ export function customHost(kind, url, name = '') {
37
+ const web = normalizeHostUrl(url);
38
+ if (!web || (kind !== 'gitlab' && kind !== 'github') || /^https:\/\/(www\.)?(github|gitlab)\.com$/.test(web)) return null;
39
+ const label = String(name ?? '').trim().slice(0, 40) || new URL(web).host;
40
+ const host = kind === 'gitlab' ? gitlabHost(hostId(kind, web), label, web) : githubHost(hostId(kind, web), label, web, `${web}/api/v3`);
41
+ return { ...host, custom: true };
42
+ }
43
+
44
+ /**
45
+ * Сервисы, к которым можно подключиться: GitHub и GitLab.com — всегда; свои серверы — из настроек (GITLAB_URL и
46
+ * GITLAB_NAME, GITHUB_URL и GITHUB_NAME) и добавленные администратором (extra: [{kind, url, name}]). Один и тот же
47
+ * адрес дважды не попадает. kind — чей API; user — имя пользователя для входа git по токену; fromEnv — задан в настройках.
48
+ * @returns {{id: string, kind: 'github'|'gitlab', label: string, web: string, api: string, tokenUrl: string, user: string, scopes: string, custom?: boolean, fromEnv?: boolean}[]}
49
+ */
50
+ export function gitHosts(env = process.env, extra = []) {
51
+ const hosts = [githubHost('github', 'GitHub', 'https://github.com', 'https://api.github.com'), gitlabHost('gitlab', 'GitLab.com', 'https://gitlab.com')];
52
+ const add = (h, fromEnv) => {
53
+ if (h && !hosts.some((x) => x.web === h.web)) hosts.push(fromEnv ? { ...h, fromEnv: true } : h);
54
+ };
55
+ add(customHost('gitlab', env.GITLAB_URL, env.GITLAB_NAME), true);
56
+ add(customHost('github', env.GITHUB_URL, env.GITHUB_NAME), true);
57
+ for (const x of Array.isArray(extra) ? extra : []) add(customHost(x?.kind, x?.url, x?.name), false);
58
+ return hosts;
59
+ }
60
+
61
+ /** Сервис по id или null. */
62
+ export const hostById = (id, hosts = gitHosts()) => hosts.find((h) => h.id === id) ?? null;
63
+
64
+ /** Сервис, которому принадлежит адрес репозитория (только https), или null. */
65
+ export function hostOfUrl(url, hosts = gitHosts()) {
66
+ const u = String(url ?? '').trim().toLowerCase();
67
+ return hosts.find((h) => u === h.web.toLowerCase() || u.startsWith(`${h.web.toLowerCase()}/`)) ?? null;
68
+ }
69
+
70
+ /**
71
+ * Похож ли адрес на сервер своего вида: его API отвечает JSON (без токена — обычно отказом 401, это тоже ответ API).
72
+ * @returns {Promise<{ok: true} | {ok: false, error: string}>}
73
+ */
74
+ export async function probeHost(host, { fetchImpl = fetch } = {}) {
75
+ const url = host.kind === 'gitlab' ? `${host.api}/version` : `${host.api}/meta`;
76
+ let res;
77
+ try {
78
+ res = await fetchImpl(url, { headers: { accept: 'application/json', 'user-agent': 'acpgram' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
79
+ } catch (e) {
80
+ return { ok: false, error: e.message };
81
+ }
82
+ const isJson = /json/i.test(res.headers?.get?.('content-type') ?? '');
83
+ return [200, 401, 403].includes(res.status) && isJson ? { ok: true } : { ok: false, error: `HTTP ${res.status}` };
84
+ }
85
+
86
+ /** Адрес репозитория для показа: «github.com/owner/repo» (без схемы, входа и «.git»). */
87
+ export const showRemote = (url) => String(url ?? '').trim().replace(/^https?:\/\/([^@/]*@)?/i, '').replace(/\.git$/i, '');
88
+
89
+ /** Имя папки по адресу репозитория: «https://host/group/my-app.git» → «my-app». */
90
+ export const repoFolder = (url) => showRemote(url).split('/').filter(Boolean).pop() ?? '';
91
+
92
+ /**
93
+ * Настройка git для входа по токену: заголовок Authorization только для адресов этого сервиса (на другой адрес —
94
+ * например, после перенаправления или подмены origin — токен не уйдёт). Пары [ключ, значение] для configEnv.
95
+ */
96
+ export const authConfig = (host, token) => [[`http.${host.web}/.extraheader`, `Authorization: Basic ${Buffer.from(`${host.user}:${token}`).toString('base64')}`]];
97
+
98
+ /** Ошибка обращения к сервису: code — 'auth' (токен не подошёл), 'http' или 'network'. */
99
+ export class HostError extends Error {
100
+ constructor(code, message, status = null) {
101
+ super(message);
102
+ this.code = code;
103
+ this.status = status;
104
+ }
105
+ }
106
+
107
+ async function api(host, token, path, { fetchImpl = fetch } = {}) {
108
+ const headers = host.kind === 'github'
109
+ ? { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'user-agent': 'acpgram' }
110
+ : { 'private-token': token, accept: 'application/json', 'user-agent': 'acpgram' };
111
+ let res;
112
+ try {
113
+ res = await fetchImpl(`${host.api}${path}`, { headers, signal: AbortSignal.timeout(TIMEOUT_MS) });
114
+ } catch (e) {
115
+ throw new HostError('network', `${host.label}: ${e.message}`);
116
+ }
117
+ if (res.status === 401 || res.status === 403) throw new HostError('auth', `${host.label}: HTTP ${res.status}`, res.status);
118
+ if (!res.ok) throw new HostError('http', `${host.label}: HTTP ${res.status}`, res.status);
119
+ return { data: await res.json(), headers: res.headers };
120
+ }
121
+
122
+ const isoDate = (v) => {
123
+ const d = v ? new Date(v) : null;
124
+ return d && !Number.isNaN(d.getTime()) ? d.toISOString() : null;
125
+ };
126
+
127
+ /**
128
+ * Профиль владельца токена: {login, name, email, expiresAt, scopes}. email — адрес для коммитов (у GitHub без
129
+ * открытого адреса — служебный noreply). scopes — права токена, если сервис их сообщил (иначе null).
130
+ */
131
+ export async function fetchProfile(host, token, opts) {
132
+ if (host.kind === 'github') {
133
+ const { data, headers } = await api(host, token, '/user', opts);
134
+ const scopes = headers?.get?.('x-oauth-scopes');
135
+ return {
136
+ login: data.login,
137
+ name: data.name || data.login,
138
+ email: data.email || `${data.id}+${data.login}@users.noreply.${new URL(host.web).host}`,
139
+ // «2026-12-01 00:00:00 UTC» — в привычный Date формат
140
+ expiresAt: isoDate(headers?.get?.('github-authentication-token-expiration')?.replace(' UTC', 'Z').replace(' ', 'T')),
141
+ scopes: scopes == null ? null : scopes.split(',').map((s) => s.trim()).filter(Boolean),
142
+ };
143
+ }
144
+ const { data } = await api(host, token, '/user', opts);
145
+ // срок и права токена — отдельным запросом; старый GitLab его не знает — тогда без них
146
+ const self = await api(host, token, '/personal_access_tokens/self', opts).then((r) => r.data, () => null);
147
+ return {
148
+ login: data.username,
149
+ name: data.name || data.username,
150
+ email: data.commit_email || data.email || data.public_email || `${data.username}@users.noreply.${new URL(host.web).host}`,
151
+ expiresAt: isoDate(self?.expires_at),
152
+ scopes: Array.isArray(self?.scopes) ? self.scopes : null,
153
+ };
154
+ }
155
+
156
+ /** Каких прав токену не хватает для работы с репозиториями (по сообщённым сервисом правам); неизвестно — пусто. */
157
+ export function missingScopes(host, scopes) {
158
+ if (!Array.isArray(scopes)) return [];
159
+ const has = (s) => scopes.includes(s);
160
+ if (host.kind === 'github') return has('repo') || !scopes.length ? [] : ['repo']; // у fine-grained токенов список пуст
161
+ if (has('api')) return [];
162
+ return ['read_api', 'read_repository', 'write_repository'].filter((s) => !has(s));
163
+ }
164
+
165
+ export const REPOS_PAGE = 10;
166
+
167
+ /**
168
+ * Репозитории пользователя, недавно менявшиеся первыми: {items: [{name, url, private}], more}.
169
+ * search — часть названия. У GitHub поиска по своим репозиториям в API нет: берутся первые 300 и отбираются здесь.
170
+ */
171
+ export async function listRepos(host, token, { search = '', page = 0, perPage = REPOS_PAGE, ...opts } = {}) {
172
+ const q = search.trim().toLowerCase();
173
+ if (host.kind === 'gitlab') {
174
+ const query = `membership=true&simple=true&archived=false&order_by=last_activity_at&per_page=${perPage}&page=${page + 1}${q ? `&search=${encodeURIComponent(q)}` : ''}`;
175
+ const { data, headers } = await api(host, token, `/projects?${query}`, opts);
176
+ const items = data.map((p) => ({ name: p.path_with_namespace, url: p.http_url_to_repo, private: p.visibility !== 'public' }));
177
+ // есть ли следующая страница, GitLab сообщает заголовком; без него — по заполненности страницы
178
+ const next = headers?.get?.('x-next-page');
179
+ return { items, more: next == null ? items.length === perPage : Boolean(next) };
180
+ }
181
+ const gh = (p) => api(host, token, `/user/repos?sort=pushed&per_page=100&page=${p}`, opts).then((r) => r.data);
182
+ const map = (r) => ({ name: r.full_name, url: r.clone_url, private: Boolean(r.private) });
183
+ if (!q) {
184
+ const { data } = await api(host, token, `/user/repos?sort=pushed&per_page=${perPage}&page=${page + 1}`, opts);
185
+ return { items: data.map(map), more: data.length === perPage };
186
+ }
187
+ const all = [];
188
+ for (let p = 1; p <= 3; p++) {
189
+ const chunk = await gh(p);
190
+ all.push(...chunk);
191
+ if (chunk.length < 100) break;
192
+ }
193
+ const found = all.filter((r) => r.full_name.toLowerCase().includes(q)).map(map);
194
+ return { items: found.slice(page * perPage, (page + 1) * perPage), more: found.length > (page + 1) * perPage };
195
+ }
@@ -0,0 +1,163 @@
1
+ // Git: что изменилось и какие есть ветки — для экранов «Изменения» и «Ветки» в /git.
2
+ // Только чтение репозитория, кроме переключения и создания ветки. Команды запускает runGit (git.mjs) — с теми же
3
+ // безопасными настройками и, при включённой песочнице, внутри неё.
4
+ import { readFileSync, statSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { GitError, runGit } from './git.mjs';
7
+
8
+ /** Сколько изменённых файлов показывать (в большом несобранном проекте их могут быть тысячи). */
9
+ export const CHANGES_MAX = 300;
10
+ /** Файлы крупнее этого не читаются ради подсчёта строк. */
11
+ const COUNT_MAX_BYTES = 512 * 1024;
12
+
13
+ const kindOf = (xy) => {
14
+ if (xy === '??') return 'new';
15
+ if (xy.includes('U') || xy === 'AA' || xy === 'DD') return 'conflict';
16
+ if (xy.includes('R') || xy.includes('C')) return 'renamed';
17
+ if (xy.includes('D')) return 'deleted';
18
+ if (xy.includes('A')) return 'new';
19
+ return 'modified';
20
+ };
21
+
22
+ /**
23
+ * Разбор `git status --porcelain=v1 -z`: [{path, kind, from?}], kind — new | modified | deleted | renamed | conflict.
24
+ * У переименованного файла следующая запись — прежнее имя.
25
+ */
26
+ export function parseChanges(text) {
27
+ const parts = String(text ?? '').split('\0');
28
+ const out = [];
29
+ for (let i = 0; i < parts.length; i++) {
30
+ const rec = parts[i];
31
+ if (rec.length < 4) continue;
32
+ const xy = rec.slice(0, 2);
33
+ const item = { path: rec.slice(3), kind: kindOf(xy) };
34
+ if (xy.includes('R') || xy.includes('C')) item.from = parts[++i];
35
+ out.push(item);
36
+ }
37
+ return out;
38
+ }
39
+
40
+ /** Разбор `git diff --numstat -z`: Map путь → {added, deleted} (у двоичных файлов — null). */
41
+ export function parseNumstat(text) {
42
+ const parts = String(text ?? '').split('\0');
43
+ const map = new Map();
44
+ for (let i = 0; i < parts.length; i++) {
45
+ const m = /^(\d+|-)\t(\d+|-)\t(.*)$/s.exec(parts[i]);
46
+ if (!m) continue;
47
+ let path = m[3];
48
+ if (!path) {
49
+ path = parts[i + 2]; // переименование: далее — прежнее и новое имя
50
+ i += 2;
51
+ }
52
+ if (path) map.set(path, { added: m[1] === '-' ? null : Number(m[1]), deleted: m[2] === '-' ? null : Number(m[2]) });
53
+ }
54
+ return map;
55
+ }
56
+
57
+ /** Число строк нового файла (которого git ещё не знает) или null, если он велик, двоичный или не читается. */
58
+ function countLines(file) {
59
+ try {
60
+ if (statSync(file).size > COUNT_MAX_BYTES) return null;
61
+ const buf = readFileSync(file);
62
+ if (buf.includes(0)) return null;
63
+ if (!buf.length) return 0;
64
+ let n = 0;
65
+ for (const b of buf) if (b === 10) n++;
66
+ return buf[buf.length - 1] === 10 ? n : n + 1;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Несохранённые изменения рабочей папки относительно последнего коммита: [{path, kind, added, deleted, from?}].
74
+ * added / deleted — число строк (null, если неизвестно). total — сколько всего изменённых файлов (список обрезается).
75
+ */
76
+ export async function changedFiles(cwd, opts = {}) {
77
+ const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
78
+ const all = parseChanges(await runGit(['status', '--porcelain=v1', '-z', '--untracked-files=all'], { cwd, ...opts }));
79
+ // в репозитории без коммитов сравнивать не с чем — тогда без числа строк
80
+ const counts = await runGit(['diff', '--numstat', '-z', 'HEAD'], { cwd, ...opts }).then(parseNumstat, () => new Map());
81
+ const files = all.slice(0, CHANGES_MAX).map((f) => {
82
+ const c = counts.get(f.path);
83
+ if (c) return { ...f, ...c };
84
+ return { ...f, added: f.kind === 'new' ? countLines(join(top, f.path)) : null, deleted: f.kind === 'new' ? 0 : null };
85
+ });
86
+ return { files, total: all.length };
87
+ }
88
+
89
+ /**
90
+ * Изменения одного файла текстом (unified diff, без служебного начала). Новый файл показывается целиком как добавленный.
91
+ * @param {{path: string, kind: string}} file запись из changedFiles (путь — от корня репозитория)
92
+ */
93
+ export async function fileDiff(cwd, file, opts = {}) {
94
+ const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
95
+ const base = { cwd: top, maxOut: 300_000, ...opts };
96
+ const raw = file.kind === 'new'
97
+ ? await runGit(['diff', '--no-color', '--no-ext-diff', '--no-index', '--', '/dev/null', file.path], { ...base, okCodes: [0, 1] })
98
+ : await runGit(['diff', '--no-color', '--no-ext-diff', 'HEAD', '--', file.path], base);
99
+ // «diff --git…», «index…» и подобные строки до первого «---» пользователю ничего не говорят
100
+ const lines = raw.split(/\r?\n/);
101
+ const start = lines.findIndex((l) => l.startsWith('--- ') || l.startsWith('Binary files') || l.startsWith('@@'));
102
+ return (start > 0 ? lines.slice(start) : lines).join('\n').trimEnd();
103
+ }
104
+
105
+ /**
106
+ * Коммиты: которые ещё не отправлены ('out') или которые есть на сервере, а локально нет ('in').
107
+ * Без ветки на сервере «не отправлено» — последние коммиты ветки, «на сервере» — пусто.
108
+ * @returns {Promise<{hash: string, author: string, date: string, subject: string}[]>}
109
+ */
110
+ export async function commitList(cwd, dir, opts = {}, limit = 20) {
111
+ const upstream = await runGit(['rev-parse', '--abbrev-ref', '@{u}'], { cwd, ...opts }).then((s) => s.trim(), () => null);
112
+ if (!upstream && dir === 'in') return [];
113
+ const range = !upstream ? 'HEAD' : dir === 'in' ? 'HEAD..@{u}' : '@{u}..HEAD';
114
+ const out = await runGit(['log', `-n${limit}`, '--format=%h%x09%an%x09%ad%x09%s', '--date=short', range], { cwd, ...opts }).catch(() => '');
115
+ return out.split(/\r?\n/).filter(Boolean).map((l) => {
116
+ const [hash, author, date, ...rest] = l.split('\t');
117
+ return { hash, author, date, subject: rest.join('\t') };
118
+ });
119
+ }
120
+
121
+ /**
122
+ * Ветки: локальные и ветки сервера (origin) одним списком — [{name, local, remote, date, current}], текущая первой,
123
+ * дальше по дате последнего коммита.
124
+ */
125
+ export async function listBranches(cwd, opts = {}) {
126
+ const current = await runGit(['branch', '--show-current'], { cwd, ...opts }).then((s) => s.trim() || null, () => null);
127
+ const out = await runGit(['for-each-ref', '--format=%(refname)%09%(committerdate:iso-strict)', 'refs/heads', 'refs/remotes/origin'], { cwd, ...opts });
128
+ const map = new Map();
129
+ for (const line of out.split(/\r?\n/).filter(Boolean)) {
130
+ const [ref, date] = line.split('\t');
131
+ const local = ref.startsWith('refs/heads/');
132
+ const name = local ? ref.slice('refs/heads/'.length) : ref.slice('refs/remotes/origin/'.length);
133
+ if (!name || name === 'HEAD') continue;
134
+ const b = map.get(name) ?? { name, local: false, remote: false, date: '' };
135
+ if (local) b.local = true;
136
+ else b.remote = true;
137
+ if (date > b.date) b.date = date;
138
+ map.set(name, b);
139
+ }
140
+ const list = [...map.values()].map((b) => ({ ...b, current: b.name === current }));
141
+ list.sort((a, b) => Number(b.current) - Number(a.current) || b.date.localeCompare(a.date) || a.name.localeCompare(b.name));
142
+ return { current, branches: list };
143
+ }
144
+
145
+ /** Название ветки из текста пользователя: пробелы — в «-»; не подходит — null (проверку формата делает сам git). */
146
+ export async function branchName(input, { cwd, ...opts }) {
147
+ const name = String(input ?? '').trim().replace(/\s+/g, '-');
148
+ if (!name || name.length > 100 || name.startsWith('-')) return null;
149
+ return runGit(['check-ref-format', '--branch', name], { cwd, ...opts }).then(() => name, () => null);
150
+ }
151
+
152
+ /**
153
+ * Переключается на ветку: локальную — как есть, существующую только на сервере — создаёт локальную, связанную с ней.
154
+ * Вызывающий отвечает за то, что в рабочей папке нет несохранённых изменений.
155
+ */
156
+ export async function switchBranch(cwd, branch, opts = {}) {
157
+ if (!branch?.name || branch.name.startsWith('-')) throw new GitError('некорректное название ветки');
158
+ if (branch.local) return runGit(['switch', '--quiet', branch.name], { cwd, ...opts });
159
+ return runGit(['switch', '--quiet', '--track', `origin/${branch.name}`], { cwd, ...opts });
160
+ }
161
+
162
+ /** Создаёт ветку от текущего коммита и переключается на неё (несохранённые изменения остаются в рабочей папке). */
163
+ export const createBranch = (cwd, name, opts = {}) => runGit(['switch', '--quiet', '-c', name], { cwd, ...opts });