acpgram 1.31.7 → 1.31.8
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 +1 -1
- package/README.ru.md +2 -1
- package/package.json +1 -1
- package/src/git.mjs +50 -5
- package/src/gitCtx.mjs +68 -0
- package/src/gitInspect.mjs +7 -2
- package/src/gitPublishUi.mjs +25 -28
- package/src/gitRepoUi.mjs +43 -33
- package/src/gitUi.mjs +49 -58
- package/src/i18n.mjs +1 -0
- package/src/state.mjs +1 -0
package/README.md
CHANGED
|
@@ -250,7 +250,7 @@ The `/git` command connects projects to GitHub, GitLab.com and your own servers
|
|
|
250
250
|
|
|
251
251
|
**Where the token lives.** By default only in the bot's database: the bot clones, pulls and pushes, while the agent works with the repository locally (status, diff, commits, branches, merges) and sends the user to `/git` when changes must be pushed. In the sandbox the token is not reachable by the agent at all. The administrator can choose another mode, `GIT_AGENT_AUTH=1`: the sign-in is also given to the agent process, which then pulls and pushes by itself. That is more convenient, but the token becomes visible to the agent and may end up in a model request; turn it on only if you trust the models your teammates use.
|
|
252
252
|
|
|
253
|
-
**How the bot runs git.** The repository lives where the agent writes, and repository settings and hooks can run programs. So the bot runs git with hooks
|
|
253
|
+
**How the bot runs git.** The repository lives where the agent writes, and repository settings and hooks can run programs. So the bot runs git with hooks, credential helpers and password prompts turned off, without the global and system config (on Linux and macOS), over HTTPS only, and, when the sandbox is on, inside the same teammate's sandbox. Before operations with sign-in and commits, the local `.git/config` is checked: commands, external includes, filters (except Git LFS) and disabled TLS verification are rejected, and only setting names are shown in the reply. The sign-in is needed only for cloning, pulling, pushing, switching branches and creating a merge request; local commands run without it and it is never written to the repository settings or the URL. Only one git operation runs per repository folder, and a failed clone leaves no partial folder behind. Residual risk: on Windows the global and system config is still read, Git LFS filters run during operations, and without the sandbox a deliberately malicious agent could change the local config between the check and the command.
|
|
254
254
|
|
|
255
255
|
Only HTTPS repositories from the listed services can be connected; a repository with an SSH address or from another server is shown, but the bot cannot pull from or push to it.
|
|
256
256
|
|
package/README.ru.md
CHANGED
|
@@ -138,7 +138,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
138
138
|
|
|
139
139
|
**Где лежит токен.** По умолчанию — только в базе бота: клонирование, получение и отправку делает бот, а агент работает с репозиторием локально (состояние, сравнение, коммиты, ветки, слияние) и на просьбу отправить изменения направляет пользователя в `/git`. В песочнице токен агенту недоступен совсем. Администратор может выбрать другой режим — `GIT_AGENT_AUTH=1`: вход передаётся и процессу агента, он сам получает и отправляет изменения. Это удобнее, но токен становится виден агенту и может попасть в запрос к модели; включайте его, только если доверяете моделям, с которыми работают сотрудники.
|
|
140
140
|
|
|
141
|
-
**Как бот запускает git.** Репозиторий лежит там, куда пишет агент, а настройки и хуки репозитория умеют запускать программы. Поэтому бот запускает git с отключёнными
|
|
141
|
+
**Как бот запускает git.** Репозиторий лежит там, куда пишет агент, а настройки и хуки репозитория умеют запускать программы. Поэтому бот запускает git с отключёнными хуками, помощниками входа и запросом пароля, без общего и системного конфига (на Linux и macOS), только по HTTPS, а при включённой песочнице — внутри песочницы того же сотрудника. Перед операциями со входом и коммитом проверяется локальный `.git/config`: команды, внешние include, фильтры (кроме Git LFS) и отключённая проверка TLS отклоняются, в ответе показываются только имена параметров. Вход нужен только для клонирования, получения, отправки, смены ветки и запроса на слияние; локальные команды запускаются без него и в настройки репозитория он не пишется. На одну папку репозитория одновременно работает одна операция, а неудавшийся клон не оставляет частичную папку. Остаточный риск: на Windows читается глобальный и системный конфиг, фильтры Git LFS выполняются при операциях, а без песочницы намеренно вредоносный агент мог бы изменить локальный конфиг между проверкой и командой.
|
|
142
142
|
|
|
143
143
|
Подключаются только репозитории по HTTPS с перечисленных сервисов; репозиторий с адресом SSH или с другого сервера бот показывает, но получать и отправлять в него не может.
|
|
144
144
|
|
|
@@ -432,6 +432,7 @@ src/
|
|
|
432
432
|
projectFiles.mjs файлы проекта в обход агента: безопасная запись и удаление внутри проекта, без ссылок
|
|
433
433
|
filesUi.mjs команда /files: список, создание, загрузка и удаление файлов проекта
|
|
434
434
|
git.mjs команды git бота: клонирование, состояние, получение, отправка, коммит без секретов; безопасный запуск
|
|
435
|
+
gitCtx.mjs общие настройки запуска, выбор аккаунта и блокировки для экранов git
|
|
435
436
|
gitHosts.mjs GitHub и GitLab: профиль и репозитории по токену, вход для git
|
|
436
437
|
gitAccess.mjs аккаунты Git пользователей; что из них получает агент (автор коммитов, вход при GIT_AGENT_AUTH)
|
|
437
438
|
gitUi.mjs команда /git: аккаунты, свои серверы, клонирование, получить / отправить / сохранить
|
package/package.json
CHANGED
package/src/git.mjs
CHANGED
|
@@ -54,7 +54,10 @@ export const SAFE_CONFIG = [
|
|
|
54
54
|
['core.hooksPath', devNull],
|
|
55
55
|
['core.fsmonitor', 'false'],
|
|
56
56
|
['credential.helper', ''],
|
|
57
|
+
['protocol.allow', 'never'],
|
|
58
|
+
['protocol.https.allow', 'always'],
|
|
57
59
|
['protocol.ext.allow', 'never'],
|
|
60
|
+
['safe.bareRepository', 'explicit'],
|
|
58
61
|
['advice.detachedHead', 'false'],
|
|
59
62
|
['core.quotePath', 'false'], // имена файлов не латиницей — как есть, а не восьмеричными кодами
|
|
60
63
|
];
|
|
@@ -65,7 +68,7 @@ export const SAFE_CONFIG = [
|
|
|
65
68
|
* На Linux и macOS общий и системный конфиги не читаются: в песочнице общий конфиг лежит в папке, куда пишет агент.
|
|
66
69
|
*/
|
|
67
70
|
export function gitEnv({ identity = null, auth = [], base = process.env } = {}) {
|
|
68
|
-
const env = { ...agentEnv({ apiKeys: [] }, base), GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_EDITOR: 'true', GIT_PAGER: 'cat', LC_ALL: 'C' };
|
|
71
|
+
const env = { ...agentEnv({ apiKeys: [] }, base), GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_ASKPASS: '', GIT_EDITOR: 'true', GIT_PAGER: 'cat', LC_ALL: 'C' };
|
|
69
72
|
if (!IS_WIN) Object.assign(env, { GIT_CONFIG_GLOBAL: devNull, GIT_CONFIG_NOSYSTEM: '1' });
|
|
70
73
|
if (identity?.name && identity?.email) {
|
|
71
74
|
Object.assign(env, { GIT_AUTHOR_NAME: identity.name, GIT_AUTHOR_EMAIL: identity.email, GIT_COMMITTER_NAME: identity.name, GIT_COMMITTER_EMAIL: identity.email });
|
|
@@ -83,6 +86,13 @@ export class GitError extends Error {
|
|
|
83
86
|
}
|
|
84
87
|
}
|
|
85
88
|
|
|
89
|
+
export class GitConfigError extends GitError {
|
|
90
|
+
constructor(keys) {
|
|
91
|
+
super(`небезопасные настройки репозитория: ${keys.join(', ')}`);
|
|
92
|
+
this.keys = keys;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
86
96
|
/**
|
|
87
97
|
* Запускает git. Без оболочки: аргументы (описание коммита, имена файлов) передаются как есть.
|
|
88
98
|
* @param {string[]} args
|
|
@@ -138,6 +148,28 @@ export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120
|
|
|
138
148
|
});
|
|
139
149
|
}
|
|
140
150
|
|
|
151
|
+
const DENIED_CONFIG = (key) =>
|
|
152
|
+
['core.sshcommand', 'core.askpass', 'gpg.program', 'core.alternaterefscommand'].includes(key) ||
|
|
153
|
+
key === 'include.path' ||
|
|
154
|
+
/^includeif\..*\.path$/.test(key) ||
|
|
155
|
+
/^remote\..+\.(uploadpack|receivepack)$/.test(key) ||
|
|
156
|
+
(/^filter\./.test(key) && !key.startsWith('filter.lfs.'));
|
|
157
|
+
|
|
158
|
+
const isFalse = (value) => /^(false|no|off|0)$/i.test(String(value).trim());
|
|
159
|
+
|
|
160
|
+
export async function assertPlainConfig(cwd, opts = {}) {
|
|
161
|
+
const raw = await runGit(['config', '--local', '--list', '-z'], { cwd, ...opts });
|
|
162
|
+
const bad = [];
|
|
163
|
+
for (const rec of raw.split('\0')) {
|
|
164
|
+
if (!rec) continue;
|
|
165
|
+
const cut = rec.indexOf('\n');
|
|
166
|
+
const key = (cut < 0 ? rec : rec.slice(0, cut)).toLowerCase();
|
|
167
|
+
const value = cut < 0 ? '' : rec.slice(cut + 1);
|
|
168
|
+
if (DENIED_CONFIG(key) || (/^http(\..+)?\.sslverify$/.test(key) && isFalse(value))) bad.push(key);
|
|
169
|
+
}
|
|
170
|
+
if (bad.length) throw new GitConfigError([...new Set(bad)]);
|
|
171
|
+
}
|
|
172
|
+
|
|
141
173
|
/**
|
|
142
174
|
* Разбор `git status --porcelain=v2 --branch`.
|
|
143
175
|
* @returns {{branch: string|null, upstream: string|null, ahead: number, behind: number, changed: number}}
|
|
@@ -174,17 +206,26 @@ export async function repoState(cwd, opts = {}) {
|
|
|
174
206
|
}
|
|
175
207
|
|
|
176
208
|
/** Клонирует репозиторий url в папку dest (её ещё нет), запускается из её родительской папки cwd. Подмодули не тянутся. */
|
|
177
|
-
export
|
|
209
|
+
export async function cloneRepo(url, dest, { cwd, ...opts }) {
|
|
210
|
+
await runGit(['clone', '--no-recurse-submodules', '--', url, dest], { cwd, timeoutMs: 10 * 60_000, ...opts });
|
|
211
|
+
await assertPlainConfig(join(cwd, dest), opts);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const fetchRaw = (cwd, opts) => runGit(['fetch', '--prune', 'origin'], { cwd, timeoutMs: 60_000, ...opts });
|
|
178
215
|
|
|
179
216
|
/** Сверяется с сервером (git fetch): рабочие файлы не трогает, обновляет сведения о ветках сервера. */
|
|
180
|
-
export
|
|
217
|
+
export async function fetchRepo(cwd, opts = {}) {
|
|
218
|
+
await assertPlainConfig(cwd, opts);
|
|
219
|
+
return fetchRaw(cwd, opts);
|
|
220
|
+
}
|
|
181
221
|
|
|
182
222
|
/**
|
|
183
223
|
* Получает изменения с сервера: fetch и перемотка вперёд, если это возможно без слияния.
|
|
184
224
|
* @returns {Promise<'updated'|'uptodate'|'diverged'|'noupstream'>} diverged — истории разошлись, нужно слияние (его делает агент)
|
|
185
225
|
*/
|
|
186
226
|
export async function pullRepo(cwd, opts = {}) {
|
|
187
|
-
await
|
|
227
|
+
await assertPlainConfig(cwd, opts);
|
|
228
|
+
await fetchRaw(cwd, opts);
|
|
188
229
|
const before = parseStatus(await runGit(['status', '--porcelain=v2', '--branch'], { cwd, ...opts }));
|
|
189
230
|
if (!before.upstream) return 'noupstream';
|
|
190
231
|
if (!before.behind) return 'uptodate';
|
|
@@ -211,7 +252,10 @@ export async function unpushedSecrets(cwd, opts = {}) {
|
|
|
211
252
|
}
|
|
212
253
|
|
|
213
254
|
/** Отправляет текущую ветку на сервер (и связывает её с веткой сервера). */
|
|
214
|
-
export
|
|
255
|
+
export async function pushRepo(cwd, opts = {}) {
|
|
256
|
+
await assertPlainConfig(cwd, opts);
|
|
257
|
+
return runGit(['push', '-u', 'origin', 'HEAD'], { cwd, ...opts });
|
|
258
|
+
}
|
|
215
259
|
|
|
216
260
|
/**
|
|
217
261
|
* Коммитит все изменения, кроме файлов с секретами: их из коммита убирает, новые — дописывает в .gitignore.
|
|
@@ -221,6 +265,7 @@ export const pushRepo = (cwd, opts = {}) => runGit(['push', '-u', 'origin', 'HEA
|
|
|
221
265
|
* подменён ссылкой или недоступен, правила туда не записаны
|
|
222
266
|
*/
|
|
223
267
|
export async function commitAll(cwd, message, opts = {}) {
|
|
268
|
+
await assertPlainConfig(cwd, opts);
|
|
224
269
|
await runGit(['add', '-A'], { cwd, ...opts });
|
|
225
270
|
const staged = (await runGit(['diff', '--cached', '--name-status'], { cwd, ...opts }))
|
|
226
271
|
.split(/\r?\n/)
|
package/src/gitCtx.mjs
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { db } from './ctx.mjs';
|
|
3
|
+
import { accountsOf, hostFor, identityOf } from './gitAccess.mjs';
|
|
4
|
+
import { authConfig, HostError } from './gitHosts.mjs';
|
|
5
|
+
import { gitCommand, gitEnv, GitConfigError, GitError, repoState } from './git.mjs';
|
|
6
|
+
import { errText } from './i18n.mjs';
|
|
7
|
+
import { insideRoot, isPersonalRoot, ROOT } from './projects.mjs';
|
|
8
|
+
import { agentSandbox } from './sandbox.mjs';
|
|
9
|
+
import { rootOf, sandboxed } from './state.mjs';
|
|
10
|
+
import { th } from './ui.mjs';
|
|
11
|
+
|
|
12
|
+
export const projectOf = (st) => insideRoot(st.project, rootOf(st.userId));
|
|
13
|
+
|
|
14
|
+
const baseOpts = (st, cwd, account, auth, hide) => {
|
|
15
|
+
const root = rootOf(st.userId);
|
|
16
|
+
const wrap = sandboxed(st.userId)
|
|
17
|
+
? agentSandbox({ userId: st.userId, cwd, root, command: gitCommand(), protect: isPersonalRoot(root) ? [ROOT] : [] })
|
|
18
|
+
: null;
|
|
19
|
+
return { env: gitEnv({ identity: identityOf(account), auth }), wrap, hide };
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export function gitOpts(st, cwd, account = null) {
|
|
23
|
+
const who = account ?? accountsOf(st.userId)[0]?.account ?? null;
|
|
24
|
+
return baseOpts(st, cwd, who, [], []);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function gitNetOpts(st, cwd, { host, account }) {
|
|
28
|
+
const auth = host && account ? authConfig(host, account.token) : [];
|
|
29
|
+
const hide = account ? [account.token, auth[0]?.[1]?.split(' ').pop()] : [];
|
|
30
|
+
return baseOpts(st, cwd, account, auth, hide);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function repoOf(st, project) {
|
|
34
|
+
const state = await repoState(project, gitOpts(st, project));
|
|
35
|
+
if (!state || !insideRoot(state.top, rootOf(st.userId))) return null;
|
|
36
|
+
const host = hostFor(state.remote);
|
|
37
|
+
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
38
|
+
return { state, host, account };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const failText = (e, lang, host = null) => {
|
|
42
|
+
if (e instanceof GitConfigError) return th('git.unsafeConfig', lang, { keys: e.keys.join(', ') });
|
|
43
|
+
if (e instanceof HostError && e.code === 'forbidden') return th('git.needApi', lang, { host: host?.label ?? 'Git', msg: e.message });
|
|
44
|
+
return th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const gitLocks = new Map();
|
|
48
|
+
const lockKey = (cwd) => {
|
|
49
|
+
const p = resolve(String(cwd ?? ''));
|
|
50
|
+
return process.platform === 'win32' ? p.toLowerCase() : p;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export function acquireGitLock(st, cwd) {
|
|
54
|
+
const key = lockKey(cwd);
|
|
55
|
+
if (gitLocks.has(key)) return null;
|
|
56
|
+
const token = Symbol('git');
|
|
57
|
+
gitLocks.set(key, token);
|
|
58
|
+
st.gitBusy = true;
|
|
59
|
+
return { key, token };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function releaseGitLock(st, lock) {
|
|
63
|
+
if (!lock) return;
|
|
64
|
+
if (gitLocks.get(lock.key) === lock.token) gitLocks.delete(lock.key);
|
|
65
|
+
st.gitBusy = false;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const isGitLocked = (cwd) => gitLocks.has(lockKey(cwd));
|
package/src/gitInspect.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// безопасными настройками и, при включённой песочнице, внутри неё.
|
|
4
4
|
import { lstatSync, readFileSync } from 'node:fs';
|
|
5
5
|
import { join, resolve } from 'node:path';
|
|
6
|
-
import { GitError, runGit } from './git.mjs';
|
|
6
|
+
import { assertPlainConfig, GitError, runGit } from './git.mjs';
|
|
7
7
|
import { samePath } from './projects.mjs';
|
|
8
8
|
|
|
9
9
|
/** Сколько изменённых файлов показывать (в большом несобранном проекте их могут быть тысячи). */
|
|
@@ -158,12 +158,16 @@ export async function branchName(input, { cwd, ...opts }) {
|
|
|
158
158
|
*/
|
|
159
159
|
export async function switchBranch(cwd, branch, opts = {}) {
|
|
160
160
|
if (!branch?.name || branch.name.startsWith('-')) throw new GitError('некорректное название ветки');
|
|
161
|
+
await assertPlainConfig(cwd, opts);
|
|
161
162
|
if (branch.local) return runGit(['switch', '--quiet', branch.name], { cwd, ...opts });
|
|
162
163
|
return runGit(['switch', '--quiet', '--track', `origin/${branch.name}`], { cwd, ...opts });
|
|
163
164
|
}
|
|
164
165
|
|
|
165
166
|
/** Создаёт ветку от текущего коммита и переключается на неё (несохранённые изменения остаются в рабочей папке). */
|
|
166
|
-
export
|
|
167
|
+
export async function createBranch(cwd, name, opts = {}) {
|
|
168
|
+
await assertPlainConfig(cwd, opts);
|
|
169
|
+
return runGit(['switch', '--quiet', '-c', name], { cwd, ...opts });
|
|
170
|
+
}
|
|
167
171
|
|
|
168
172
|
/**
|
|
169
173
|
* Отменяет несохранённые изменения файлов (записи из changedFiles): изменённые и удалённые возвращаются к последнему
|
|
@@ -172,6 +176,7 @@ export const createBranch = (cwd, name, opts = {}) => runGit(['switch', '--quiet
|
|
|
172
176
|
*/
|
|
173
177
|
export async function discardFiles(cwd, files, opts = {}) {
|
|
174
178
|
if (!files.length) return 0;
|
|
179
|
+
await assertPlainConfig(cwd, opts);
|
|
175
180
|
const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
176
181
|
const at = { cwd: top, ...opts };
|
|
177
182
|
const paths = [...new Set(files.flatMap((f) => [f.path, f.from]).filter(Boolean))];
|
package/src/gitPublishUi.mjs
CHANGED
|
@@ -2,17 +2,18 @@
|
|
|
2
2
|
// Публикация: папка, которая ещё не связана с сервером, становится репозиторием — пользователь выбирает сервис, место
|
|
3
3
|
// (личное пространство, группа или организация), видимость и название; бот создаёт репозиторий, делает первый коммит
|
|
4
4
|
// (без файлов с секретами) и отправляет. Запрос на слияние: из текущей ветки в основную ветку репозитория.
|
|
5
|
-
//
|
|
5
|
+
// Общие помощники (проект, репозиторий, запуск git) живут в gitCtx.mjs.
|
|
6
6
|
import { basename } from 'node:path';
|
|
7
7
|
import { db, log, say } from './ctx.mjs';
|
|
8
8
|
import { canManageFiles } from './filesUi.mjs';
|
|
9
|
-
import {
|
|
9
|
+
import { commitAll, pushRepo, repoState } from './git.mjs';
|
|
10
10
|
import { accountsOf, findHost, hostFor } from './gitAccess.mjs';
|
|
11
|
+
import { acquireGitLock, failText, gitNetOpts, gitOpts, releaseGitLock, repoOf } from './gitCtx.mjs';
|
|
11
12
|
import { recall, remember } from './gitKeys.mjs';
|
|
12
13
|
import { createRepo, listNamespaces, openMergeRequest, repoInfo, repoSlug, visibilities } from './gitApi.mjs';
|
|
13
14
|
import { HostError, showRemote } from './gitHosts.mjs';
|
|
14
15
|
import { ensureRepo, hasCommits, isRepoRoot, lastSubject, setRemote } from './gitInspect.mjs';
|
|
15
|
-
import {
|
|
16
|
+
import { t } from './i18n.mjs';
|
|
16
17
|
import { userPath } from './state.mjs';
|
|
17
18
|
import { hCode, th } from './ui.mjs';
|
|
18
19
|
|
|
@@ -27,16 +28,10 @@ const VIS_MARK = { private: '🔒', internal: '🏢', public: '🌍' };
|
|
|
27
28
|
const backRow = (lang) => [{ text: t('btn.back', lang), callback_data: 'gt:v' }];
|
|
28
29
|
const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] });
|
|
29
30
|
|
|
30
|
-
/** Текст ошибки: не хватило прав токена — отдельной подсказкой (нужен токен с правом api). */
|
|
31
|
-
const failText = (e, lang, host) => {
|
|
32
|
-
if (e instanceof HostError && e.code === 'forbidden') return th('git.needApi', lang, { host: host?.label ?? 'Git', msg: e.message });
|
|
33
|
-
return th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
|
|
34
|
-
};
|
|
35
|
-
|
|
36
31
|
/** Можно ли публиковать проект: это ещё не репозиторий с адресом сервера (свой репозиторий без origin — тоже можно). */
|
|
37
|
-
export async function canPublish(st, project
|
|
32
|
+
export async function canPublish(st, project) {
|
|
38
33
|
if (!canManageFiles(st.userId) || !accountsOf(st.userId).length) return false;
|
|
39
|
-
const opts =
|
|
34
|
+
const opts = gitOpts(st, project);
|
|
40
35
|
if (!(await isRepoRoot(project, opts))) return true;
|
|
41
36
|
return !(await repoState(project, opts))?.remote;
|
|
42
37
|
}
|
|
@@ -72,11 +67,13 @@ function summaryView(st, project, lang) {
|
|
|
72
67
|
}
|
|
73
68
|
|
|
74
69
|
/** Создаёт репозиторий на сервисе, делает первый коммит и отправляет. */
|
|
75
|
-
async function publish(st, project, lang, edit,
|
|
70
|
+
async function publish(st, project, lang, edit, view) {
|
|
76
71
|
const pub = st.gitPublish;
|
|
77
72
|
const { host, account } = accountOf(st, pub);
|
|
78
|
-
const opts =
|
|
79
|
-
|
|
73
|
+
const opts = gitOpts(st, project, account);
|
|
74
|
+
const net = gitNetOpts(st, project, { host, account });
|
|
75
|
+
const lock = acquireGitLock(st, project);
|
|
76
|
+
if (!lock) return edit({ text: t('git.busy', lang), markup: { inline_keyboard: [backRow(lang)] } });
|
|
80
77
|
try {
|
|
81
78
|
await edit({ text: th('git.pb.working', lang) });
|
|
82
79
|
// сначала локальная часть: если публиковать нечего, репозиторий на сервере не создаётся
|
|
@@ -88,7 +85,7 @@ async function publish(st, project, lang, edit, h) {
|
|
|
88
85
|
// адрес из ответа сервиса уходит в настройки репозитория: чужой адрес (или не адрес вовсе) не принимаем
|
|
89
86
|
if (hostFor(created.url)?.id !== host.id) throw new HostError('http', `${host.label}: unexpected repository address`);
|
|
90
87
|
await setRemote(project, created.url, opts);
|
|
91
|
-
await pushRepo(project,
|
|
88
|
+
await pushRepo(project, net);
|
|
92
89
|
log('git: проект опубликован:', st.userId, project, '→', created.path);
|
|
93
90
|
st.gitPublish = null;
|
|
94
91
|
const note = [
|
|
@@ -96,21 +93,21 @@ async function publish(st, project, lang, edit, h) {
|
|
|
96
93
|
...(first.tracked.length ? [th('git.tracked', lang, { files: first.tracked.join(', ') })] : []),
|
|
97
94
|
...(first.ignoreWarning ? [th('git.ignoreLink', lang)] : []),
|
|
98
95
|
].map((s) => `\n${s}`).join('');
|
|
99
|
-
const v = await
|
|
96
|
+
const v = await view();
|
|
100
97
|
const open = created.web ? [[{ text: t('git.open', lang), url: created.web }]] : [];
|
|
101
98
|
return await edit({ text: `${th('git.pb.done', lang, { address: hCode(showRemote(created.url)) })}${note}\n\n${v.text}`, markup: { inline_keyboard: [...open, ...v.markup.inline_keyboard] } });
|
|
102
99
|
} catch (e) {
|
|
103
100
|
log('git: публикация:', e.message, '| пользователь', st.userId);
|
|
104
101
|
return await edit({ text: failText(e, lang, host), markup: { inline_keyboard: [backRow(lang)] } });
|
|
105
102
|
} finally {
|
|
106
|
-
st
|
|
103
|
+
releaseGitLock(st, lock);
|
|
107
104
|
}
|
|
108
105
|
}
|
|
109
106
|
|
|
110
107
|
/** Создаёт запрос на слияние текущей ветки в основную (или находит уже открытый) и даёт ссылку. */
|
|
111
|
-
async function mergeRequest(st, project, title, lang, edit
|
|
108
|
+
async function mergeRequest(st, project, title, lang, edit) {
|
|
112
109
|
const mr = st.gitMr;
|
|
113
|
-
const repo = await
|
|
110
|
+
const repo = await repoOf(st, project);
|
|
114
111
|
if (!mr || !repo?.account) return edit({ text: th('git.diff.gone', lang), markup: { inline_keyboard: [backRow(lang)] } });
|
|
115
112
|
st.gitMr = null;
|
|
116
113
|
try {
|
|
@@ -124,9 +121,9 @@ async function mergeRequest(st, project, title, lang, edit, h) {
|
|
|
124
121
|
}
|
|
125
122
|
}
|
|
126
123
|
|
|
127
|
-
/** Кнопки «Опубликовать проект» (pb…) и «Запрос на слияние» (mr…).
|
|
124
|
+
/** Кнопки «Опубликовать проект» (pb…) и «Запрос на слияние» (mr…). */
|
|
128
125
|
export async function onPublishCallback(st, cb, h) {
|
|
129
|
-
const { action, arg, lang, ack, edit, project } = h;
|
|
126
|
+
const { action, arg, lang, ack, edit, project, view } = h;
|
|
130
127
|
if (!project) return ack(t('state.projectGone', lang));
|
|
131
128
|
if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
|
|
132
129
|
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
@@ -134,14 +131,14 @@ export async function onPublishCallback(st, cb, h) {
|
|
|
134
131
|
try {
|
|
135
132
|
// ---- запрос на слияние ----
|
|
136
133
|
if (action === 'mr') {
|
|
137
|
-
const repo = await
|
|
134
|
+
const repo = await repoOf(st, project);
|
|
138
135
|
if (!repo?.account || !repo.state.branch) return ack(t('proj.stale', lang));
|
|
139
136
|
await ack();
|
|
140
137
|
const info = await repoInfo(repo.host, repo.account.token, repo.state.remote);
|
|
141
138
|
const s = repo.state;
|
|
142
139
|
if (s.branch === info.defaultBranch) return edit({ text: th('git.mr.onDefault', lang, { branch: hCode(s.branch) }), markup: { inline_keyboard: [[{ text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }], backRow(lang)] } });
|
|
143
140
|
if (!s.upstream || s.ahead) return edit({ text: th('git.mr.pushFirst', lang, { branch: hCode(s.branch) }), markup: { inline_keyboard: [[{ text: t('git.push', lang), callback_data: 'gt:push' }], backRow(lang)] } });
|
|
144
|
-
const suggested = (await lastSubject(project,
|
|
141
|
+
const suggested = (await lastSubject(project, gitOpts(st, project, repo.account))) || s.branch;
|
|
145
142
|
st.gitMr = { branch: s.branch, target: info.defaultBranch, suggested };
|
|
146
143
|
st.pendingInput = { kind: 'gitMrTitle', at: Date.now() };
|
|
147
144
|
const markup = { inline_keyboard: [[{ text: [...`«${suggested}»`].slice(0, 60).join(''), callback_data: 'gt:mrgo' }], [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] };
|
|
@@ -150,10 +147,10 @@ export async function onPublishCallback(st, cb, h) {
|
|
|
150
147
|
if (action === 'mrgo') {
|
|
151
148
|
st.pendingInput = null;
|
|
152
149
|
await ack();
|
|
153
|
-
return await mergeRequest(st, project, st.gitMr?.suggested ?? '', lang, edit
|
|
150
|
+
return await mergeRequest(st, project, st.gitMr?.suggested ?? '', lang, edit);
|
|
154
151
|
}
|
|
155
152
|
// ---- публикация ----
|
|
156
|
-
if (!(await canPublish(st, project
|
|
153
|
+
if (!(await canPublish(st, project))) return ack(t('proj.stale', lang));
|
|
157
154
|
const accounts = accountsOf(st.userId);
|
|
158
155
|
if (action === 'pb') {
|
|
159
156
|
await ack();
|
|
@@ -200,7 +197,7 @@ export async function onPublishCallback(st, cb, h) {
|
|
|
200
197
|
if (action === 'pbgo') {
|
|
201
198
|
if (!pub.slug) return ack(t('git.pb.nameBad', lang));
|
|
202
199
|
await ack();
|
|
203
|
-
return await publish(st, project, lang, edit,
|
|
200
|
+
return await publish(st, project, lang, edit, view);
|
|
204
201
|
}
|
|
205
202
|
return ack(t('proj.stale', lang));
|
|
206
203
|
} catch (e) {
|
|
@@ -212,7 +209,7 @@ export async function onPublishCallback(st, cb, h) {
|
|
|
212
209
|
|
|
213
210
|
/**
|
|
214
211
|
* Текст пользователя для публикации и запроса на слияние: строка поиска группы, название репозитория, заголовок запроса.
|
|
215
|
-
* @param {object} h {wait, now, lang, project, send,
|
|
212
|
+
* @param {object} h {wait, now, lang, project, send, view}
|
|
216
213
|
* @returns {Promise<boolean>} true — текст обработан здесь
|
|
217
214
|
*/
|
|
218
215
|
export async function onPublishInput(st, text, h) {
|
|
@@ -222,7 +219,7 @@ export async function onPublishInput(st, text, h) {
|
|
|
222
219
|
if (wait.kind === 'gitMrTitle') {
|
|
223
220
|
if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
|
|
224
221
|
const title = [...text.trim().split(/\r?\n/)[0]].slice(0, 200).join('') || st.gitMr?.suggested || '';
|
|
225
|
-
await mergeRequest(st, project, title, lang, send
|
|
222
|
+
await mergeRequest(st, project, title, lang, send);
|
|
226
223
|
return true;
|
|
227
224
|
}
|
|
228
225
|
const pub = st.gitPublish;
|
package/src/gitRepoUi.mjs
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
// Экраны /git «Изменения» и «Ветки»: что изменено в проекте (список файлов, изменения по файлу, неотправленные и
|
|
2
2
|
// ожидающие на сервере коммиты) и ветки (список, переключение, новая ветка). Смотреть может любой пользователь —
|
|
3
3
|
// без агента и без запросов к модели; переключать и создавать ветки — тот, кому разрешено менять файлы проекта.
|
|
4
|
-
//
|
|
4
|
+
// Общие помощники (проект, репозиторий, запуск git) живут в gitCtx.mjs.
|
|
5
5
|
import { basename } from 'node:path';
|
|
6
6
|
import { log, say } from './ctx.mjs';
|
|
7
7
|
import { isSecretName, safeFileName } from './files.mjs';
|
|
8
8
|
import { canManageFiles } from './filesUi.mjs';
|
|
9
|
-
import {
|
|
9
|
+
import { fetchRepo } from './git.mjs';
|
|
10
|
+
import { acquireGitLock, failText, gitNetOpts, gitOpts, releaseGitLock, repoOf } from './gitCtx.mjs';
|
|
10
11
|
import { recall, remember } from './gitKeys.mjs';
|
|
11
12
|
import { branchName, changedFiles, commitList, createBranch, discardFiles, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
|
|
12
|
-
import {
|
|
13
|
+
import { t } from './i18n.mjs';
|
|
13
14
|
import { endAgent, userPath } from './state.mjs';
|
|
14
15
|
import { escHtml, sendBuffer } from './telegram.mjs';
|
|
15
16
|
import { hCode, th } from './ui.mjs';
|
|
@@ -23,7 +24,6 @@ export const DIFF_INLINE_MAX = 3200;
|
|
|
23
24
|
const DIFF_FILE_MAX = 1024 * 1024;
|
|
24
25
|
const MARK = { new: '🆕', modified: '✏️', deleted: '🗑', renamed: '🔀', conflict: '⚠️' };
|
|
25
26
|
|
|
26
|
-
const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError ? e.message : errText(e, lang) });
|
|
27
27
|
/** Длинный путь на кнопке показывается хвостом: имя файла важнее начала пути. */
|
|
28
28
|
const tail = (s, n) => ([...s].length > n ? `…${[...s].slice(-(n - 1)).join('')}` : s);
|
|
29
29
|
const counts = (f) => [f.added ? `+${f.added}` : '', f.deleted ? `−${f.deleted}` : ''].filter(Boolean).join(' ');
|
|
@@ -60,9 +60,20 @@ async function changesView(st, project, repo, opts, page, lang) {
|
|
|
60
60
|
const isSecretFile = (f) => isSecretName(`/${f.path}`);
|
|
61
61
|
|
|
62
62
|
/** Экран «Ветки»: текущая отмечена, ветки только с сервера помечены облаком; нажатие переключает. */
|
|
63
|
-
async function branchesView(st, project, repo, opts, page, lang, { sync = false } = {}) {
|
|
63
|
+
async function branchesView(st, project, repo, opts, net, page, lang, { sync = false } = {}) {
|
|
64
64
|
// ветки сервера узнаём сверкой с ним — нужен подключённый аккаунт; не вышло — показываем то, что известно
|
|
65
|
-
if (sync && repo.account && !st.busy && !st.gitBusy)
|
|
65
|
+
if (sync && repo.account && net && !st.busy && !st.gitBusy) {
|
|
66
|
+
const lock = acquireGitLock(st, project);
|
|
67
|
+
if (lock) {
|
|
68
|
+
try {
|
|
69
|
+
await fetchRepo(project, net);
|
|
70
|
+
} catch (e) {
|
|
71
|
+
log('git: сверка веток:', e.message, '| пользователь', st.userId);
|
|
72
|
+
} finally {
|
|
73
|
+
releaseGitLock(st, lock);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
66
77
|
const { current, branches } = await listBranches(project, opts);
|
|
67
78
|
const pages = Math.max(1, Math.ceil(branches.length / PAGE));
|
|
68
79
|
page = Math.min(Math.max(page, 0), pages - 1);
|
|
@@ -98,15 +109,19 @@ async function commitsView(project, opts, which, lang) {
|
|
|
98
109
|
|
|
99
110
|
/**
|
|
100
111
|
* Кнопки экранов «Изменения» и «Ветки».
|
|
101
|
-
* @param {object} h
|
|
112
|
+
* @param {object} h {action, arg, lang, ack, edit, project}
|
|
102
113
|
*/
|
|
103
114
|
export async function onRepoCallback(st, cb, h) {
|
|
104
115
|
const { action, arg, lang, ack, edit, project } = h;
|
|
105
116
|
if (!project) return ack(t('state.projectGone', lang));
|
|
117
|
+
const mutating = ['dX', 'dA', 'bs'].includes(action);
|
|
118
|
+
const lock = mutating ? acquireGitLock(st, project) : null;
|
|
119
|
+
if (mutating && !lock) return ack(t('git.busy', lang));
|
|
106
120
|
try {
|
|
107
|
-
const repo = await
|
|
121
|
+
const repo = await repoOf(st, project);
|
|
108
122
|
if (!repo) return (await ack(), edit({ text: th('git.noRepo', lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } }));
|
|
109
|
-
const opts =
|
|
123
|
+
const opts = gitOpts(st, project, repo.account);
|
|
124
|
+
const net = repo.account ? gitNetOpts(st, project, repo) : null;
|
|
110
125
|
if (action === 'ch') return (await ack(), edit(await changesView(st, project, repo, opts, Number(arg) || 0, lang)));
|
|
111
126
|
if (action === 'cm') return (await ack(), edit(await commitsView(project, opts, arg, lang)));
|
|
112
127
|
if (action === 'cf') {
|
|
@@ -117,10 +132,10 @@ export async function onRepoCallback(st, cb, h) {
|
|
|
117
132
|
await ack();
|
|
118
133
|
return await showDiff(st, project, file, arg, opts, lang, edit);
|
|
119
134
|
}
|
|
120
|
-
if (action === 'br') return (await ack(), edit(await branchesView(st, project, repo, opts, Number(arg) || 0, lang, { sync: true })));
|
|
135
|
+
if (action === 'br') return (await ack(), edit(await branchesView(st, project, repo, opts, net, Number(arg) || 0, lang, { sync: true })));
|
|
121
136
|
// ---- переключение и создание ветки меняют проект ----
|
|
122
137
|
if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
|
|
123
|
-
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
138
|
+
if (!mutating && st.gitBusy) return ack(t('git.busy', lang));
|
|
124
139
|
if (st.busy) return ack(t('git.agentBusy', lang));
|
|
125
140
|
if (action === 'bn') {
|
|
126
141
|
await ack();
|
|
@@ -130,16 +145,9 @@ export async function onRepoCallback(st, cb, h) {
|
|
|
130
145
|
// ---- отмена изменений: необратимо, поэтому сначала вопрос, а список файлов берётся заново ----
|
|
131
146
|
if (['dx', 'dX', 'da', 'dA'].includes(action)) {
|
|
132
147
|
const fresh = (await changedFiles(project, opts)).files;
|
|
133
|
-
const run = async (list) =>
|
|
134
|
-
st.gitBusy = true;
|
|
135
|
-
try {
|
|
136
|
-
return await discardFiles(project, list, opts);
|
|
137
|
-
} finally {
|
|
138
|
-
st.gitBusy = false;
|
|
139
|
-
}
|
|
140
|
-
};
|
|
148
|
+
const run = async (list) => discardFiles(project, list, opts);
|
|
141
149
|
const show = async (note) => {
|
|
142
|
-
const v = await changesView(st, project, await
|
|
150
|
+
const v = await changesView(st, project, await repoOf(st, project), opts, 0, lang);
|
|
143
151
|
return edit({ text: `${note}\n\n${v.text}`, markup: v.markup });
|
|
144
152
|
};
|
|
145
153
|
if (action === 'dx' || action === 'dX') {
|
|
@@ -180,51 +188,53 @@ export async function onRepoCallback(st, cb, h) {
|
|
|
180
188
|
return edit({ text: th('git.br.dirty', lang, { n: repo.state.changed, name: hCode(branch.name) }), markup });
|
|
181
189
|
}
|
|
182
190
|
await ack();
|
|
183
|
-
|
|
184
|
-
try {
|
|
185
|
-
await switchBranch(project, branch, opts);
|
|
186
|
-
} finally {
|
|
187
|
-
st.gitBusy = false;
|
|
188
|
-
}
|
|
191
|
+
await switchBranch(project, branch, net ?? opts);
|
|
189
192
|
// файлы проекта сменились целиком: сессия агента с прежним представлением о них продолжаться не должна
|
|
190
193
|
endAgent(st, 'branch');
|
|
191
194
|
log('git: ветка переключена:', st.userId, project, '→', branch.name);
|
|
192
|
-
const v = await branchesView(st, project, repo, opts, 0, lang);
|
|
195
|
+
const v = await branchesView(st, project, repo, opts, net, 0, lang);
|
|
193
196
|
return edit({ text: `${th('git.br.switched', lang, { name: hCode(branch.name) })}\n\n${v.text}`, markup: v.markup });
|
|
194
197
|
} catch (e) {
|
|
195
198
|
log(`git: ${action}:`, e.message, '| пользователь', st.userId);
|
|
196
199
|
await ack();
|
|
197
200
|
return edit({ text: failText(e, lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } });
|
|
201
|
+
} finally {
|
|
202
|
+
releaseGitLock(st, lock);
|
|
198
203
|
}
|
|
199
204
|
}
|
|
200
205
|
|
|
201
206
|
/**
|
|
202
207
|
* Название новой ветки от пользователя (после кнопки «Новая ветка»): создаёт ветку от текущей и переключается на неё.
|
|
203
208
|
* Несохранённые изменения остаются в рабочей папке, сессия агента продолжается — файлы те же.
|
|
204
|
-
* @param {object} h {wait, now, lang, project
|
|
209
|
+
* @param {object} h {wait, now, lang, project}
|
|
205
210
|
* @returns {Promise<boolean>} true — текст обработан здесь
|
|
206
211
|
*/
|
|
207
212
|
export async function onBranchInput(st, text, h) {
|
|
208
|
-
const { lang, project } = h;
|
|
213
|
+
const { wait, now, lang, project } = h;
|
|
209
214
|
const html = { parse_mode: 'HTML' };
|
|
210
215
|
if (!project || !canManageFiles(st.userId)) return false;
|
|
211
216
|
if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
|
|
217
|
+
const lock = acquireGitLock(st, project);
|
|
218
|
+
if (!lock) return (await say(st.to, t('git.busy', lang), html), true);
|
|
212
219
|
try {
|
|
213
|
-
const repo = await
|
|
220
|
+
const repo = await repoOf(st, project);
|
|
214
221
|
if (!repo) return (await say(st.to, th('git.noRepo', lang), html), true);
|
|
215
|
-
const opts =
|
|
222
|
+
const opts = gitOpts(st, project, repo.account);
|
|
223
|
+
const net = repo.account ? gitNetOpts(st, project, repo) : null;
|
|
216
224
|
const name = await branchName(text, { cwd: project, ...opts });
|
|
217
225
|
if (!name) {
|
|
218
|
-
st.pendingInput = { ...
|
|
226
|
+
st.pendingInput = { ...wait, at: now }; // название не подошло — ждём другое
|
|
219
227
|
return (await say(st.to, t('git.br.badName', lang), { reply_markup: { inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] } }), true);
|
|
220
228
|
}
|
|
221
|
-
await createBranch(project, name, opts);
|
|
229
|
+
await createBranch(project, name, net ?? opts);
|
|
222
230
|
log('git: ветка создана:', st.userId, project, name);
|
|
223
231
|
const markup = { inline_keyboard: [[{ text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }, { text: t('btn.back', lang), callback_data: 'gt:v' }]] };
|
|
224
232
|
await say(st.to, th('git.br.created', lang, { name: hCode(name) }), { ...html, reply_markup: markup });
|
|
225
233
|
} catch (e) {
|
|
226
234
|
log('git: новая ветка:', e.message, '| пользователь', st.userId);
|
|
227
235
|
await say(st.to, failText(e, lang), html);
|
|
236
|
+
} finally {
|
|
237
|
+
releaseGitLock(st, lock);
|
|
228
238
|
}
|
|
229
239
|
return true;
|
|
230
240
|
}
|
package/src/gitUi.mjs
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
// Команда /git: аккаунты GitHub и GitLab пользователя (вход по токену доступа), клонирование репозитория кнопками,
|
|
2
2
|
// состояние репозитория проекта, «Получить», «Отправить», «Сохранить и отправить».
|
|
3
3
|
// Токен вводится сообщением, которое не передаётся агенту и удаляется из чата; команды git с входом выполняет бот.
|
|
4
|
+
import { lstatSync, realpathSync, rmSync } from 'node:fs';
|
|
4
5
|
import { join } from 'node:path';
|
|
5
6
|
import { db, langOf, log, say } from './ctx.mjs';
|
|
6
7
|
import { canManageFiles } from './filesUi.mjs';
|
|
7
|
-
import {
|
|
8
|
+
import { cloneRepo, commitAll, fetchRepo, gitAvailable, pullRepo, pushRepo, repoState, unpushedSecrets } from './git.mjs';
|
|
8
9
|
import { DeviceError, deviceLogin, startDeviceLogin, waitDeviceLogin } from './gitDevice.mjs';
|
|
9
10
|
import { recall, remember } from './gitKeys.mjs';
|
|
10
|
-
import {
|
|
11
|
+
import { acquireGitLock, failText, gitNetOpts, gitOpts, projectOf, releaseGitLock, repoOf } from './gitCtx.mjs';
|
|
12
|
+
import { accountsOf, addCustomHost, findHost, hostFor, hosts as allHosts, refreshAccounts, removeCustomHost, renameCustomHost } from './gitAccess.mjs';
|
|
11
13
|
import { PUBLISH_ACTIONS, PUBLISH_INPUTS, canPublish, onPublishCallback, onPublishInput } from './gitPublishUi.mjs';
|
|
12
14
|
import { REPO_ACTIONS, onBranchInput, onRepoCallback } from './gitRepoUi.mjs';
|
|
13
|
-
import { HostError,
|
|
14
|
-
import { LOCALES,
|
|
15
|
-
import {
|
|
15
|
+
import { HostError, customHost, fetchProfile, listRepos, missingScopes, probeHost, repoFolder, showRemote } from './gitHosts.mjs';
|
|
16
|
+
import { LOCALES, t } from './i18n.mjs';
|
|
17
|
+
import { folderName, insideRoot, isPersonalRoot, navStart } from './projects.mjs';
|
|
16
18
|
import { canCreateProject, selectProject } from './projectsUi.mjs';
|
|
17
|
-
import {
|
|
18
|
-
import { isAdmin, rootOf, sandboxed, userPath } from './state.mjs';
|
|
19
|
+
import { isAdmin, rootOf, userPath } from './state.mjs';
|
|
19
20
|
import { dest, tg } from './telegram.mjs';
|
|
20
21
|
import { hCode, th } from './ui.mjs';
|
|
21
22
|
|
|
@@ -26,32 +27,6 @@ export const GIT_WAIT_MS = 10 * 60_000;
|
|
|
26
27
|
const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] });
|
|
27
28
|
const dateOf = (iso, lang) => (iso ? new Date(iso).toLocaleDateString(LOCALES[lang] ?? LOCALES.en, { day: '2-digit', month: '2-digit', year: 'numeric' }) : '—');
|
|
28
29
|
|
|
29
|
-
/** Папка проекта диалога, если она доступна, иначе null. */
|
|
30
|
-
const projectOf = (st) => insideRoot(st.project, rootOf(st.userId));
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Как запускать git для этого пользователя: окружение (автор коммитов, вход в сервис), песочница сотрудника
|
|
34
|
-
* (если она включена) и строки, которые нужно вычистить из сообщений об ошибках.
|
|
35
|
-
*/
|
|
36
|
-
function gitOpts(st, cwd, { host = null, account = null } = {}) {
|
|
37
|
-
const who = account ?? accountsOf(st.userId)[0]?.account ?? null;
|
|
38
|
-
const auth = host && account ? authConfig(host, account.token) : [];
|
|
39
|
-
const root = rootOf(st.userId);
|
|
40
|
-
const wrap = sandboxed(st.userId)
|
|
41
|
-
? agentSandbox({ userId: st.userId, cwd, root, command: gitCommand(), protect: isPersonalRoot(root) ? [ROOT] : [] })
|
|
42
|
-
: null;
|
|
43
|
-
return { env: gitEnv({ identity: identityOf(who), auth }), wrap, hide: account ? [account.token, auth[0]?.[1]?.split(' ').pop()] : [] };
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** Репозиторий проекта и его сервис: {state, host, account} или null, если проект не репозиторий (или репозиторий выше корня пользователя). */
|
|
47
|
-
async function repoOf(st, project) {
|
|
48
|
-
const state = await repoState(project, gitOpts(st, project));
|
|
49
|
-
if (!state || !insideRoot(state.top, rootOf(st.userId))) return null;
|
|
50
|
-
const host = hostFor(state.remote);
|
|
51
|
-
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
52
|
-
return { state, host, account };
|
|
53
|
-
}
|
|
54
|
-
|
|
55
30
|
/**
|
|
56
31
|
* Экран /git: состояние репозитория проекта, аккаунты, кнопки. Текст — HTML.
|
|
57
32
|
* sync — сначала свериться с сервером (git fetch), чтобы «новых на сервере» было настоящим числом: при открытии экрана
|
|
@@ -67,12 +42,17 @@ export async function gitView(st, lang = langOf(st.userId), { sync = false } = {
|
|
|
67
42
|
let repo = await load();
|
|
68
43
|
let syncError = null;
|
|
69
44
|
if (sync && repo?.account && !st.busy && !st.gitBusy) {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
45
|
+
const lock = acquireGitLock(st, project);
|
|
46
|
+
if (lock) {
|
|
47
|
+
try {
|
|
48
|
+
await fetchRepo(project, gitNetOpts(st, project, repo));
|
|
49
|
+
repo = await load();
|
|
50
|
+
} catch (e) {
|
|
51
|
+
log('git: сверка с сервером:', e.message, '| пользователь', st.userId);
|
|
52
|
+
syncError = e.message;
|
|
53
|
+
} finally {
|
|
54
|
+
releaseGitLock(st, lock);
|
|
55
|
+
}
|
|
76
56
|
}
|
|
77
57
|
}
|
|
78
58
|
if (repo) {
|
|
@@ -91,7 +71,7 @@ export async function gitView(st, lang = langOf(st.userId), { sync = false } = {
|
|
|
91
71
|
rows.push([{ text: t('git.changesBtn', lang), callback_data: 'gt:ch:0' }, { text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }]);
|
|
92
72
|
} else lines.push(th('git.noRepo', lang));
|
|
93
73
|
// папку, которая ещё не связана с сервером, можно опубликовать: бот создаст для неё репозиторий
|
|
94
|
-
const publishable = project && !repo?.state.remote ? await canPublish(st, project
|
|
74
|
+
const publishable = project && !repo?.state.remote ? await canPublish(st, project).catch(() => false) : false;
|
|
95
75
|
if (publishable) rows.push([{ text: t('git.pbBtn', lang), callback_data: 'gt:pb' }]);
|
|
96
76
|
lines.push(accounts.length ? [t('git.accounts', lang), ...accounts.map(({ host, account }) => th('git.accLine', lang, { host: host.label, login: account.login }))].join('\n') : th('git.noAccounts', lang));
|
|
97
77
|
if (accounts.length && canCreateProject(st.userId)) rows.push([{ text: t('git.clone', lang), callback_data: 'gt:cl' }]);
|
|
@@ -153,9 +133,6 @@ export async function offerGitActions(st, actions) {
|
|
|
153
133
|
return say(st.to, t(actions.length > 1 ? 'git.offer.both' : `git.offer.${actions[0]}`, lang), { reply_markup: { inline_keyboard: [row] } });
|
|
154
134
|
}
|
|
155
135
|
|
|
156
|
-
/** Текст ошибки git или сервиса для пользователя. */
|
|
157
|
-
const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
|
|
158
|
-
|
|
159
136
|
/** Куда клонировать: личное пространство сотрудника, иначе — папка рядом с текущим проектом (или корень). */
|
|
160
137
|
function cloneBase(st) {
|
|
161
138
|
const root = rootOf(st.userId);
|
|
@@ -178,6 +155,17 @@ async function reposView(st, host, account, { page = 0, search = '' } = {}, lang
|
|
|
178
155
|
return { text: items.length ? head : `${head}\n\n<i>${th('git.reposNone', lang)}</i>`, markup: { inline_keyboard: rows } };
|
|
179
156
|
}
|
|
180
157
|
|
|
158
|
+
export function cleanFailedClone(st, target, base) {
|
|
159
|
+
try {
|
|
160
|
+
const info = lstatSync(target);
|
|
161
|
+
const real = realpathSync.native(target);
|
|
162
|
+
if (!info.isDirectory() || info.isSymbolicLink() || !insideRoot(real, base)) return;
|
|
163
|
+
rmSync(real, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
|
164
|
+
} catch (e) {
|
|
165
|
+
log('git: папка неудачного клона не убрана:', e.message, '| пользователь', st.userId);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
181
169
|
/** Клонирует выбранный репозиторий в пространство пользователя и выбирает его проектом. */
|
|
182
170
|
async function cloneChosen(st, repo, host, account, lang, edit) {
|
|
183
171
|
const base = cloneBase(st);
|
|
@@ -187,9 +175,10 @@ async function cloneChosen(st, repo, host, account, lang, edit) {
|
|
|
187
175
|
if (insideRoot(target, rootOf(st.userId))) return edit({ text: th('git.cloneExists', lang, { name: hCode(name), dir: hCode(userPath(st.userId, base, lang)) }) });
|
|
188
176
|
await edit({ text: th('git.cloning', lang, { name: hCode(repo.name) }) });
|
|
189
177
|
try {
|
|
190
|
-
await cloneRepo(repo.url, name, { cwd: base, ...
|
|
178
|
+
await cloneRepo(repo.url, name, { cwd: base, ...gitNetOpts(st, base, { host, account }) });
|
|
191
179
|
} catch (e) {
|
|
192
180
|
log('git: клонирование:', e.message, '| пользователь', st.userId);
|
|
181
|
+
cleanFailedClone(st, target, base);
|
|
193
182
|
return edit({ text: failText(e, lang) });
|
|
194
183
|
}
|
|
195
184
|
const dir = insideRoot(target, rootOf(st.userId));
|
|
@@ -205,18 +194,20 @@ async function cloneChosen(st, repo, host, account, lang, edit) {
|
|
|
205
194
|
*/
|
|
206
195
|
async function repoAction(st, action, lang, edit, { message = null } = {}) {
|
|
207
196
|
const project = projectOf(st);
|
|
208
|
-
const
|
|
209
|
-
if (!
|
|
210
|
-
const opts = gitOpts(st, project, repo);
|
|
197
|
+
const lock = acquireGitLock(st, project ?? st.userId);
|
|
198
|
+
if (!lock) return edit({ text: t('git.busy', lang) });
|
|
211
199
|
const done = async (text) => {
|
|
212
200
|
const v = await gitView(st, lang);
|
|
213
201
|
return edit({ text: `${text}\n\n${v.text}`, markup: v.markup });
|
|
214
202
|
};
|
|
215
|
-
st.gitBusy = true;
|
|
216
203
|
try {
|
|
204
|
+
const repo = project ? await repoOf(st, project) : null;
|
|
205
|
+
if (!repo?.account) return edit(await gitView(st, lang));
|
|
206
|
+
const opts = gitOpts(st, project, repo.account);
|
|
207
|
+
const net = gitNetOpts(st, project, repo);
|
|
217
208
|
if (action === 'pull') {
|
|
218
209
|
await edit({ text: th('git.pulling', lang) });
|
|
219
|
-
const result = await pullRepo(project,
|
|
210
|
+
const result = await pullRepo(project, net);
|
|
220
211
|
log('git: получено:', st.userId, project, '|', result);
|
|
221
212
|
return await done(th(`git.pull.${result}`, lang));
|
|
222
213
|
}
|
|
@@ -241,7 +232,7 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
|
|
|
241
232
|
const state = await repoState(project, opts);
|
|
242
233
|
if (state?.upstream && !state.ahead) return await done(th('git.nothingToPush', lang) + note);
|
|
243
234
|
try {
|
|
244
|
-
await pushRepo(project,
|
|
235
|
+
await pushRepo(project, net);
|
|
245
236
|
} catch (e) {
|
|
246
237
|
if (/rejected|non-fast-forward|fetch first/i.test(`${e.message} ${e.stderr ?? ''}`)) return await done(th('git.pushRejected', lang) + note);
|
|
247
238
|
throw e;
|
|
@@ -252,7 +243,7 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
|
|
|
252
243
|
log(`git: ${action}:`, e.message, '| пользователь', st.userId);
|
|
253
244
|
return await done(failText(e, lang));
|
|
254
245
|
} finally {
|
|
255
|
-
st
|
|
246
|
+
releaseGitLock(st, lock);
|
|
256
247
|
}
|
|
257
248
|
}
|
|
258
249
|
|
|
@@ -362,9 +353,9 @@ export async function onGitCallback(st, cb) {
|
|
|
362
353
|
return edit(hostsView(lang, th('git.hosts.deleted', lang, { label: own.label, n: n ?? 0 })));
|
|
363
354
|
}
|
|
364
355
|
// экраны «Изменения» и «Ветки» — gitRepoUi
|
|
365
|
-
if (REPO_ACTIONS.includes(action)) return onRepoCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st)
|
|
356
|
+
if (REPO_ACTIONS.includes(action)) return onRepoCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st) });
|
|
366
357
|
// «Опубликовать проект» и «Запрос на слияние» — gitPublishUi
|
|
367
|
-
if (PUBLISH_ACTIONS.includes(action)) return onPublishCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st),
|
|
358
|
+
if (PUBLISH_ACTIONS.includes(action)) return onPublishCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), view: () => gitView(st, lang) });
|
|
368
359
|
const host = findHost(arg);
|
|
369
360
|
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
370
361
|
try {
|
|
@@ -425,13 +416,13 @@ export async function onGitCallback(st, cb) {
|
|
|
425
416
|
const acc = h ? db.getGitAccount(st.userId, h.id) : null;
|
|
426
417
|
if (!repo || !acc || !canCreateProject(st.userId)) return ack(t('proj.stale', lang));
|
|
427
418
|
if (hostFor(repo.url)?.id !== h.id) return ack(t('proj.stale', lang)); // адрес обязан принадлежать своему сервису
|
|
428
|
-
|
|
419
|
+
const lock = acquireGitLock(st, cloneBase(st) ?? st.userId);
|
|
420
|
+
if (!lock) return ack(t('git.busy', lang));
|
|
429
421
|
await ack();
|
|
430
|
-
st.gitBusy = true;
|
|
431
422
|
try {
|
|
432
423
|
return await cloneChosen(st, repo, h, acc, lang, edit);
|
|
433
424
|
} finally {
|
|
434
|
-
st
|
|
425
|
+
releaseGitLock(st, lock);
|
|
435
426
|
}
|
|
436
427
|
}
|
|
437
428
|
// ---- репозиторий проекта ----
|
|
@@ -499,8 +490,8 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
|
|
|
499
490
|
|
|
500
491
|
st.pendingInput = null;
|
|
501
492
|
if (expired) return false; // адрес сервера, строка поиска и описание изменений — не секреты: позже это обычный запрос агенту
|
|
502
|
-
if (wait.kind === 'gitBranch') return onBranchInput(st, text, { wait, now, lang, project: projectOf(st)
|
|
503
|
-
if (PUBLISH_INPUTS.includes(wait.kind)) return onPublishInput(st, text, { wait, now, lang, send, project: projectOf(st),
|
|
493
|
+
if (wait.kind === 'gitBranch') return onBranchInput(st, text, { wait, now, lang, project: projectOf(st) });
|
|
494
|
+
if (PUBLISH_INPUTS.includes(wait.kind)) return onPublishInput(st, text, { wait, now, lang, send, project: projectOf(st), view: () => gitView(st, lang) });
|
|
504
495
|
// свои серверы: адрес нового сервера или новое название — только от администратора
|
|
505
496
|
if (wait.kind === 'gitHostUrl' || wait.kind === 'gitHostName') {
|
|
506
497
|
if (!isAdmin(st.userId)) return false;
|
package/src/i18n.mjs
CHANGED
|
@@ -324,6 +324,7 @@ const M = {
|
|
|
324
324
|
'git.cloneExists': { en: "⚠️ The folder {name} already exists in {dir}. Choose it in /project or rename it.", ru: "⚠️ Папка {name} уже есть в {dir}. Выберите её в /project или переименуйте.", uk: "⚠️ Папка {name} уже є в {dir}. Оберіть її в /project або перейменуйте." },
|
|
325
325
|
'git.cloneBadName': { en: "⚠️ This repository cannot be cloned here: its name is not suitable for a folder.", ru: "⚠️ Этот репозиторий сюда клонировать нельзя: его название не подходит для папки.", uk: "⚠️ Цей репозиторій сюди клонувати не можна: його назва не підходить для папки." },
|
|
326
326
|
'git.opFail': { en: "⚠️ Git: {msg}", ru: "⚠️ Git: {msg}", uk: "⚠️ Git: {msg}" },
|
|
327
|
+
'git.unsafeConfig': { en: "⚠️ Git: unsafe repository settings found: {keys}. Remove them and try again.", ru: "⚠️ Git: в настройках репозитория найдены небезопасные параметры: {keys}. Уберите их и повторите.", uk: "⚠️ Git: у налаштуваннях репозиторію знайдено небезпечні параметри: {keys}. Приберіть їх і повторіть." },
|
|
327
328
|
'git.busy': { en: "Wait for the current Git operation to finish.", ru: "Дождитесь завершения текущей операции Git.", uk: "Дочекайтеся завершення поточної операції Git." },
|
|
328
329
|
'git.agentBusy': { en: "First wait for the agent to answer or stop it: /stop", ru: "Сначала дождитесь ответа агента или остановите его: /stop", uk: "Спочатку дочекайтеся відповіді агента або зупиніть його: /stop" },
|
|
329
330
|
'git.pulling': { en: "⏳ Pulling changes…", ru: "⏳ Получаю изменения…", uk: "⏳ Отримую зміни…" },
|
package/src/state.mjs
CHANGED
|
@@ -124,6 +124,7 @@ export function getState(userId, chatId, threadId = null) {
|
|
|
124
124
|
agent: null,
|
|
125
125
|
engine: row?.engine ?? db.getSetting(`engine:${userId}`), // выбор пользователя; null — движок по умолчанию (DEFAULT_ENGINE)
|
|
126
126
|
busy: false,
|
|
127
|
+
gitBusy: false,
|
|
127
128
|
requestId: null,
|
|
128
129
|
onUpdate: null, // обработчик событий текущего запроса
|
|
129
130
|
perms: new Map(), // ожидающие запросы разрешений
|