acpgram 1.28.0 → 1.30.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 +14 -2
- package/package.json +1 -1
- package/src/bot.mjs +19 -2
- package/src/db.mjs +19 -4
- package/src/gitAccess.mjs +71 -2
- package/src/gitApi.mjs +79 -0
- package/src/gitDevice.mjs +121 -0
- package/src/gitHosts.mjs +29 -10
- package/src/gitInspect.mjs +45 -1
- package/src/gitKeys.mjs +20 -0
- package/src/gitMarks.mjs +42 -0
- package/src/gitPublishUi.mjs +239 -0
- package/src/gitRepoUi.mjs +62 -12
- package/src/gitUi.mjs +122 -22
- package/src/i18n.mjs +59 -1
- package/src/state.mjs +3 -1
- package/src/turn.mjs +7 -2
package/src/gitInspect.mjs
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
// Только чтение репозитория, кроме переключения и создания ветки. Команды запускает runGit (git.mjs) — с теми же
|
|
3
3
|
// безопасными настройками и, при включённой песочнице, внутри неё.
|
|
4
4
|
import { readFileSync, statSync } from 'node:fs';
|
|
5
|
-
import { join } from 'node:path';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
6
|
import { GitError, runGit } from './git.mjs';
|
|
7
|
+
import { samePath } from './projects.mjs';
|
|
7
8
|
|
|
8
9
|
/** Сколько изменённых файлов показывать (в большом несобранном проекте их могут быть тысячи). */
|
|
9
10
|
export const CHANGES_MAX = 300;
|
|
@@ -161,3 +162,46 @@ export async function switchBranch(cwd, branch, opts = {}) {
|
|
|
161
162
|
|
|
162
163
|
/** Создаёт ветку от текущего коммита и переключается на неё (несохранённые изменения остаются в рабочей папке). */
|
|
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;
|
package/src/gitMarks.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Метки агента [[git:push]] и [[git:pull]]: у агента нет входа на сервер Git, поэтому отправить или получить изменения
|
|
2
|
+
// он просит бота. Бот убирает метку из ответа и показывает под ним кнопку — без нажатия пользователя ничего не уходит.
|
|
3
|
+
import { splitCode } from './files.mjs';
|
|
4
|
+
|
|
5
|
+
const MARK = /\[\[git:(push|pull)\]\]/gi;
|
|
6
|
+
/** После вырезанной метки: пробелы в конце строки и двойные пробелы внутри неё. */
|
|
7
|
+
const tidy = (s) => s.replace(/[ \t]+(\r?\n)/g, '$1').replace(/([^ \n]) {2,}/g, '$1 ');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Достаёт из ответа агента метки [[git:push]] и [[git:pull]] (вне кода) и убирает их из текста.
|
|
11
|
+
* @returns {{text: string, actions: ('push'|'pull')[]}} actions — без повторов, в порядке появления
|
|
12
|
+
*/
|
|
13
|
+
export function extractGitMarks(text) {
|
|
14
|
+
const src = String(text ?? '');
|
|
15
|
+
if (!/\[\[git:/i.test(src)) return { text: src, actions: [] };
|
|
16
|
+
const actions = [];
|
|
17
|
+
const out = splitCode(src)
|
|
18
|
+
.map(({ code, s }) => {
|
|
19
|
+
if (code) return s;
|
|
20
|
+
return tidy(
|
|
21
|
+
s.replace(MARK, (_, a) => {
|
|
22
|
+
const action = a.toLowerCase();
|
|
23
|
+
if (!actions.includes(action)) actions.push(action);
|
|
24
|
+
return '';
|
|
25
|
+
}),
|
|
26
|
+
);
|
|
27
|
+
})
|
|
28
|
+
.join('');
|
|
29
|
+
return { text: out.replace(/\n{3,}/g, '\n\n').trim(), actions };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Для черновика: убирает целые метки и ещё не дописанную в конце («[[git:pu», «[[gi»). Код не трогает. */
|
|
33
|
+
export function stripGitMarks(text) {
|
|
34
|
+
const parts = splitCode(String(text ?? ''));
|
|
35
|
+
return parts
|
|
36
|
+
.map(({ code, s }, i) => {
|
|
37
|
+
if (code) return s;
|
|
38
|
+
const r = s.replace(MARK, '');
|
|
39
|
+
return i === parts.length - 1 ? r.replace(/\[\[g(?:i(?:t(?::(?:p(?:u(?:s(?:h(?:\]\]?)?)?|l(?:l(?:\]\]?)?)?)?)?)?)?)?)?$/i, '') : r;
|
|
40
|
+
})
|
|
41
|
+
.join('');
|
|
42
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// Экраны /git «Опубликовать проект» и «Запрос на слияние».
|
|
2
|
+
// Публикация: папка, которая ещё не связана с сервером, становится репозиторием — пользователь выбирает сервис, место
|
|
3
|
+
// (личное пространство, группа или организация), видимость и название; бот создаёт репозиторий, делает первый коммит
|
|
4
|
+
// (без файлов с секретами) и отправляет. Запрос на слияние: из текущей ветки в основную ветку репозитория.
|
|
5
|
+
// Вызывается из gitUi.mjs, который передаёт общие помощники (h).
|
|
6
|
+
import { basename } from 'node:path';
|
|
7
|
+
import { db, log, say } from './ctx.mjs';
|
|
8
|
+
import { canManageFiles } from './filesUi.mjs';
|
|
9
|
+
import { GitError, commitAll, pushRepo, repoState } from './git.mjs';
|
|
10
|
+
import { accountsOf, findHost } from './gitAccess.mjs';
|
|
11
|
+
import { recall, remember } from './gitKeys.mjs';
|
|
12
|
+
import { createRepo, listNamespaces, openMergeRequest, repoInfo, repoSlug, visibilities } from './gitApi.mjs';
|
|
13
|
+
import { HostError, showRemote } from './gitHosts.mjs';
|
|
14
|
+
import { ensureRepo, hasCommits, isRepoRoot, lastSubject, setRemote } from './gitInspect.mjs';
|
|
15
|
+
import { errText, t } from './i18n.mjs';
|
|
16
|
+
import { userPath } from './state.mjs';
|
|
17
|
+
import { hCode, th } from './ui.mjs';
|
|
18
|
+
|
|
19
|
+
/** Действия кнопок этого модуля (gt:<действие>:<аргумент>). */
|
|
20
|
+
export const PUBLISH_ACTIONS = ['pb', 'pbh', 'pbn', 'pbs', 'pbv', 'pbname', 'pbgo', 'mr', 'mrgo'];
|
|
21
|
+
/** Ожидания текста, которые обрабатывает этот модуль. */
|
|
22
|
+
export const PUBLISH_INPUTS = ['gitNsSearch', 'gitRepoName', 'gitMrTitle'];
|
|
23
|
+
|
|
24
|
+
const HTML = { parse_mode: 'HTML', link_preview_options: { is_disabled: true } };
|
|
25
|
+
const NS_MAX = 30;
|
|
26
|
+
const VIS_MARK = { private: '🔒', internal: '🏢', public: '🌍' };
|
|
27
|
+
const backRow = (lang) => [{ text: t('btn.back', lang), callback_data: 'gt:v' }];
|
|
28
|
+
const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] });
|
|
29
|
+
|
|
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
|
+
/** Можно ли публиковать проект: это ещё не репозиторий с адресом сервера (свой репозиторий без origin — тоже можно). */
|
|
37
|
+
export async function canPublish(st, project, h) {
|
|
38
|
+
if (!canManageFiles(st.userId) || !accountsOf(st.userId).length) return false;
|
|
39
|
+
const opts = h.gitOpts(st, project);
|
|
40
|
+
if (!(await isRepoRoot(project, opts))) return true;
|
|
41
|
+
return !(await repoState(project, opts))?.remote;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const accountOf = (st, pub) => {
|
|
45
|
+
const host = findHost(pub?.hostId);
|
|
46
|
+
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
47
|
+
return host && account ? { host, account } : null;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** Шаг «куда»: личное пространство и группы (организации) кнопками, поиск по группам. */
|
|
51
|
+
async function namespacesView(st, lang, search = '') {
|
|
52
|
+
const { host, account } = accountOf(st, st.gitPublish);
|
|
53
|
+
const list = (await listNamespaces(host, account.token, account.login, { search })).slice(0, NS_MAX);
|
|
54
|
+
const rows = list.map((n) => [{ text: [...(n.kind === 'user' ? `👤 ${n.path} — ${t('git.pb.personal', lang)}` : `👥 ${n.path}`)].slice(0, 60).join(''), callback_data: `gt:pbn:${remember(st, { host: host.id, namespace: n })}` }]);
|
|
55
|
+
rows.push([{ text: t('git.pb.search', lang), callback_data: 'gt:pbs' }, ...backRow(lang)]);
|
|
56
|
+
const head = th('git.pb.where', lang, { host: host.label, q: search ? ` «${search}»` : '' });
|
|
57
|
+
return { text: list.length ? head : `${head}\n\n<i>${th('git.pb.noPlaces', lang)}</i>`, markup: { inline_keyboard: rows } };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Итог перед созданием: что и куда публикуется; название можно изменить. */
|
|
61
|
+
function summaryView(st, project, lang) {
|
|
62
|
+
const pub = st.gitPublish;
|
|
63
|
+
const { host } = accountOf(st, pub);
|
|
64
|
+
const address = pub.slug ? `${showRemote(host.web)}/${pub.namespace.path}/${pub.slug}` : '—';
|
|
65
|
+
const text = th('git.pb.summary', lang, { p: hCode(userPath(st.userId, project, lang)), address: hCode(address), vis: `${VIS_MARK[pub.visibility]} ${t(`git.vis.${pub.visibility}`, lang)}` });
|
|
66
|
+
const rows = [
|
|
67
|
+
...(pub.slug ? [[{ text: t('git.pb.go', lang), callback_data: 'gt:pbgo', style: 'success' }]] : []),
|
|
68
|
+
[{ text: t('git.pb.rename', lang), callback_data: 'gt:pbname' }],
|
|
69
|
+
backRow(lang),
|
|
70
|
+
];
|
|
71
|
+
return { text, markup: { inline_keyboard: rows } };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Создаёт репозиторий на сервисе, делает первый коммит и отправляет. */
|
|
75
|
+
async function publish(st, project, lang, edit, h) {
|
|
76
|
+
const pub = st.gitPublish;
|
|
77
|
+
const { host, account } = accountOf(st, pub);
|
|
78
|
+
const opts = h.gitOpts(st, project, { host, account });
|
|
79
|
+
st.gitBusy = true;
|
|
80
|
+
try {
|
|
81
|
+
await edit({ text: th('git.pb.working', lang) });
|
|
82
|
+
// сначала локальная часть: если публиковать нечего, репозиторий на сервере не создаётся
|
|
83
|
+
await ensureRepo(project, opts);
|
|
84
|
+
const first = await commitAll(project, t('git.pb.firstCommit', lang), opts);
|
|
85
|
+
if (!(await hasCommits(project, opts))) return await edit({ text: th('git.pb.empty', lang), markup: { inline_keyboard: [backRow(lang)] } });
|
|
86
|
+
const created = await createRepo(host, account.token, { name: pub.name, slug: pub.slug, namespace: pub.namespace, visibility: pub.visibility });
|
|
87
|
+
log('git: репозиторий создан:', st.userId, host.id, created.path);
|
|
88
|
+
await setRemote(project, created.url, opts);
|
|
89
|
+
await pushRepo(project, opts);
|
|
90
|
+
log('git: проект опубликован:', st.userId, project, '→', created.path);
|
|
91
|
+
st.gitPublish = null;
|
|
92
|
+
const note = first.skipped.length ? `\n${th('git.skipped', lang, { files: first.skipped.join(', ') })}` : '';
|
|
93
|
+
const v = await h.view();
|
|
94
|
+
const open = created.web ? [[{ text: t('git.open', lang), url: created.web }]] : [];
|
|
95
|
+
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] } });
|
|
96
|
+
} catch (e) {
|
|
97
|
+
log('git: публикация:', e.message, '| пользователь', st.userId);
|
|
98
|
+
return await edit({ text: failText(e, lang, host), markup: { inline_keyboard: [backRow(lang)] } });
|
|
99
|
+
} finally {
|
|
100
|
+
st.gitBusy = false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Создаёт запрос на слияние текущей ветки в основную (или находит уже открытый) и даёт ссылку. */
|
|
105
|
+
async function mergeRequest(st, project, title, lang, edit, h) {
|
|
106
|
+
const mr = st.gitMr;
|
|
107
|
+
const repo = await h.repoOf(st, project);
|
|
108
|
+
if (!mr || !repo?.account) return edit({ text: th('git.diff.gone', lang), markup: { inline_keyboard: [backRow(lang)] } });
|
|
109
|
+
st.gitMr = null;
|
|
110
|
+
try {
|
|
111
|
+
const r = await openMergeRequest(repo.host, repo.account.token, repo.state.remote, { branch: mr.branch, target: mr.target, title });
|
|
112
|
+
log('git: запрос на слияние:', st.userId, project, mr.branch, '→', mr.target, r.existed ? '(уже был)' : '');
|
|
113
|
+
const text = th(r.existed ? 'git.mr.exists' : 'git.mr.done', lang, { n: r.number, branch: hCode(mr.branch), target: hCode(mr.target) });
|
|
114
|
+
return await edit({ text, markup: { inline_keyboard: [[{ text: t('git.open', lang), url: r.url }], backRow(lang)] } });
|
|
115
|
+
} catch (e) {
|
|
116
|
+
log('git: запрос на слияние:', e.message, '| пользователь', st.userId);
|
|
117
|
+
return await edit({ text: failText(e, lang, repo.host), markup: { inline_keyboard: [backRow(lang)] } });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Кнопки «Опубликовать проект» (pb…) и «Запрос на слияние» (mr…). h — помощники из gitUi. */
|
|
122
|
+
export async function onPublishCallback(st, cb, h) {
|
|
123
|
+
const { action, arg, lang, ack, edit, project } = h;
|
|
124
|
+
if (!project) return ack(t('state.projectGone', lang));
|
|
125
|
+
if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
|
|
126
|
+
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
127
|
+
if (st.busy) return ack(t('git.agentBusy', lang));
|
|
128
|
+
try {
|
|
129
|
+
// ---- запрос на слияние ----
|
|
130
|
+
if (action === 'mr') {
|
|
131
|
+
const repo = await h.repoOf(st, project);
|
|
132
|
+
if (!repo?.account || !repo.state.branch) return ack(t('proj.stale', lang));
|
|
133
|
+
await ack();
|
|
134
|
+
const info = await repoInfo(repo.host, repo.account.token, repo.state.remote);
|
|
135
|
+
const s = repo.state;
|
|
136
|
+
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)] } });
|
|
137
|
+
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)] } });
|
|
138
|
+
const suggested = (await lastSubject(project, h.gitOpts(st, project, repo))) || s.branch;
|
|
139
|
+
st.gitMr = { branch: s.branch, target: info.defaultBranch, suggested };
|
|
140
|
+
st.pendingInput = { kind: 'gitMrTitle', at: Date.now() };
|
|
141
|
+
const markup = { inline_keyboard: [[{ text: [...`«${suggested}»`].slice(0, 60).join(''), callback_data: 'gt:mrgo' }], [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] };
|
|
142
|
+
return edit({ text: th('git.mr.ask', lang, { branch: hCode(s.branch), target: hCode(info.defaultBranch) }), markup });
|
|
143
|
+
}
|
|
144
|
+
if (action === 'mrgo') {
|
|
145
|
+
st.pendingInput = null;
|
|
146
|
+
await ack();
|
|
147
|
+
return await mergeRequest(st, project, st.gitMr?.suggested ?? '', lang, edit, h);
|
|
148
|
+
}
|
|
149
|
+
// ---- публикация ----
|
|
150
|
+
if (!(await canPublish(st, project, h))) return ack(t('proj.stale', lang));
|
|
151
|
+
const accounts = accountsOf(st.userId);
|
|
152
|
+
if (action === 'pb') {
|
|
153
|
+
await ack();
|
|
154
|
+
st.gitPublish = { hostId: accounts[0].host.id, visibility: 'private', name: basename(project), slug: repoSlug(basename(project)) };
|
|
155
|
+
if (accounts.length === 1) return edit(await namespacesView(st, lang));
|
|
156
|
+
return edit({ text: th('git.pb.pickHost', lang), markup: { inline_keyboard: [...accounts.map((x) => [{ text: x.host.label, callback_data: `gt:pbh:${x.host.id}` }]), backRow(lang)] } });
|
|
157
|
+
}
|
|
158
|
+
const pub = st.gitPublish;
|
|
159
|
+
if (!pub) return ack(t('proj.stale', lang));
|
|
160
|
+
if (action === 'pbh') {
|
|
161
|
+
if (!accounts.some((x) => x.host.id === arg)) return ack(t('proj.stale', lang));
|
|
162
|
+
pub.hostId = arg;
|
|
163
|
+
await ack();
|
|
164
|
+
return edit(await namespacesView(st, lang));
|
|
165
|
+
}
|
|
166
|
+
if (!accountOf(st, pub)) return ack(t('proj.stale', lang));
|
|
167
|
+
if (action === 'pbs') {
|
|
168
|
+
await ack();
|
|
169
|
+
st.pendingInput = { kind: 'gitNsSearch', at: Date.now() };
|
|
170
|
+
return say(st.to, t('git.pb.searchAsk', lang), { reply_markup: cancelMarkup(lang) });
|
|
171
|
+
}
|
|
172
|
+
if (action === 'pbn') {
|
|
173
|
+
const chosen = recall(st, arg);
|
|
174
|
+
const ns = chosen?.host === pub.hostId ? chosen.namespace : null; // место — того же сервиса, что выбран для публикации
|
|
175
|
+
if (!ns) return ack(t('proj.stale', lang));
|
|
176
|
+
pub.namespace = ns;
|
|
177
|
+
await ack();
|
|
178
|
+
const { host } = accountOf(st, pub);
|
|
179
|
+
const rows = visibilities(host).map((v) => [{ text: `${VIS_MARK[v]} ${t(`git.vis.${v}`, lang)} — ${t(`git.vis.${v}.hint`, lang)}`, callback_data: `gt:pbv:${v}` }]);
|
|
180
|
+
return edit({ text: th('git.pb.visAsk', lang, { where: hCode(ns.path) }), markup: { inline_keyboard: [...rows, backRow(lang)] } });
|
|
181
|
+
}
|
|
182
|
+
if (!pub.namespace) return ack(t('proj.stale', lang));
|
|
183
|
+
if (action === 'pbv') {
|
|
184
|
+
if (!visibilities(accountOf(st, pub).host).includes(arg)) return ack(t('proj.stale', lang));
|
|
185
|
+
pub.visibility = arg;
|
|
186
|
+
await ack();
|
|
187
|
+
return edit(summaryView(st, project, lang));
|
|
188
|
+
}
|
|
189
|
+
if (action === 'pbname') {
|
|
190
|
+
await ack();
|
|
191
|
+
st.pendingInput = { kind: 'gitRepoName', at: Date.now() };
|
|
192
|
+
return say(st.to, t('git.pb.nameAsk', lang), { reply_markup: cancelMarkup(lang) });
|
|
193
|
+
}
|
|
194
|
+
if (action === 'pbgo') {
|
|
195
|
+
if (!pub.slug) return ack(t('git.pb.nameBad', lang));
|
|
196
|
+
await ack();
|
|
197
|
+
return await publish(st, project, lang, edit, h);
|
|
198
|
+
}
|
|
199
|
+
return ack(t('proj.stale', lang));
|
|
200
|
+
} catch (e) {
|
|
201
|
+
log(`git: ${action}:`, e.message, '| пользователь', st.userId);
|
|
202
|
+
await ack();
|
|
203
|
+
return edit({ text: failText(e, lang, accountOf(st, st.gitPublish)?.host), markup: { inline_keyboard: [backRow(lang)] } });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Текст пользователя для публикации и запроса на слияние: строка поиска группы, название репозитория, заголовок запроса.
|
|
209
|
+
* @param {object} h {wait, now, lang, project, send, repoOf, gitOpts, view}
|
|
210
|
+
* @returns {Promise<boolean>} true — текст обработан здесь
|
|
211
|
+
*/
|
|
212
|
+
export async function onPublishInput(st, text, h) {
|
|
213
|
+
const { wait, lang, project, send } = h;
|
|
214
|
+
if (!project || !canManageFiles(st.userId)) return false;
|
|
215
|
+
try {
|
|
216
|
+
if (wait.kind === 'gitMrTitle') {
|
|
217
|
+
if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
|
|
218
|
+
const title = [...text.trim().split(/\r?\n/)[0]].slice(0, 200).join('') || st.gitMr?.suggested || '';
|
|
219
|
+
await mergeRequest(st, project, title, lang, send, h);
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
const pub = st.gitPublish;
|
|
223
|
+
if (!pub || !accountOf(st, pub)) return false;
|
|
224
|
+
if (wait.kind === 'gitNsSearch') return (await send(await namespacesView(st, lang, text.trim().slice(0, 60))), true);
|
|
225
|
+
// название репозитория
|
|
226
|
+
const slug = repoSlug(text);
|
|
227
|
+
if (!slug) {
|
|
228
|
+
st.pendingInput = { ...wait, at: h.now }; // название не подошло — ждём другое
|
|
229
|
+
return (await say(st.to, t('git.pb.nameBad', lang), { reply_markup: cancelMarkup(lang) }), true);
|
|
230
|
+
}
|
|
231
|
+
Object.assign(pub, { name: text.trim().slice(0, 100), slug });
|
|
232
|
+
if (!pub.namespace) return (await send(await namespacesView(st, lang)), true);
|
|
233
|
+
return (await send(summaryView(st, project, lang)), true);
|
|
234
|
+
} catch (e) {
|
|
235
|
+
log('git: публикация (ввод):', e.message, '| пользователь', st.userId);
|
|
236
|
+
await say(st.to, failText(e, lang, accountOf(st, st.gitPublish)?.host), HTML);
|
|
237
|
+
return true;
|
|
238
|
+
}
|
|
239
|
+
}
|
package/src/gitRepoUi.mjs
CHANGED
|
@@ -8,14 +8,15 @@ import { log, say } from './ctx.mjs';
|
|
|
8
8
|
import { isSecretName, outboxDir, safeFileName } from './files.mjs';
|
|
9
9
|
import { canManageFiles } from './filesUi.mjs';
|
|
10
10
|
import { GitError, fetchRepo } from './git.mjs';
|
|
11
|
-
import {
|
|
11
|
+
import { recall, remember } from './gitKeys.mjs';
|
|
12
|
+
import { branchName, changedFiles, commitList, createBranch, discardFiles, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
|
|
12
13
|
import { errText, t } from './i18n.mjs';
|
|
13
14
|
import { endAgent, userPath } from './state.mjs';
|
|
14
15
|
import { escHtml, sendFile } from './telegram.mjs';
|
|
15
16
|
import { hCode, th } from './ui.mjs';
|
|
16
17
|
|
|
17
18
|
/** Действия кнопок, которые обрабатывает этот модуль (gt:<действие>:<аргумент>). */
|
|
18
|
-
export const REPO_ACTIONS = ['ch', 'cf', 'cm', 'br', 'bs', 'bn'];
|
|
19
|
+
export const REPO_ACTIONS = ['ch', 'cf', 'cm', 'br', 'bs', 'bn', 'dx', 'dX', 'da', 'dA'];
|
|
19
20
|
|
|
20
21
|
const PAGE = 10;
|
|
21
22
|
/** Изменения файла длиннее этого приходят файлом: в сообщение Telegram они не помещаются. */
|
|
@@ -38,13 +39,12 @@ const pager = (prefix, page, pages) => {
|
|
|
38
39
|
/** Экран «Изменения»: несохранённые изменения рабочей папки кнопками по файлам и переходы к спискам коммитов. */
|
|
39
40
|
async function changesView(st, project, repo, opts, page, lang) {
|
|
40
41
|
const { files, total } = await changedFiles(project, opts);
|
|
41
|
-
st.gitChanges = files; // кнопки ссылаются на файл номером в этом списке
|
|
42
42
|
const pages = Math.max(1, Math.ceil(files.length / PAGE));
|
|
43
43
|
page = Math.min(Math.max(page, 0), pages - 1);
|
|
44
44
|
const sum = (key) => files.reduce((n, f) => n + (f[key] ?? 0), 0);
|
|
45
45
|
const head = th('git.ch.head', lang, { p: hCode(userPath(st.userId, project, lang)), branch: repo.state.branch ?? '—' });
|
|
46
46
|
const body = total ? th('git.ch.sum', lang, { n: total, a: sum('added'), d: sum('deleted') }) + (total > files.length ? `\n<i>${th('git.ch.cut', lang, { n: files.length })}</i>` : '') : th('git.ch.none', lang);
|
|
47
|
-
const rows = files.slice(page * PAGE, (page + 1) * PAGE).map((f
|
|
47
|
+
const rows = files.slice(page * PAGE, (page + 1) * PAGE).map((f) => [{ text: [...`${MARK[f.kind] ?? '✏️'} ${tail(f.path, 40)} ${counts(f)}`.trim()].slice(0, 60).join(''), callback_data: `gt:cf:${remember(st, { path: f.path })}` }]);
|
|
48
48
|
if (pages > 1) rows.push(pager('gt:ch', page, pages));
|
|
49
49
|
const s = repo.state;
|
|
50
50
|
const commits = [];
|
|
@@ -52,19 +52,22 @@ async function changesView(st, project, repo, opts, page, lang) {
|
|
|
52
52
|
if (s.upstream && s.ahead) commits.push({ text: t('git.ch.out', lang, { n: s.ahead }), callback_data: 'gt:cm:o' });
|
|
53
53
|
if (s.upstream && s.behind) commits.push({ text: t('git.ch.in', lang, { n: s.behind }), callback_data: 'gt:cm:i' });
|
|
54
54
|
if (commits.length) rows.push(commits);
|
|
55
|
+
if (files.length && canManageFiles(st.userId)) rows.push([{ text: t('git.da.btn', lang), callback_data: 'gt:da' }]);
|
|
55
56
|
rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
56
57
|
return { text: `${head}\n\n${body}`, markup: { inline_keyboard: rows } };
|
|
57
58
|
}
|
|
58
59
|
|
|
60
|
+
/** Файлы с секретами отменой не трогаем: ими пользователь управляет сам в /files. */
|
|
61
|
+
const isSecretFile = (f) => isSecretName(`/${f.path}`);
|
|
62
|
+
|
|
59
63
|
/** Экран «Ветки»: текущая отмечена, ветки только с сервера помечены облаком; нажатие переключает. */
|
|
60
64
|
async function branchesView(st, project, repo, opts, page, lang, { sync = false } = {}) {
|
|
61
65
|
// ветки сервера узнаём сверкой с ним — нужен подключённый аккаунт; не вышло — показываем то, что известно
|
|
62
66
|
if (sync && repo.account && !st.busy && !st.gitBusy) await fetchRepo(project, opts).catch((e) => log('git: сверка веток:', e.message, '| пользователь', st.userId));
|
|
63
67
|
const { current, branches } = await listBranches(project, opts);
|
|
64
|
-
st.gitBranches = branches;
|
|
65
68
|
const pages = Math.max(1, Math.ceil(branches.length / PAGE));
|
|
66
69
|
page = Math.min(Math.max(page, 0), pages - 1);
|
|
67
|
-
const rows = branches.slice(page * PAGE, (page + 1) * PAGE).map((b
|
|
70
|
+
const rows = branches.slice(page * PAGE, (page + 1) * PAGE).map((b) => [{ text: [...`${b.current ? '✓' : b.local ? '🌿' : '☁️'} ${b.name}`].slice(0, 60).join(''), callback_data: `gt:bs:${remember(st, { branch: b.name })}` }]);
|
|
68
71
|
if (pages > 1) rows.push(pager('gt:br', page, pages));
|
|
69
72
|
if (canManageFiles(st.userId)) rows.push([{ text: t('git.br.new', lang), callback_data: 'gt:bn' }]);
|
|
70
73
|
rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
@@ -72,10 +75,12 @@ async function branchesView(st, project, repo, opts, page, lang, { sync = false
|
|
|
72
75
|
}
|
|
73
76
|
|
|
74
77
|
/** Изменения одного файла: короткие — в сообщении, длинные — файлом; содержимое файлов с секретами не показывается. */
|
|
75
|
-
async function showDiff(st, project, file, opts, lang, edit) {
|
|
76
|
-
const
|
|
78
|
+
async function showDiff(st, project, file, index, opts, lang, edit) {
|
|
79
|
+
const toList = [{ text: t('git.ch.back', lang), callback_data: 'gt:ch:0' }];
|
|
77
80
|
const title = `${MARK[file.kind] ?? '✏️'} ${hCode(file.path).html}`;
|
|
78
|
-
if (
|
|
81
|
+
if (isSecretFile(file)) return edit({ text: th('git.diff.secret', lang, { path: hCode(file.path) }), markup: { inline_keyboard: [toList] } });
|
|
82
|
+
// «Вернуть как было» — отмена изменений этого файла (с подтверждением)
|
|
83
|
+
const back = { inline_keyboard: [...(canManageFiles(st.userId) ? [[{ text: t('git.dx.btn', lang), callback_data: `gt:dx:${index}` }]] : []), toList] };
|
|
79
84
|
const diff = await fileDiff(project, file, opts);
|
|
80
85
|
if (!diff) return edit({ text: `${title}\n\n${th('git.diff.empty', lang)}`, markup: back });
|
|
81
86
|
if (diff.length <= DIFF_INLINE_MAX) return edit({ text: `${title}\n<pre><code class="language-diff">${escHtml(diff)}</code></pre>`, markup: back });
|
|
@@ -114,10 +119,12 @@ export async function onRepoCallback(st, cb, h) {
|
|
|
114
119
|
if (action === 'ch') return (await ack(), edit(await changesView(st, project, repo, opts, Number(arg) || 0, lang)));
|
|
115
120
|
if (action === 'cm') return (await ack(), edit(await commitsView(project, opts, arg, lang)));
|
|
116
121
|
if (action === 'cf') {
|
|
117
|
-
|
|
122
|
+
// кнопка помнит путь файла; сам файл ищется в свежем списке изменений
|
|
123
|
+
const path = recall(st, arg)?.path;
|
|
124
|
+
const file = path ? (await changedFiles(project, opts)).files.find((f) => f.path === path) : null;
|
|
118
125
|
if (!file) return ack(t('git.diff.gone', lang));
|
|
119
126
|
await ack();
|
|
120
|
-
return await showDiff(st, project, file, opts, lang, edit);
|
|
127
|
+
return await showDiff(st, project, file, arg, opts, lang, edit);
|
|
121
128
|
}
|
|
122
129
|
if (action === 'br') return (await ack(), edit(await branchesView(st, project, repo, opts, Number(arg) || 0, lang, { sync: true })));
|
|
123
130
|
// ---- переключение и создание ветки меняют проект ----
|
|
@@ -129,7 +136,50 @@ export async function onRepoCallback(st, cb, h) {
|
|
|
129
136
|
st.pendingInput = { kind: 'gitBranch', at: Date.now() };
|
|
130
137
|
return say(st.to, th('git.br.nameAsk', lang, { branch: hCode(repo.state.branch ?? '—') }), { parse_mode: 'HTML', reply_markup: { inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] } });
|
|
131
138
|
}
|
|
132
|
-
|
|
139
|
+
// ---- отмена изменений: необратимо, поэтому сначала вопрос, а список файлов берётся заново ----
|
|
140
|
+
if (['dx', 'dX', 'da', 'dA'].includes(action)) {
|
|
141
|
+
const fresh = (await changedFiles(project, opts)).files;
|
|
142
|
+
const run = async (list) => {
|
|
143
|
+
st.gitBusy = true;
|
|
144
|
+
try {
|
|
145
|
+
return await discardFiles(project, list, opts);
|
|
146
|
+
} finally {
|
|
147
|
+
st.gitBusy = false;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const show = async (note) => {
|
|
151
|
+
const v = await changesView(st, project, await h.repoOf(st, project), opts, 0, lang);
|
|
152
|
+
return edit({ text: `${note}\n\n${v.text}`, markup: v.markup });
|
|
153
|
+
};
|
|
154
|
+
if (action === 'dx' || action === 'dX') {
|
|
155
|
+
const path = recall(st, arg)?.path;
|
|
156
|
+
const file = path ? fresh.find((f) => f.path === path) : null;
|
|
157
|
+
if (!file) return ack(t('git.diff.gone', lang));
|
|
158
|
+
if (isSecretFile(file)) return ack(t('git.dx.secret', lang));
|
|
159
|
+
await ack();
|
|
160
|
+
if (action === 'dx') {
|
|
161
|
+
const markup = { inline_keyboard: [[{ text: t('git.dx.yes', lang), callback_data: `gt:dX:${arg}` }, { text: t('btn.cancel', lang), callback_data: `gt:cf:${arg}` }]] };
|
|
162
|
+
return edit({ text: th(file.kind === 'new' ? 'git.dx.askNew' : 'git.dx.ask', lang, { path: hCode(file.path) }), markup });
|
|
163
|
+
}
|
|
164
|
+
await run([file]);
|
|
165
|
+
log('git: изменения файла отменены:', st.userId, project, file.path);
|
|
166
|
+
return show(th('git.dx.done', lang, { path: hCode(file.path) }));
|
|
167
|
+
}
|
|
168
|
+
const list = fresh.filter((f) => !isSecretFile(f));
|
|
169
|
+
if (!list.length) return ack(t('git.ch.none', lang));
|
|
170
|
+
await ack();
|
|
171
|
+
if (action === 'da') {
|
|
172
|
+
const markup = { inline_keyboard: [[{ text: t('git.da.yes', lang), callback_data: 'gt:dA' }, { text: t('btn.cancel', lang), callback_data: 'gt:ch:0' }]] };
|
|
173
|
+
const names = list.slice(0, 15).map((f) => `${MARK[f.kind] ?? '✏️'} ${escHtml(f.path)}`).join('\n') + (list.length > 15 ? '\n…' : '');
|
|
174
|
+
return edit({ text: `${th('git.da.ask', lang, { n: list.length })}\n\n${names}`, markup });
|
|
175
|
+
}
|
|
176
|
+
const n = await run(list);
|
|
177
|
+
log('git: все изменения отменены:', st.userId, project, '| файлов', n);
|
|
178
|
+
return show(th('git.da.done', lang, { n }));
|
|
179
|
+
}
|
|
180
|
+
// кнопка помнит название ветки; сама ветка ищется в свежем списке
|
|
181
|
+
const name = recall(st, arg)?.branch;
|
|
182
|
+
const branch = name ? (await listBranches(project, opts)).branches.find((b) => b.name === name) : null;
|
|
133
183
|
if (!branch) return ack(t('proj.stale', lang));
|
|
134
184
|
if (branch.current) return ack(t('git.br.same', lang));
|
|
135
185
|
// несохранённые изменения git либо не даст унести, либо молча перенесёт в другую ветку — сначала их нужно сохранить
|