acpgram 1.27.0 → 1.29.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.
- package/README.md +8 -1
- package/README.ru.md +15 -2
- package/package.json +1 -1
- package/src/bot.mjs +19 -2
- package/src/db.mjs +3 -0
- package/src/git.mjs +13 -4
- package/src/gitAccess.mjs +26 -1
- package/src/gitApi.mjs +79 -0
- package/src/gitHosts.mjs +27 -8
- package/src/gitInspect.mjs +207 -0
- package/src/gitKeys.mjs +20 -0
- package/src/gitMarks.mjs +42 -0
- package/src/gitPublishUi.mjs +239 -0
- package/src/gitRepoUi.mjs +239 -0
- package/src/gitUi.mjs +39 -8
- package/src/i18n.mjs +73 -1
- package/src/turn.mjs +7 -2
package/README.md
CHANGED
|
@@ -230,9 +230,16 @@ The `/git` command connects projects to GitHub, GitLab.com and your own servers
|
|
|
230
230
|
|
|
231
231
|
- **Own servers** are added by the administrator right in `/git`: "⚙️ Own servers" → "➕ GitLab" or "➕ GitHub Enterprise" → the server address (`https://git.example.com`). The bot checks that a server of that kind answers at the address, and after that every user can connect an account on it. The same screen renames and removes a server — together with the accounts connected to it. Without this the menu has only GitHub and GitLab.com. Where settings are kept in a file, a server can also be set in `.env` (`GITLAB_URL`, `GITHUB_URL`).
|
|
232
232
|
|
|
233
|
-
- **Connecting an account.** "➕ Connect …" → the bot gives a link to the tokens page and the list of permissions, and the user sends the access token in one message. The message is deleted from the chat right away and is not passed to the agent. The bot checks the token with the service, shows who is connected and until when the token is valid, and warns if permissions are missing. Disconnecting removes the token from the bot.
|
|
233
|
+
- **Connecting an account.** "➕ Connect …" → the bot gives a link to the tokens page and the list of permissions, and the user sends the access token in one message. The message is deleted from the chat right away and is not passed to the agent. The bot checks the token with the service, shows who is connected and until when the token is valid, and warns if permissions are missing. Full permissions are needed: on GitLab `api`, `read_repository`, `write_repository` (without `api` publishing and merge requests do not work), on GitHub `repo`. Disconnecting removes the token from the bot.
|
|
234
234
|
- **Cloning.** "⬇️ Clone a repository" (or "⬇️ From Git" in `/project`) lists the user's repositories as buttons, recently changed first, with search by name. The chosen one is cloned into the personal workspace (without it, next to the current project) and becomes the project.
|
|
235
235
|
- **The project repository.** The screen shows the branch, the number of changed files, of commits not pushed and of new commits on the server; it checks the server when opened and on "Refresh". "⬇️ Pull" takes the changes when that is possible without a merge; if the histories diverged, the agent does the merge. "⬆️ Push" sends the commits. "💾 Save and push" asks for a description, commits all changes and pushes.
|
|
236
|
+
- **"📋 Changes".** The list of changed files with marks (new, modified, deleted, renamed) and the number of added and removed lines. Pressing a file shows what changed in it: short changes in the message, long ones as a file. The contents of files with secrets are not shown. The same screen lists the commits that are not pushed yet and those waiting on the server. All of this is visible without the agent and without model requests.
|
|
237
|
+
- **"🌿 Branches".** Local and server branches in one list; pressing a branch switches to it, "➕ New branch" creates one from the current branch. With unsaved changes the bot does not switch and offers to save them first; the same while the agent is working. After switching, the next request starts a new agent session, because the project files have changed. "Push" creates a new branch on the server too.
|
|
238
|
+
- **Discarding changes.** The card of a changed file has "↩️ Restore as it was", and the "Changes" screen has "↩️ Discard all changes": modified and deleted files return to the last commit, new files are deleted. It cannot be undone, so it always asks for confirmation; files with secrets are not touched.
|
|
239
|
+
- **"🚀 Publish the project".** For a folder that is not connected to a server yet: the user chooses the service, the place (personal space, a GitLab group with subgroups or a GitHub organization — with search), the visibility (private, internal, public) and the name. The bot creates the repository, makes the first commit without files with secrets and pushes it.
|
|
240
|
+
- **"🔀 Merge request".** From the current branch into the main branch of the repository: the bot asks for a title (or suggests the last commit message), creates the request and gives the link; if an open request from this branch already exists, it shows that one.
|
|
241
|
+
- **The agent asks to push.** The agent has no sign-in for the server, so on "push it" it commits and puts the mark `[[git:push]]` (or `[[git:pull]]`) into its reply. The bot removes the mark and shows a button under the reply; nothing is sent without the user pressing it.
|
|
242
|
+
- **Token reminder.** A week before, a day before and when the token expires, the bot writes to the account owner.
|
|
236
243
|
- **The commit author** is the account owner: the name and email are given to both the bot and the agent, so the agent's commits are signed by the user.
|
|
237
244
|
- **Secrets do not go to the repository.** On "Save and push", files with secrets (`.env`, keys, credentials) are left out of the commit and appended to `.gitignore`. If the agent committed such a file, the bot warns before pushing and pushes only after "Push anyway".
|
|
238
245
|
|
package/README.ru.md
CHANGED
|
@@ -120,9 +120,16 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
120
120
|
|
|
121
121
|
- **Свои серверы** добавляет администратор прямо в `/git`: «⚙️ Свои серверы» → «➕ GitLab» или «➕ GitHub Enterprise» → адрес сервера (`https://git.example.com`). Бот проверяет, что по адресу отвечает сервер нужного вида, и после этого каждый пользователь может подключить на нём аккаунт. Там же сервер переименовывается и убирается — вместе с подключёнными к нему аккаунтами. Без этого в меню только GitHub и GitLab.com. Там, где настройки задаются файлом, сервер можно указать и в `.env` (`GITLAB_URL`, `GITHUB_URL`).
|
|
122
122
|
|
|
123
|
-
- **Подключение аккаунта.** «➕ Подключить …» → бот даёт ссылку на страницу токенов и список нужных прав, пользователь присылает токен доступа одним сообщением. Сообщение сразу удаляется из чата и агенту не передаётся. Бот проверяет токен в сервисе, показывает, кто подключён и до какого числа токен действует, и предупреждает, если прав не хватает. Отключение удаляет токен из бота.
|
|
123
|
+
- **Подключение аккаунта.** «➕ Подключить …» → бот даёт ссылку на страницу токенов и список нужных прав, пользователь присылает токен доступа одним сообщением. Сообщение сразу удаляется из чата и агенту не передаётся. Бот проверяет токен в сервисе, показывает, кто подключён и до какого числа токен действует, и предупреждает, если прав не хватает. Права нужны полные: у GitLab — `api`, `read_repository`, `write_repository` (без `api` не работают публикация и запросы на слияние), у GitHub — `repo`. Отключение удаляет токен из бота.
|
|
124
124
|
- **Клонирование.** «⬇️ Клонировать репозиторий» (или «⬇️ Из Git» в `/project`) показывает репозитории пользователя кнопками, недавно менявшиеся первыми, с поиском по названию. Выбранный клонируется в личное пространство (без него — рядом с текущим проектом) и становится проектом.
|
|
125
125
|
- **Репозиторий проекта.** Экран показывает ветку, число изменённых файлов, неотправленных коммитов и новых коммитов на сервере; при открытии и по кнопке «Обновить» он сверяется с сервером. «⬇️ Получить» забирает изменения, если это возможно без слияния; если истории разошлись, слияние делает агент. «⬆️ Отправить» отправляет коммиты. «💾 Сохранить и отправить» спрашивает описание, коммитит все изменения и отправляет.
|
|
126
|
+
- **«📋 Изменения».** Список изменённых файлов с пометками (новый, изменён, удалён, переименован) и числом добавленных и убранных строк. Нажатие на файл показывает, что в нём изменилось: короткие изменения — в сообщении, длинные — файлом. Содержимое файлов с секретами не показывается. Там же — коммиты, которые ещё не отправлены, и те, что ждут на сервере. Всё это видно без агента и без запросов к модели.
|
|
127
|
+
- **«🌿 Ветки».** Локальные ветки и ветки сервера одним списком; нажатие переключает на ветку, «➕ Новая ветка» создаёт её от текущей. При несохранённых изменениях бот не переключает, а предлагает сначала сохранить их; пока агент выполняет запрос — тоже. После переключения следующий запрос начинает новую сессию агента: файлы проекта сменились. «Отправить» создаёт новую ветку и на сервере.
|
|
128
|
+
- **Отмена изменений.** В карточке изменённого файла — «↩️ Вернуть как было», на экране «Изменения» — «↩️ Отменить все изменения»: изменённые и удалённые файлы возвращаются к последнему коммиту, новые удаляются. Действие необратимо, поэтому всегда с подтверждением; файлы с секретами не затрагиваются.
|
|
129
|
+
- **«🚀 Опубликовать проект».** Для папки, которая ещё не связана с сервером: пользователь выбирает сервис, место (личное пространство, группа GitLab с подгруппами или организация GitHub — с поиском), видимость (закрытый, внутренний, открытый) и название. Бот создаёт репозиторий, делает первый коммит без файлов с секретами и отправляет его.
|
|
130
|
+
- **«🔀 Запрос на слияние».** Из текущей ветки в основную ветку репозитория: бот спрашивает заголовок (или предлагает описание последнего коммита), создаёт запрос и даёт ссылку; если открытый запрос из этой ветки уже есть — показывает его.
|
|
131
|
+
- **Агент просит отправить.** У агента нет входа на сервер, поэтому «отправь на сервер» он выполняет так: коммитит и ставит в ответе метку `[[git:push]]` (или `[[git:pull]]`). Бот убирает метку и показывает под ответом кнопку; без нажатия пользователя ничего не уходит.
|
|
132
|
+
- **Напоминание о токене.** За неделю, за день и по истечении срока токена бот пишет владельцу аккаунта.
|
|
126
133
|
- **Автор коммитов** — владелец аккаунта: его имя и почта передаются и боту, и агенту, так что коммиты агента подписаны пользователем.
|
|
127
134
|
- **Секреты не уходят в репозиторий.** При «Сохранить и отправить» файлы с секретами (`.env`, ключи, учётные данные) из коммита исключаются и дописываются в `.gitignore`. Если такой файл закоммитил агент, перед отправкой бот предупреждает и отправляет только после «Отправить всё равно».
|
|
128
135
|
|
|
@@ -421,7 +428,13 @@ src/
|
|
|
421
428
|
git.mjs команды git бота: клонирование, состояние, получение, отправка, коммит без секретов; безопасный запуск
|
|
422
429
|
gitHosts.mjs GitHub и GitLab: профиль и репозитории по токену, вход для git
|
|
423
430
|
gitAccess.mjs аккаунты Git пользователей; что из них получает агент (автор коммитов, вход при GIT_AGENT_AUTH)
|
|
424
|
-
gitUi.mjs команда /git: аккаунты, клонирование, получить / отправить / сохранить
|
|
431
|
+
gitUi.mjs команда /git: аккаунты, свои серверы, клонирование, получить / отправить / сохранить
|
|
432
|
+
gitInspect.mjs что изменилось и какие есть ветки: список файлов, изменения по файлу, коммиты, переключение ветки
|
|
433
|
+
gitRepoUi.mjs экраны /git «Изменения» и «Ветки», отмена изменений
|
|
434
|
+
gitApi.mjs GitHub и GitLab: создание репозитория, места для публикации, запрос на слияние
|
|
435
|
+
gitPublishUi.mjs экраны /git «Опубликовать проект» и «Запрос на слияние»
|
|
436
|
+
gitMarks.mjs метки агента [[git:push]] / [[git:pull]]: отправка и получение по просьбе агента
|
|
437
|
+
gitKeys.mjs ключи кнопок списков /git: старая кнопка не укажет на другой файл или ветку
|
|
425
438
|
sessionsUi.mjs команда /sessions: возврат к прошлой сессии
|
|
426
439
|
tools.mjs разбор событий вызовов инструментов агента
|
|
427
440
|
asks.mjs кнопки быстрого ответа от агента: метка [[ask: …]], разметка кнопок, выбор по нажатию
|
package/package.json
CHANGED
package/src/bot.mjs
CHANGED
|
@@ -8,12 +8,12 @@ import { choiceName, effectiveSelection, killProbes, refreshCatalogs } from './a
|
|
|
8
8
|
import { handleModel, onModelCallback } from './modelUi.mjs';
|
|
9
9
|
import { ADMIN_ID, IDLE_MINUTES, LEVEL_KEYS, MAX_AGENTS, botInfo, db, langOf, log, noteTgLang, say, setLang } from './ctx.mjs';
|
|
10
10
|
import { adminCommand, handleUnknownUser, onAdminCallback, welcomeNote } from './admin.mjs';
|
|
11
|
-
import { LANGS, LANG_CODES, LANG_PICK, errText, normLang, t } from './i18n.mjs';
|
|
11
|
+
import { LANGS, LANG_CODES, LANG_PICK, LOCALES, errText, normLang, t } from './i18n.mjs';
|
|
12
12
|
import { HOME, ROOT, USER_WORKSPACES } from './projects.mjs';
|
|
13
13
|
import { handleProject, onNavCallback, onProjectNameInput, onTopicListCallback } from './projectsUi.mjs';
|
|
14
14
|
import { handleFiles, onFileInput, onFileUpload, onFilesCallback } from './filesUi.mjs';
|
|
15
15
|
import { checkGit, gitCommand } from './git.mjs';
|
|
16
|
-
import { GIT_AGENT_AUTH } from './gitAccess.mjs';
|
|
16
|
+
import { GIT_AGENT_AUTH, tokenReminders } from './gitAccess.mjs';
|
|
17
17
|
import { handleGit, onGitCallback, onGitInput } from './gitUi.mjs';
|
|
18
18
|
import { handleSessions, onSessionCallback } from './sessionsUi.mjs';
|
|
19
19
|
import { dropPermissions, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
|
|
@@ -482,6 +482,23 @@ async function main() {
|
|
|
482
482
|
};
|
|
483
483
|
sweep();
|
|
484
484
|
setInterval(sweep, 24 * 3600_000).unref();
|
|
485
|
+
// токены доступа к Git истекают: владельцу аккаунта — напоминание за неделю, за день и по истечении
|
|
486
|
+
const remind = () => {
|
|
487
|
+
try {
|
|
488
|
+
for (const r of tokenReminders()) {
|
|
489
|
+
const lang = langOf(r.userId);
|
|
490
|
+
const date = new Date(r.account.expires_at).toLocaleDateString(LOCALES[lang] ?? LOCALES.en, { day: '2-digit', month: '2-digit', year: 'numeric' });
|
|
491
|
+
log('git: напоминание о токене:', r.userId, r.host.id, r.stage);
|
|
492
|
+
say(r.userId, t(r.stage === 'expired' ? 'git.exp.expired' : 'git.exp.soon', lang, { host: r.host.label, login: r.account.login, date, days: r.days }), {
|
|
493
|
+
reply_markup: { inline_keyboard: [[{ text: t('start.btn.git', lang), callback_data: 'ui:git' }]] },
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
} catch (e) {
|
|
497
|
+
log('напоминания о токенах git:', e.message);
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
remind();
|
|
501
|
+
setInterval(remind, 12 * 3600_000).unref();
|
|
485
502
|
const admin = getState(ADMIN_ID, ADMIN_ID);
|
|
486
503
|
log(`бот @${botInfo.username} запущен | администратор ${ADMIN_ID} | проект админа: ${admin.project} | сотрудников: ${db.listUsers().filter((x) => x.status === 'active').length} | лимит агентов сотрудников: ${MAX_AGENTS} | простой: ${IDLE_MINUTES} мин | уровни: ${LEVEL_KEYS.join('/')}`);
|
|
487
504
|
|
package/src/db.mjs
CHANGED
|
@@ -245,6 +245,7 @@ export function openDb(path = 'data/bot.db') {
|
|
|
245
245
|
deleteTopic: db.prepare('DELETE FROM topics WHERE user_id = ? AND thread_id = ?'),
|
|
246
246
|
getGitAccount: db.prepare('SELECT * FROM git_accounts WHERE user_id = ? AND host = ?'),
|
|
247
247
|
listGitAccounts: db.prepare('SELECT * FROM git_accounts WHERE user_id = ? ORDER BY added_at'),
|
|
248
|
+
allGitAccounts: db.prepare('SELECT * FROM git_accounts'),
|
|
248
249
|
saveGitAccount: db.prepare(
|
|
249
250
|
`INSERT INTO git_accounts (user_id, host, login, name, email, token, expires_at, added_at) VALUES (?,?,?,?,?,?,?,?)
|
|
250
251
|
ON CONFLICT(user_id, host) DO UPDATE SET login = excluded.login, name = excluded.name, email = excluded.email,
|
|
@@ -326,6 +327,8 @@ export function openDb(path = 'data/bot.db') {
|
|
|
326
327
|
// --- аккаунты Git ---
|
|
327
328
|
getGitAccount: safe((userId, host) => q.getGitAccount.get(userId, host) ?? null),
|
|
328
329
|
listGitAccounts: (userId) => safe(() => q.listGitAccounts.all(userId))() ?? [],
|
|
330
|
+
/** Аккаунты всех пользователей (для напоминаний об истекающих токенах). */
|
|
331
|
+
allGitAccounts: () => safe(() => q.allGitAccounts.all())() ?? [],
|
|
329
332
|
/** Сохраняет аккаунт сервиса: {host, login, name, email, token, expiresAt}. Возвращает true, если записано. */
|
|
330
333
|
saveGitAccount: (userId, a) =>
|
|
331
334
|
safe(() => q.saveGitAccount.run(userId, a.host, a.login ?? null, a.name ?? null, a.email ?? null, a.token, a.expiresAt ?? null, now()).changes === 1)() ?? false,
|
package/src/git.mjs
CHANGED
|
@@ -89,7 +89,9 @@ export class GitError extends Error {
|
|
|
89
89
|
* wrap — песочница (sandbox.agentSandbox с командой git); hide — строки, которые нужно вычистить из вывода (токены)
|
|
90
90
|
* @returns {Promise<string>} stdout
|
|
91
91
|
*/
|
|
92
|
-
export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120_000, hide = [] } = {}) {
|
|
92
|
+
export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120_000, hide = [], okCodes = [0], maxOut = 4 * 1024 * 1024 } = {}) {
|
|
93
|
+
// okCodes — коды выхода, которые не считаются ошибкой (git diff --no-index возвращает 1, когда различия есть);
|
|
94
|
+
// maxOut — сколько символов вывода хранить (остальное отбрасывается: большой diff целиком не нужен)
|
|
93
95
|
const command = wrap ? wrap.command : gitCommand();
|
|
94
96
|
const argv = wrap ? [...wrap.args, ...args] : args;
|
|
95
97
|
const clean = (s) => hide.filter(Boolean).reduce((acc, h) => acc.replaceAll(h, '***'), s);
|
|
@@ -107,8 +109,15 @@ export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120
|
|
|
107
109
|
timedOut = true;
|
|
108
110
|
killTree(proc, 1000);
|
|
109
111
|
}, timeoutMs);
|
|
110
|
-
|
|
111
|
-
proc.
|
|
112
|
+
// кодировка задаётся потоку: иначе символ не из латиницы, попавший на границу порций, превращается в мусор
|
|
113
|
+
proc.stdout.setEncoding('utf8');
|
|
114
|
+
proc.stderr.setEncoding('utf8');
|
|
115
|
+
proc.stdout.on('data', (d) => {
|
|
116
|
+
if (out.length < maxOut) out += d;
|
|
117
|
+
});
|
|
118
|
+
proc.stderr.on('data', (d) => {
|
|
119
|
+
if (err.length < 64 * 1024) err += d;
|
|
120
|
+
});
|
|
112
121
|
proc.on('error', (e) => {
|
|
113
122
|
clearTimeout(timer);
|
|
114
123
|
reject(new GitError(e.message));
|
|
@@ -116,7 +125,7 @@ export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120
|
|
|
116
125
|
proc.on('close', (code) => {
|
|
117
126
|
clearTimeout(timer);
|
|
118
127
|
if (timedOut) return reject(new GitError(`git ${args[0]}: нет ответа за ${Math.round(timeoutMs / 1000)} с`, { timeout: true }));
|
|
119
|
-
if (code
|
|
128
|
+
if (!okCodes.includes(code)) {
|
|
120
129
|
const stderr = clean(err.trim());
|
|
121
130
|
// подсказки git («hint: …») пользователю не нужны — в сообщение идут последние содержательные строки
|
|
122
131
|
const lines = stderr.split(/\r?\n/).filter((l) => l.trim() && !/^hint:/i.test(l));
|
package/src/gitAccess.mjs
CHANGED
|
@@ -91,6 +91,30 @@ export function agentGitEnv(userId, { agentAuth = GIT_AGENT_AUTH, base = process
|
|
|
91
91
|
return agentAuth ? { ...env, GIT_TERMINAL_PROMPT: '0' } : env;
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
+
const DAY_MS = 24 * 3600_000;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Кому пора напомнить об истекающем токене: за 7 дней, за день и когда срок вышел. Каждое напоминание — один раз
|
|
98
|
+
* (отметка в настройках: срок токена и ступень); новый токен с другим сроком начинает отсчёт заново.
|
|
99
|
+
* @returns {{userId: number, host: object, account: object, stage: '7'|'1'|'expired', days: number}[]}
|
|
100
|
+
*/
|
|
101
|
+
export function tokenReminders(now = Date.now()) {
|
|
102
|
+
const out = [];
|
|
103
|
+
for (const account of db.allGitAccounts()) {
|
|
104
|
+
const host = account.expires_at ? findHost(account.host) : null;
|
|
105
|
+
if (!host) continue;
|
|
106
|
+
const days = Math.ceil((Date.parse(account.expires_at) - now) / DAY_MS);
|
|
107
|
+
const stage = days <= 0 ? 'expired' : days <= 1 ? '1' : days <= 7 ? '7' : null;
|
|
108
|
+
if (!stage) continue;
|
|
109
|
+
const key = `gitexp:${account.user_id}:${account.host}`;
|
|
110
|
+
const mark = `${account.expires_at}|${stage}`;
|
|
111
|
+
if (db.getSetting(key) === mark) continue;
|
|
112
|
+
db.setSetting(key, mark);
|
|
113
|
+
out.push({ userId: account.user_id, host, account, stage, days });
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
|
|
94
118
|
/**
|
|
95
119
|
* Подсказка агенту о git (служебный текст — на английском). Без входа: не пытаться получать и отправлять, а направлять
|
|
96
120
|
* пользователя в /git. Со входом (GIT_AGENT_AUTH): работать можно, показывать вход нельзя. Нет git на сервере — null.
|
|
@@ -107,6 +131,7 @@ export function gitNote(userId, { agentAuth = GIT_AGENT_AUTH } = {}) {
|
|
|
107
131
|
return (
|
|
108
132
|
'[AcpGram] Git: use git locally as usual (status, diff, add, commit, branches, merge). You have no credentials for the remote: ' +
|
|
109
133
|
'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
|
|
134
|
+
'When changes must be sent to or received from the server, put [[git:push]] or [[git:pull]] on its own line at the end of your reply: ' +
|
|
135
|
+
'the bot then shows the user a button that does it (commit first — the button only pushes). The user can also open /git. Never commit files with secrets (.env, keys).'
|
|
111
136
|
);
|
|
112
137
|
}
|
package/src/gitApi.mjs
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// GitHub и GitLab: создание репозитория (публикация проекта) и запрос на слияние — действия, которым нужен API
|
|
2
|
+
// сервиса, а не git. Запросы идут от имени владельца токена (gitHosts.api); у GitLab для них нужно право api.
|
|
3
|
+
import { api, showRemote } from './gitHosts.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Где пользователь может создать репозиторий: личное пространство и группы (GitLab, вместе с подгруппами) или
|
|
7
|
+
* организации (GitHub). search — часть названия группы.
|
|
8
|
+
* @returns {Promise<{id: string|number|null, path: string, kind: 'user'|'group'}[]>} id — для createRepo (у личного — null)
|
|
9
|
+
*/
|
|
10
|
+
export async function listNamespaces(host, token, login, { search = '', ...opts } = {}) {
|
|
11
|
+
const q = search.trim().toLowerCase();
|
|
12
|
+
const own = { id: null, path: login, kind: 'user' };
|
|
13
|
+
if (host.kind === 'gitlab') {
|
|
14
|
+
// 30 — уровень Developer: с него группа может разрешать создание проектов
|
|
15
|
+
const { data } = await api(host, token, `/groups?min_access_level=30&order_by=path&per_page=50${q ? `&search=${encodeURIComponent(q)}` : ''}`, opts);
|
|
16
|
+
return [...(!q || login.toLowerCase().includes(q) ? [own] : []), ...data.map((g) => ({ id: g.id, path: g.full_path, kind: 'group' }))];
|
|
17
|
+
}
|
|
18
|
+
const { data } = await api(host, token, '/user/orgs?per_page=100', opts);
|
|
19
|
+
const orgs = data.map((o) => ({ id: o.login, path: o.login, kind: 'group' })).filter((o) => !q || o.path.toLowerCase().includes(q));
|
|
20
|
+
return [...(!q || login.toLowerCase().includes(q) ? [own] : []), ...orgs];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Видимость нового репозитория, которую умеет сервис: «внутренний» (виден всем пользователям сервера) — только GitLab. */
|
|
24
|
+
export const visibilities = (host) => (host.kind === 'gitlab' ? ['private', 'internal', 'public'] : ['private', 'public']);
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Имя репозитория в адресе из названия папки: латиница, цифры, «.», «-», «_»; остальное — в «-». Не получилось
|
|
28
|
+
* (например, название целиком кириллицей) — null: имя нужно спросить у пользователя.
|
|
29
|
+
*/
|
|
30
|
+
export function repoSlug(name) {
|
|
31
|
+
const slug = String(name ?? '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').replace(/\.git$/, '').slice(0, 100);
|
|
32
|
+
return slug && /[a-z0-9]/.test(slug) ? slug : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Создаёт пустой репозиторий. namespace — запись из listNamespaces; visibility — private | internal | public.
|
|
37
|
+
* @returns {Promise<{url: string, web: string, path: string}>} url — адрес для git (https), web — страница репозитория
|
|
38
|
+
*/
|
|
39
|
+
export async function createRepo(host, token, { name, slug, namespace = null, visibility = 'private' }, opts = {}) {
|
|
40
|
+
if (host.kind === 'gitlab') {
|
|
41
|
+
const body = { name, path: slug, visibility, initialize_with_readme: false, ...(namespace?.id ? { namespace_id: namespace.id } : {}) };
|
|
42
|
+
const { data } = await api(host, token, '/projects', { ...opts, body });
|
|
43
|
+
return { url: data.http_url_to_repo, web: data.web_url, path: data.path_with_namespace };
|
|
44
|
+
}
|
|
45
|
+
const body = { name: slug, private: visibility !== 'public', auto_init: false };
|
|
46
|
+
const { data } = await api(host, token, namespace?.id ? `/orgs/${encodeURIComponent(namespace.id)}/repos` : '/user/repos', { ...opts, body });
|
|
47
|
+
return { url: data.clone_url, web: data.html_url, path: data.full_name };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Путь репозитория на сервисе по адресу origin: «group/sub/app» (у GitHub — «owner/repo»). */
|
|
51
|
+
export const repoPath = (host, remote) => showRemote(remote).slice(showRemote(host.web).length).replace(/^\/+|\/+$/g, '');
|
|
52
|
+
|
|
53
|
+
const projectRef = (host, remote) => (host.kind === 'gitlab' ? `/projects/${encodeURIComponent(repoPath(host, remote))}` : `/repos/${repoPath(host, remote).split('/').map(encodeURIComponent).join('/')}`);
|
|
54
|
+
|
|
55
|
+
/** Основная ветка репозитория на сервере и адрес его страницы. */
|
|
56
|
+
export async function repoInfo(host, token, remote, opts = {}) {
|
|
57
|
+
const { data } = await api(host, token, projectRef(host, remote), opts);
|
|
58
|
+
return { defaultBranch: data.default_branch ?? null, web: data.web_url ?? data.html_url ?? null };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Запрос на слияние ветки branch в ветку target (у GitHub — pull request). Если открытый запрос из этой ветки уже есть,
|
|
63
|
+
* возвращает его, а не создаёт второй.
|
|
64
|
+
* @returns {Promise<{url: string, number: number, existed: boolean}>}
|
|
65
|
+
*/
|
|
66
|
+
export async function openMergeRequest(host, token, remote, { branch, target, title }, opts = {}) {
|
|
67
|
+
const ref = projectRef(host, remote);
|
|
68
|
+
if (host.kind === 'gitlab') {
|
|
69
|
+
const found = await api(host, token, `${ref}/merge_requests?state=opened&source_branch=${encodeURIComponent(branch)}&target_branch=${encodeURIComponent(target)}`, opts);
|
|
70
|
+
if (found.data[0]) return { url: found.data[0].web_url, number: found.data[0].iid, existed: true };
|
|
71
|
+
const { data } = await api(host, token, `${ref}/merge_requests`, { ...opts, body: { source_branch: branch, target_branch: target, title } });
|
|
72
|
+
return { url: data.web_url, number: data.iid, existed: false };
|
|
73
|
+
}
|
|
74
|
+
const owner = repoPath(host, remote).split('/')[0];
|
|
75
|
+
const found = await api(host, token, `${ref}/pulls?state=open&head=${encodeURIComponent(`${owner}:${branch}`)}&base=${encodeURIComponent(target)}`, opts);
|
|
76
|
+
if (found.data[0]) return { url: found.data[0].html_url, number: found.data[0].number, existed: true };
|
|
77
|
+
const { data } = await api(host, token, `${ref}/pulls`, { ...opts, body: { title, head: branch, base: target } });
|
|
78
|
+
return { url: data.html_url, number: data.number, existed: false };
|
|
79
|
+
}
|
package/src/gitHosts.mjs
CHANGED
|
@@ -26,7 +26,7 @@ export function normalizeHostUrl(input) {
|
|
|
26
26
|
const hostId = (kind, web) => `${kind}-${web.replace(/^https:\/\//, '')}`.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+$/, '').slice(0, 40);
|
|
27
27
|
|
|
28
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: '
|
|
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: 'api, read_repository, write_repository' });
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
32
|
* Свой сервер: GitLab или GitHub Enterprise по адресу. name — название для кнопок (по умолчанию — имя сервера).
|
|
@@ -104,19 +104,38 @@ export class HostError extends Error {
|
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
-
|
|
107
|
+
/** Что сервис написал в ответе с ошибкой: у GitLab — message (строка, список или {поле: [причины]}), у GitHub — message и errors. */
|
|
108
|
+
function errorDetail(data) {
|
|
109
|
+
const m = data?.message ?? data?.error_description ?? data?.error;
|
|
110
|
+
const flat = (v) => (v == null ? [] : typeof v === 'string' ? [v] : Array.isArray(v) ? v.flatMap(flat) : Object.entries(v).flatMap(([k, x]) => flat(x).map((s) => `${k} ${s}`)));
|
|
111
|
+
const extra = Array.isArray(data?.errors) ? data.errors.map((e) => (typeof e === 'string' ? e : e?.message || [e?.field, e?.code].filter(Boolean).join(' '))).filter(Boolean) : [];
|
|
112
|
+
return [...flat(m), ...extra].join('; ').slice(0, 300);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Запрос к API сервиса от имени владельца токена. body — объект: отправляется JSON методом POST (или method).
|
|
117
|
+
* Ошибки — HostError: 'auth' (401), 'forbidden' (403: токену не хватает прав), 'http' (с текстом сервиса), 'network'.
|
|
118
|
+
*/
|
|
119
|
+
export async function api(host, token, path, { fetchImpl = fetch, method = null, body = null } = {}) {
|
|
108
120
|
const headers = host.kind === 'github'
|
|
109
121
|
? { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'user-agent': 'acpgram' }
|
|
110
122
|
: { 'private-token': token, accept: 'application/json', 'user-agent': 'acpgram' };
|
|
123
|
+
const init = { headers, signal: AbortSignal.timeout(TIMEOUT_MS) };
|
|
124
|
+
if (body) Object.assign(init, { method: method ?? 'POST', body: JSON.stringify(body), headers: { ...headers, 'content-type': 'application/json' } });
|
|
125
|
+
else if (method) init.method = method;
|
|
111
126
|
let res;
|
|
112
127
|
try {
|
|
113
|
-
res = await fetchImpl(`${host.api}${path}`,
|
|
128
|
+
res = await fetchImpl(`${host.api}${path}`, init);
|
|
114
129
|
} catch (e) {
|
|
115
130
|
throw new HostError('network', `${host.label}: ${e.message}`);
|
|
116
131
|
}
|
|
117
|
-
if (res.status === 401
|
|
118
|
-
if (!res.ok)
|
|
119
|
-
|
|
132
|
+
if (res.status === 401) throw new HostError('auth', `${host.label}: HTTP 401`, 401);
|
|
133
|
+
if (!res.ok) {
|
|
134
|
+
const detail = errorDetail(await res.json().catch(() => null));
|
|
135
|
+
// 403 при чтении профиля — тоже «токен не подошёл»; при остальном — не хватает прав
|
|
136
|
+
throw new HostError(res.status === 403 ? 'forbidden' : 'http', `${host.label}: ${detail || `HTTP ${res.status}`}`, res.status);
|
|
137
|
+
}
|
|
138
|
+
return { data: res.status === 204 ? null : await res.json(), headers: res.headers };
|
|
120
139
|
}
|
|
121
140
|
|
|
122
141
|
const isoDate = (v) => {
|
|
@@ -158,8 +177,8 @@ export function missingScopes(host, scopes) {
|
|
|
158
177
|
if (!Array.isArray(scopes)) return [];
|
|
159
178
|
const has = (s) => scopes.includes(s);
|
|
160
179
|
if (host.kind === 'github') return has('repo') || !scopes.length ? [] : ['repo']; // у fine-grained токенов список пуст
|
|
161
|
-
|
|
162
|
-
return
|
|
180
|
+
// api — создание репозиториев и запросов на слияние; с ним работают и клонирование, и отправка
|
|
181
|
+
return has('api') ? [] : ['api'];
|
|
163
182
|
}
|
|
164
183
|
|
|
165
184
|
export const REPOS_PAGE = 10;
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// Git: что изменилось и какие есть ветки — для экранов «Изменения» и «Ветки» в /git.
|
|
2
|
+
// Только чтение репозитория, кроме переключения и создания ветки. Команды запускает runGit (git.mjs) — с теми же
|
|
3
|
+
// безопасными настройками и, при включённой песочнице, внутри неё.
|
|
4
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { GitError, runGit } from './git.mjs';
|
|
7
|
+
import { samePath } from './projects.mjs';
|
|
8
|
+
|
|
9
|
+
/** Сколько изменённых файлов показывать (в большом несобранном проекте их могут быть тысячи). */
|
|
10
|
+
export const CHANGES_MAX = 300;
|
|
11
|
+
/** Файлы крупнее этого не читаются ради подсчёта строк. */
|
|
12
|
+
const COUNT_MAX_BYTES = 512 * 1024;
|
|
13
|
+
|
|
14
|
+
const kindOf = (xy) => {
|
|
15
|
+
if (xy === '??') return 'new';
|
|
16
|
+
if (xy.includes('U') || xy === 'AA' || xy === 'DD') return 'conflict';
|
|
17
|
+
if (xy.includes('R') || xy.includes('C')) return 'renamed';
|
|
18
|
+
if (xy.includes('D')) return 'deleted';
|
|
19
|
+
if (xy.includes('A')) return 'new';
|
|
20
|
+
return 'modified';
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Разбор `git status --porcelain=v1 -z`: [{path, kind, from?}], kind — new | modified | deleted | renamed | conflict.
|
|
25
|
+
* У переименованного файла следующая запись — прежнее имя.
|
|
26
|
+
*/
|
|
27
|
+
export function parseChanges(text) {
|
|
28
|
+
const parts = String(text ?? '').split('\0');
|
|
29
|
+
const out = [];
|
|
30
|
+
for (let i = 0; i < parts.length; i++) {
|
|
31
|
+
const rec = parts[i];
|
|
32
|
+
if (rec.length < 4) continue;
|
|
33
|
+
const xy = rec.slice(0, 2);
|
|
34
|
+
const item = { path: rec.slice(3), kind: kindOf(xy) };
|
|
35
|
+
if (xy.includes('R') || xy.includes('C')) item.from = parts[++i];
|
|
36
|
+
out.push(item);
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Разбор `git diff --numstat -z`: Map путь → {added, deleted} (у двоичных файлов — null). */
|
|
42
|
+
export function parseNumstat(text) {
|
|
43
|
+
const parts = String(text ?? '').split('\0');
|
|
44
|
+
const map = new Map();
|
|
45
|
+
for (let i = 0; i < parts.length; i++) {
|
|
46
|
+
const m = /^(\d+|-)\t(\d+|-)\t(.*)$/s.exec(parts[i]);
|
|
47
|
+
if (!m) continue;
|
|
48
|
+
let path = m[3];
|
|
49
|
+
if (!path) {
|
|
50
|
+
path = parts[i + 2]; // переименование: далее — прежнее и новое имя
|
|
51
|
+
i += 2;
|
|
52
|
+
}
|
|
53
|
+
if (path) map.set(path, { added: m[1] === '-' ? null : Number(m[1]), deleted: m[2] === '-' ? null : Number(m[2]) });
|
|
54
|
+
}
|
|
55
|
+
return map;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Число строк нового файла (которого git ещё не знает) или null, если он велик, двоичный или не читается. */
|
|
59
|
+
function countLines(file) {
|
|
60
|
+
try {
|
|
61
|
+
if (statSync(file).size > COUNT_MAX_BYTES) return null;
|
|
62
|
+
const buf = readFileSync(file);
|
|
63
|
+
if (buf.includes(0)) return null;
|
|
64
|
+
if (!buf.length) return 0;
|
|
65
|
+
let n = 0;
|
|
66
|
+
for (const b of buf) if (b === 10) n++;
|
|
67
|
+
return buf[buf.length - 1] === 10 ? n : n + 1;
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Несохранённые изменения рабочей папки относительно последнего коммита: [{path, kind, added, deleted, from?}].
|
|
75
|
+
* added / deleted — число строк (null, если неизвестно). total — сколько всего изменённых файлов (список обрезается).
|
|
76
|
+
*/
|
|
77
|
+
export async function changedFiles(cwd, opts = {}) {
|
|
78
|
+
const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
79
|
+
const all = parseChanges(await runGit(['status', '--porcelain=v1', '-z', '--untracked-files=all'], { cwd, ...opts }));
|
|
80
|
+
// в репозитории без коммитов сравнивать не с чем — тогда без числа строк
|
|
81
|
+
const counts = await runGit(['diff', '--numstat', '-z', 'HEAD'], { cwd, ...opts }).then(parseNumstat, () => new Map());
|
|
82
|
+
const files = all.slice(0, CHANGES_MAX).map((f) => {
|
|
83
|
+
const c = counts.get(f.path);
|
|
84
|
+
if (c) return { ...f, ...c };
|
|
85
|
+
return { ...f, added: f.kind === 'new' ? countLines(join(top, f.path)) : null, deleted: f.kind === 'new' ? 0 : null };
|
|
86
|
+
});
|
|
87
|
+
return { files, total: all.length };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Изменения одного файла текстом (unified diff, без служебного начала). Новый файл показывается целиком как добавленный.
|
|
92
|
+
* @param {{path: string, kind: string}} file запись из changedFiles (путь — от корня репозитория)
|
|
93
|
+
*/
|
|
94
|
+
export async function fileDiff(cwd, file, opts = {}) {
|
|
95
|
+
const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
96
|
+
const base = { cwd: top, maxOut: 300_000, ...opts };
|
|
97
|
+
const raw = file.kind === 'new'
|
|
98
|
+
? await runGit(['diff', '--no-color', '--no-ext-diff', '--no-index', '--', '/dev/null', file.path], { ...base, okCodes: [0, 1] })
|
|
99
|
+
: await runGit(['diff', '--no-color', '--no-ext-diff', 'HEAD', '--', file.path], base);
|
|
100
|
+
// «diff --git…», «index…» и подобные строки до первого «---» пользователю ничего не говорят
|
|
101
|
+
const lines = raw.split(/\r?\n/);
|
|
102
|
+
const start = lines.findIndex((l) => l.startsWith('--- ') || l.startsWith('Binary files') || l.startsWith('@@'));
|
|
103
|
+
return (start > 0 ? lines.slice(start) : lines).join('\n').trimEnd();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Коммиты: которые ещё не отправлены ('out') или которые есть на сервере, а локально нет ('in').
|
|
108
|
+
* Без ветки на сервере «не отправлено» — последние коммиты ветки, «на сервере» — пусто.
|
|
109
|
+
* @returns {Promise<{hash: string, author: string, date: string, subject: string}[]>}
|
|
110
|
+
*/
|
|
111
|
+
export async function commitList(cwd, dir, opts = {}, limit = 20) {
|
|
112
|
+
const upstream = await runGit(['rev-parse', '--abbrev-ref', '@{u}'], { cwd, ...opts }).then((s) => s.trim(), () => null);
|
|
113
|
+
if (!upstream && dir === 'in') return [];
|
|
114
|
+
const range = !upstream ? 'HEAD' : dir === 'in' ? 'HEAD..@{u}' : '@{u}..HEAD';
|
|
115
|
+
const out = await runGit(['log', `-n${limit}`, '--format=%h%x09%an%x09%ad%x09%s', '--date=short', range], { cwd, ...opts }).catch(() => '');
|
|
116
|
+
return out.split(/\r?\n/).filter(Boolean).map((l) => {
|
|
117
|
+
const [hash, author, date, ...rest] = l.split('\t');
|
|
118
|
+
return { hash, author, date, subject: rest.join('\t') };
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Ветки: локальные и ветки сервера (origin) одним списком — [{name, local, remote, date, current}], текущая первой,
|
|
124
|
+
* дальше по дате последнего коммита.
|
|
125
|
+
*/
|
|
126
|
+
export async function listBranches(cwd, opts = {}) {
|
|
127
|
+
const current = await runGit(['branch', '--show-current'], { cwd, ...opts }).then((s) => s.trim() || null, () => null);
|
|
128
|
+
const out = await runGit(['for-each-ref', '--format=%(refname)%09%(committerdate:iso-strict)', 'refs/heads', 'refs/remotes/origin'], { cwd, ...opts });
|
|
129
|
+
const map = new Map();
|
|
130
|
+
for (const line of out.split(/\r?\n/).filter(Boolean)) {
|
|
131
|
+
const [ref, date] = line.split('\t');
|
|
132
|
+
const local = ref.startsWith('refs/heads/');
|
|
133
|
+
const name = local ? ref.slice('refs/heads/'.length) : ref.slice('refs/remotes/origin/'.length);
|
|
134
|
+
if (!name || name === 'HEAD') continue;
|
|
135
|
+
const b = map.get(name) ?? { name, local: false, remote: false, date: '' };
|
|
136
|
+
if (local) b.local = true;
|
|
137
|
+
else b.remote = true;
|
|
138
|
+
if (date > b.date) b.date = date;
|
|
139
|
+
map.set(name, b);
|
|
140
|
+
}
|
|
141
|
+
const list = [...map.values()].map((b) => ({ ...b, current: b.name === current }));
|
|
142
|
+
list.sort((a, b) => Number(b.current) - Number(a.current) || b.date.localeCompare(a.date) || a.name.localeCompare(b.name));
|
|
143
|
+
return { current, branches: list };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Название ветки из текста пользователя: пробелы — в «-»; не подходит — null (проверку формата делает сам git). */
|
|
147
|
+
export async function branchName(input, { cwd, ...opts }) {
|
|
148
|
+
const name = String(input ?? '').trim().replace(/\s+/g, '-');
|
|
149
|
+
if (!name || name.length > 100 || name.startsWith('-')) return null;
|
|
150
|
+
return runGit(['check-ref-format', '--branch', name], { cwd, ...opts }).then(() => name, () => null);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Переключается на ветку: локальную — как есть, существующую только на сервере — создаёт локальную, связанную с ней.
|
|
155
|
+
* Вызывающий отвечает за то, что в рабочей папке нет несохранённых изменений.
|
|
156
|
+
*/
|
|
157
|
+
export async function switchBranch(cwd, branch, opts = {}) {
|
|
158
|
+
if (!branch?.name || branch.name.startsWith('-')) throw new GitError('некорректное название ветки');
|
|
159
|
+
if (branch.local) return runGit(['switch', '--quiet', branch.name], { cwd, ...opts });
|
|
160
|
+
return runGit(['switch', '--quiet', '--track', `origin/${branch.name}`], { cwd, ...opts });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Создаёт ветку от текущего коммита и переключается на неё (несохранённые изменения остаются в рабочей папке). */
|
|
164
|
+
export const createBranch = (cwd, name, opts = {}) => runGit(['switch', '--quiet', '-c', name], { cwd, ...opts });
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Отменяет несохранённые изменения файлов (записи из changedFiles): изменённые и удалённые возвращаются к последнему
|
|
168
|
+
* коммиту, новые — удаляются. Действие необратимо; что отменять, решает вызывающий (секреты сюда не передаются).
|
|
169
|
+
* @returns {Promise<number>} сколько файлов обработано
|
|
170
|
+
*/
|
|
171
|
+
export async function discardFiles(cwd, files, opts = {}) {
|
|
172
|
+
if (!files.length) return 0;
|
|
173
|
+
const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
174
|
+
const at = { cwd: top, ...opts };
|
|
175
|
+
const paths = [...new Set(files.flatMap((f) => [f.path, f.from]).filter(Boolean))];
|
|
176
|
+
// какие пути есть в последнем коммите: их возвращаем, остальные (новые файлы) убираем
|
|
177
|
+
const tracked = new Set((await runGit(['ls-tree', '-r', '-z', '--name-only', 'HEAD', '--', ...paths], at).catch(() => '')).split('\0').filter(Boolean));
|
|
178
|
+
const restore = paths.filter((p) => tracked.has(p));
|
|
179
|
+
const remove = paths.filter((p) => !tracked.has(p));
|
|
180
|
+
await runGit(['reset', '-q', '--', ...paths], at).catch(() => {}); // убрать из подготовленного к коммиту
|
|
181
|
+
if (restore.length) await runGit(['checkout', '-q', 'HEAD', '--', ...restore], at);
|
|
182
|
+
if (remove.length) await runGit(['clean', '-f', '-q', '--', ...remove], at);
|
|
183
|
+
return files.length;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Является ли сама папка cwd корнем репозитория (а не просто лежит внутри чужого, выше по дереву). */
|
|
187
|
+
export async function isRepoRoot(cwd, opts = {}) {
|
|
188
|
+
const top = await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts }).then((s) => s.trim(), () => null);
|
|
189
|
+
return Boolean(top) && samePath(resolve(top), resolve(cwd));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Делает папку репозиторием с веткой main, если она им ещё не была (чужой репозиторий выше по дереву не трогается). */
|
|
193
|
+
export async function ensureRepo(cwd, opts = {}) {
|
|
194
|
+
if (!(await isRepoRoot(cwd, opts))) await runGit(['init', '-q', '-b', 'main'], { cwd, ...opts });
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Есть ли в репозитории хотя бы один коммит. */
|
|
198
|
+
export const hasCommits = (cwd, opts = {}) => runGit(['rev-parse', '--verify', '-q', 'HEAD'], { cwd, ...opts }).then(() => true, () => false);
|
|
199
|
+
|
|
200
|
+
/** Описание последнего коммита (первая строка) или пусто. */
|
|
201
|
+
export const lastSubject = (cwd, opts = {}) => runGit(['log', '-1', '--format=%s'], { cwd, ...opts }).then((s) => s.trim(), () => '');
|
|
202
|
+
|
|
203
|
+
/** Записывает адрес сервера (origin). Адрес — без входа: он передаётся отдельно, на время отправки. */
|
|
204
|
+
export async function setRemote(cwd, url, opts = {}) {
|
|
205
|
+
const has = await runGit(['config', '--get', 'remote.origin.url'], { cwd, ...opts }).then((s) => s.trim(), () => '');
|
|
206
|
+
await runGit(has ? ['remote', 'set-url', 'origin', url] : ['remote', 'add', 'origin', url], { cwd, ...opts });
|
|
207
|
+
}
|
package/src/gitKeys.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Что стоит за кнопкой списка в /git (файл, ветка, репозиторий, место публикации).
|
|
2
|
+
// Кнопка не должна ссылаться на номер в списке: список перерисовывается, и старая кнопка указала бы на другой элемент —
|
|
3
|
+
// для «Отменить изменения» это значило бы потерю не того файла. Поэтому каждому элементу при показе выдаётся ключ,
|
|
4
|
+
// который больше никогда не повторяется: старая кнопка ведёт либо к тому же элементу, либо никуда («кнопка устарела»).
|
|
5
|
+
|
|
6
|
+
let seq = 0;
|
|
7
|
+
/** Сколько ключей помнит диалог; сверх этого старые забываются, их кнопки становятся устаревшими. */
|
|
8
|
+
const KEEP = 600;
|
|
9
|
+
|
|
10
|
+
/** Запоминает значение за кнопкой и возвращает её ключ (короткая строка для callback_data). */
|
|
11
|
+
export function remember(st, value) {
|
|
12
|
+
st.gitKeys ??= new Map();
|
|
13
|
+
if (st.gitKeys.size >= KEEP) st.gitKeys.clear();
|
|
14
|
+
const key = (++seq).toString(36);
|
|
15
|
+
st.gitKeys.set(key, value);
|
|
16
|
+
return key;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Значение за кнопкой по её ключу или null, если кнопка устарела. */
|
|
20
|
+
export const recall = (st, key) => st.gitKeys?.get(String(key)) ?? null;
|