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/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
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// Экраны /git «Изменения» и «Ветки»: что изменено в проекте (список файлов, изменения по файлу, неотправленные и
|
|
2
|
+
// ожидающие на сервере коммиты) и ветки (список, переключение, новая ветка). Смотреть может любой пользователь —
|
|
3
|
+
// без агента и без запросов к модели; переключать и создавать ветки — тот, кому разрешено менять файлы проекта.
|
|
4
|
+
// Вызывается из gitUi.mjs, который передаёт сюда общие помощники (h): проект, репозиторий, запуск git.
|
|
5
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { basename, join } from 'node:path';
|
|
7
|
+
import { log, say } from './ctx.mjs';
|
|
8
|
+
import { isSecretName, outboxDir, safeFileName } from './files.mjs';
|
|
9
|
+
import { canManageFiles } from './filesUi.mjs';
|
|
10
|
+
import { GitError, fetchRepo } from './git.mjs';
|
|
11
|
+
import { recall, remember } from './gitKeys.mjs';
|
|
12
|
+
import { branchName, changedFiles, commitList, createBranch, discardFiles, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
|
|
13
|
+
import { errText, t } from './i18n.mjs';
|
|
14
|
+
import { endAgent, userPath } from './state.mjs';
|
|
15
|
+
import { escHtml, sendFile } from './telegram.mjs';
|
|
16
|
+
import { hCode, th } from './ui.mjs';
|
|
17
|
+
|
|
18
|
+
/** Действия кнопок, которые обрабатывает этот модуль (gt:<действие>:<аргумент>). */
|
|
19
|
+
export const REPO_ACTIONS = ['ch', 'cf', 'cm', 'br', 'bs', 'bn', 'dx', 'dX', 'da', 'dA'];
|
|
20
|
+
|
|
21
|
+
const PAGE = 10;
|
|
22
|
+
/** Изменения файла длиннее этого приходят файлом: в сообщение Telegram они не помещаются. */
|
|
23
|
+
export const DIFF_INLINE_MAX = 3200;
|
|
24
|
+
const DIFF_FILE_MAX = 1024 * 1024;
|
|
25
|
+
const MARK = { new: '🆕', modified: '✏️', deleted: '🗑', renamed: '🔀', conflict: '⚠️' };
|
|
26
|
+
|
|
27
|
+
const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError ? e.message : errText(e, lang) });
|
|
28
|
+
/** Длинный путь на кнопке показывается хвостом: имя файла важнее начала пути. */
|
|
29
|
+
const tail = (s, n) => ([...s].length > n ? `…${[...s].slice(-(n - 1)).join('')}` : s);
|
|
30
|
+
const counts = (f) => [f.added ? `+${f.added}` : '', f.deleted ? `−${f.deleted}` : ''].filter(Boolean).join(' ');
|
|
31
|
+
const pager = (prefix, page, pages) => {
|
|
32
|
+
const nav = [];
|
|
33
|
+
if (page > 0) nav.push({ text: '◀', callback_data: `${prefix}:${page - 1}` });
|
|
34
|
+
nav.push({ text: `${page + 1}/${pages}`, callback_data: 'nav:n' });
|
|
35
|
+
if (page < pages - 1) nav.push({ text: '▶', callback_data: `${prefix}:${page + 1}` });
|
|
36
|
+
return nav;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** Экран «Изменения»: несохранённые изменения рабочей папки кнопками по файлам и переходы к спискам коммитов. */
|
|
40
|
+
async function changesView(st, project, repo, opts, page, lang) {
|
|
41
|
+
const { files, total } = await changedFiles(project, opts);
|
|
42
|
+
const pages = Math.max(1, Math.ceil(files.length / PAGE));
|
|
43
|
+
page = Math.min(Math.max(page, 0), pages - 1);
|
|
44
|
+
const sum = (key) => files.reduce((n, f) => n + (f[key] ?? 0), 0);
|
|
45
|
+
const head = th('git.ch.head', lang, { p: hCode(userPath(st.userId, project, lang)), branch: repo.state.branch ?? '—' });
|
|
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) => [{ 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
|
+
if (pages > 1) rows.push(pager('gt:ch', page, pages));
|
|
49
|
+
const s = repo.state;
|
|
50
|
+
const commits = [];
|
|
51
|
+
if (!s.upstream) commits.push({ text: t('git.ch.local', lang), callback_data: 'gt:cm:o' });
|
|
52
|
+
if (s.upstream && s.ahead) commits.push({ text: t('git.ch.out', lang, { n: s.ahead }), callback_data: 'gt:cm:o' });
|
|
53
|
+
if (s.upstream && s.behind) commits.push({ text: t('git.ch.in', lang, { n: s.behind }), callback_data: 'gt:cm:i' });
|
|
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' }]);
|
|
56
|
+
rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
57
|
+
return { text: `${head}\n\n${body}`, markup: { inline_keyboard: rows } };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Файлы с секретами отменой не трогаем: ими пользователь управляет сам в /files. */
|
|
61
|
+
const isSecretFile = (f) => isSecretName(`/${f.path}`);
|
|
62
|
+
|
|
63
|
+
/** Экран «Ветки»: текущая отмечена, ветки только с сервера помечены облаком; нажатие переключает. */
|
|
64
|
+
async function branchesView(st, project, repo, opts, page, lang, { sync = false } = {}) {
|
|
65
|
+
// ветки сервера узнаём сверкой с ним — нужен подключённый аккаунт; не вышло — показываем то, что известно
|
|
66
|
+
if (sync && repo.account && !st.busy && !st.gitBusy) await fetchRepo(project, opts).catch((e) => log('git: сверка веток:', e.message, '| пользователь', st.userId));
|
|
67
|
+
const { current, branches } = await listBranches(project, opts);
|
|
68
|
+
const pages = Math.max(1, Math.ceil(branches.length / PAGE));
|
|
69
|
+
page = Math.min(Math.max(page, 0), pages - 1);
|
|
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 })}` }]);
|
|
71
|
+
if (pages > 1) rows.push(pager('gt:br', page, pages));
|
|
72
|
+
if (canManageFiles(st.userId)) rows.push([{ text: t('git.br.new', lang), callback_data: 'gt:bn' }]);
|
|
73
|
+
rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
74
|
+
return { text: th('git.br.head', lang, { branch: hCode(current ?? '—') }), markup: { inline_keyboard: rows } };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Изменения одного файла: короткие — в сообщении, длинные — файлом; содержимое файлов с секретами не показывается. */
|
|
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' }];
|
|
80
|
+
const title = `${MARK[file.kind] ?? '✏️'} ${hCode(file.path).html}`;
|
|
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] };
|
|
84
|
+
const diff = await fileDiff(project, file, opts);
|
|
85
|
+
if (!diff) return edit({ text: `${title}\n\n${th('git.diff.empty', lang)}`, markup: back });
|
|
86
|
+
if (diff.length <= DIFF_INLINE_MAX) return edit({ text: `${title}\n<pre><code class="language-diff">${escHtml(diff)}</code></pre>`, markup: back });
|
|
87
|
+
// большой diff — файлом через каталог исходящих пользователя; после отправки файл не нужен
|
|
88
|
+
const dir = outboxDir(st.userId);
|
|
89
|
+
mkdirSync(dir, { recursive: true });
|
|
90
|
+
const path = join(dir, `${safeFileName(basename(file.path))}.diff`);
|
|
91
|
+
writeFileSync(path, diff.length > DIFF_FILE_MAX ? `${diff.slice(0, DIFF_FILE_MAX)}\n… (truncated)\n` : `${diff}\n`);
|
|
92
|
+
try {
|
|
93
|
+
await sendFile(st.to, path);
|
|
94
|
+
} finally {
|
|
95
|
+
rmSync(path, { force: true });
|
|
96
|
+
}
|
|
97
|
+
return edit({ text: th('git.diff.sent', lang, { path: hCode(file.path) }), markup: back });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Список коммитов: ещё не отправленных ('o') или ждущих на сервере ('i'). */
|
|
101
|
+
async function commitsView(project, opts, which, lang) {
|
|
102
|
+
const list = await commitList(project, which === 'i' ? 'in' : 'out', opts);
|
|
103
|
+
const lines = list.map((c) => `<code>${escHtml(c.hash)}</code> ${escHtml(c.date)} · ${escHtml(c.author)}\n${escHtml(c.subject)}`);
|
|
104
|
+
const head = th(which === 'i' ? 'git.cm.in' : 'git.cm.out', lang, { n: list.length });
|
|
105
|
+
return { text: `${head}\n\n${lines.length ? lines.join('\n\n') : `<i>${th('git.cm.none', lang)}</i>`}`, markup: { inline_keyboard: [[{ text: t('git.ch.back', lang), callback_data: 'gt:ch:0' }]] } };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Кнопки экранов «Изменения» и «Ветки».
|
|
110
|
+
* @param {object} h помощники из gitUi: {action, arg, lang, ack, edit, project, repoOf, gitOpts}
|
|
111
|
+
*/
|
|
112
|
+
export async function onRepoCallback(st, cb, h) {
|
|
113
|
+
const { action, arg, lang, ack, edit, project } = h;
|
|
114
|
+
if (!project) return ack(t('state.projectGone', lang));
|
|
115
|
+
try {
|
|
116
|
+
const repo = await h.repoOf(st, project);
|
|
117
|
+
if (!repo) return (await ack(), edit({ text: th('git.noRepo', lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } }));
|
|
118
|
+
const opts = h.gitOpts(st, project, repo);
|
|
119
|
+
if (action === 'ch') return (await ack(), edit(await changesView(st, project, repo, opts, Number(arg) || 0, lang)));
|
|
120
|
+
if (action === 'cm') return (await ack(), edit(await commitsView(project, opts, arg, lang)));
|
|
121
|
+
if (action === 'cf') {
|
|
122
|
+
// кнопка помнит путь файла; сам файл ищется в свежем списке изменений
|
|
123
|
+
const path = recall(st, arg)?.path;
|
|
124
|
+
const file = path ? (await changedFiles(project, opts)).files.find((f) => f.path === path) : null;
|
|
125
|
+
if (!file) return ack(t('git.diff.gone', lang));
|
|
126
|
+
await ack();
|
|
127
|
+
return await showDiff(st, project, file, arg, opts, lang, edit);
|
|
128
|
+
}
|
|
129
|
+
if (action === 'br') return (await ack(), edit(await branchesView(st, project, repo, opts, Number(arg) || 0, lang, { sync: true })));
|
|
130
|
+
// ---- переключение и создание ветки меняют проект ----
|
|
131
|
+
if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
|
|
132
|
+
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
133
|
+
if (st.busy) return ack(t('git.agentBusy', lang));
|
|
134
|
+
if (action === 'bn') {
|
|
135
|
+
await ack();
|
|
136
|
+
st.pendingInput = { kind: 'gitBranch', at: Date.now() };
|
|
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' }]] } });
|
|
138
|
+
}
|
|
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;
|
|
183
|
+
if (!branch) return ack(t('proj.stale', lang));
|
|
184
|
+
if (branch.current) return ack(t('git.br.same', lang));
|
|
185
|
+
// несохранённые изменения git либо не даст унести, либо молча перенесёт в другую ветку — сначала их нужно сохранить
|
|
186
|
+
if (repo.state.changed) {
|
|
187
|
+
await ack();
|
|
188
|
+
const markup = { inline_keyboard: [[{ text: t('git.save', lang), callback_data: 'gt:save' }], [{ text: t('btn.back', lang), callback_data: 'gt:br:0' }]] };
|
|
189
|
+
return edit({ text: th('git.br.dirty', lang, { n: repo.state.changed, name: hCode(branch.name) }), markup });
|
|
190
|
+
}
|
|
191
|
+
await ack();
|
|
192
|
+
st.gitBusy = true;
|
|
193
|
+
try {
|
|
194
|
+
await switchBranch(project, branch, opts);
|
|
195
|
+
} finally {
|
|
196
|
+
st.gitBusy = false;
|
|
197
|
+
}
|
|
198
|
+
// файлы проекта сменились целиком: сессия агента с прежним представлением о них продолжаться не должна
|
|
199
|
+
endAgent(st, 'branch');
|
|
200
|
+
log('git: ветка переключена:', st.userId, project, '→', branch.name);
|
|
201
|
+
const v = await branchesView(st, project, repo, opts, 0, lang);
|
|
202
|
+
return edit({ text: `${th('git.br.switched', lang, { name: hCode(branch.name) })}\n\n${v.text}`, markup: v.markup });
|
|
203
|
+
} catch (e) {
|
|
204
|
+
log(`git: ${action}:`, e.message, '| пользователь', st.userId);
|
|
205
|
+
await ack();
|
|
206
|
+
return edit({ text: failText(e, lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } });
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Название новой ветки от пользователя (после кнопки «Новая ветка»): создаёт ветку от текущей и переключается на неё.
|
|
212
|
+
* Несохранённые изменения остаются в рабочей папке, сессия агента продолжается — файлы те же.
|
|
213
|
+
* @param {object} h {wait, now, lang, project, repoOf, gitOpts}
|
|
214
|
+
* @returns {Promise<boolean>} true — текст обработан здесь
|
|
215
|
+
*/
|
|
216
|
+
export async function onBranchInput(st, text, h) {
|
|
217
|
+
const { lang, project } = h;
|
|
218
|
+
const html = { parse_mode: 'HTML' };
|
|
219
|
+
if (!project || !canManageFiles(st.userId)) return false;
|
|
220
|
+
if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
|
|
221
|
+
try {
|
|
222
|
+
const repo = await h.repoOf(st, project);
|
|
223
|
+
if (!repo) return (await say(st.to, th('git.noRepo', lang), html), true);
|
|
224
|
+
const opts = h.gitOpts(st, project, repo);
|
|
225
|
+
const name = await branchName(text, { cwd: project, ...opts });
|
|
226
|
+
if (!name) {
|
|
227
|
+
st.pendingInput = { ...h.wait, at: h.now }; // название не подошло — ждём другое
|
|
228
|
+
return (await say(st.to, t('git.br.badName', lang), { reply_markup: { inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] } }), true);
|
|
229
|
+
}
|
|
230
|
+
await createBranch(project, name, opts);
|
|
231
|
+
log('git: ветка создана:', st.userId, project, name);
|
|
232
|
+
const markup = { inline_keyboard: [[{ text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }, { text: t('btn.back', lang), callback_data: 'gt:v' }]] };
|
|
233
|
+
await say(st.to, th('git.br.created', lang, { name: hCode(name) }), { ...html, reply_markup: markup });
|
|
234
|
+
} catch (e) {
|
|
235
|
+
log('git: новая ветка:', e.message, '| пользователь', st.userId);
|
|
236
|
+
await say(st.to, failText(e, lang), html);
|
|
237
|
+
}
|
|
238
|
+
return true;
|
|
239
|
+
}
|
package/src/gitUi.mjs
CHANGED
|
@@ -5,7 +5,10 @@ import { join } from 'node:path';
|
|
|
5
5
|
import { db, langOf, log, say } from './ctx.mjs';
|
|
6
6
|
import { canManageFiles } from './filesUi.mjs';
|
|
7
7
|
import { GitError, cloneRepo, commitAll, fetchRepo, gitAvailable, gitCommand, gitEnv, pullRepo, pushRepo, repoState, unpushedSecrets } from './git.mjs';
|
|
8
|
+
import { recall, remember } from './gitKeys.mjs';
|
|
8
9
|
import { accountsOf, addCustomHost, findHost, hostFor, hosts as allHosts, identityOf, removeCustomHost, renameCustomHost } from './gitAccess.mjs';
|
|
10
|
+
import { PUBLISH_ACTIONS, PUBLISH_INPUTS, canPublish, onPublishCallback, onPublishInput } from './gitPublishUi.mjs';
|
|
11
|
+
import { REPO_ACTIONS, onBranchInput, onRepoCallback } from './gitRepoUi.mjs';
|
|
9
12
|
import { HostError, authConfig, customHost, fetchProfile, listRepos, missingScopes, probeHost, repoFolder, showRemote } from './gitHosts.mjs';
|
|
10
13
|
import { LOCALES, errText, t } from './i18n.mjs';
|
|
11
14
|
import { ROOT, folderName, insideRoot, isPersonalRoot, navStart } from './projects.mjs';
|
|
@@ -79,10 +82,16 @@ export async function gitView(st, lang = langOf(st.userId), { sync = false } = {
|
|
|
79
82
|
if (canManageFiles(st.userId)) {
|
|
80
83
|
rows.push([{ text: t('git.pull', lang), callback_data: 'gt:pull' }, { text: t('git.push', lang), callback_data: 'gt:push' }]);
|
|
81
84
|
rows.push([{ text: t('git.save', lang), callback_data: 'gt:save', style: 'success' }]);
|
|
85
|
+
if (s.branch) rows.push([{ text: t('git.mrBtn', lang), callback_data: 'gt:mr' }]);
|
|
82
86
|
}
|
|
83
87
|
} else if (repo.host) lines.push(th('git.needAccount', lang, { host: repo.host.label }));
|
|
84
88
|
else lines.push(th(s.remote ? 'git.foreign' : 'git.noRemote', lang));
|
|
89
|
+
// что изменено и какие есть ветки — можно смотреть без агента и без аккаунта
|
|
90
|
+
rows.push([{ text: t('git.changesBtn', lang), callback_data: 'gt:ch:0' }, { text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }]);
|
|
85
91
|
} else lines.push(th('git.noRepo', lang));
|
|
92
|
+
// папку, которая ещё не связана с сервером, можно опубликовать: бот создаст для неё репозиторий
|
|
93
|
+
const publishable = project && !repo?.state.remote ? await canPublish(st, project, { gitOpts }).catch(() => false) : false;
|
|
94
|
+
if (publishable) rows.push([{ text: t('git.pbBtn', lang), callback_data: 'gt:pb' }]);
|
|
86
95
|
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));
|
|
87
96
|
if (accounts.length && canCreateProject(st.userId)) rows.push([{ text: t('git.clone', lang), callback_data: 'gt:cl' }]);
|
|
88
97
|
for (const h of hosts) {
|
|
@@ -116,6 +125,22 @@ export async function handleGit(st) {
|
|
|
116
125
|
return tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup }).catch((e) => log('git:', e.message));
|
|
117
126
|
}
|
|
118
127
|
|
|
128
|
+
/**
|
|
129
|
+
* Агент попросил отправить или получить изменения (метки [[git:push]] / [[git:pull]] в ответе): под ответом —
|
|
130
|
+
* сообщение с кнопкой. Нажатие выполняет ту же операцию, что и кнопка на экране /git. Проект не связан с сервером
|
|
131
|
+
* или аккаунт не подключён — подсказка открыть /git.
|
|
132
|
+
* @param {('push'|'pull')[]} actions
|
|
133
|
+
*/
|
|
134
|
+
export async function offerGitActions(st, actions) {
|
|
135
|
+
if (!gitAvailable() || !actions.length) return;
|
|
136
|
+
const lang = langOf(st.userId);
|
|
137
|
+
const project = projectOf(st);
|
|
138
|
+
const repo = project ? await repoOf(st, project).catch(() => null) : null;
|
|
139
|
+
if (!repo?.account || !canManageFiles(st.userId)) return say(st.to, t('git.offer.noAccount', lang), { reply_markup: { inline_keyboard: [[{ text: t('start.btn.git', lang), callback_data: 'ui:git' }]] } });
|
|
140
|
+
const row = actions.map((a) => ({ text: t(a === 'push' ? 'git.push' : 'git.pull', lang), callback_data: a === 'push' ? 'gt:push' : 'gt:pull' }));
|
|
141
|
+
return say(st.to, t(actions.length > 1 ? 'git.offer.both' : `git.offer.${actions[0]}`, lang), { reply_markup: { inline_keyboard: [row] } });
|
|
142
|
+
}
|
|
143
|
+
|
|
119
144
|
/** Текст ошибки git или сервиса для пользователя. */
|
|
120
145
|
const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
|
|
121
146
|
|
|
@@ -126,12 +151,12 @@ function cloneBase(st) {
|
|
|
126
151
|
return insideRoot(navStart(st.project, root), root) ?? (root ? insideRoot(root, root) : null);
|
|
127
152
|
}
|
|
128
153
|
|
|
129
|
-
/** Список репозиториев сервиса кнопками (страница, поиск). Выбор — gt:k
|
|
154
|
+
/** Список репозиториев сервиса кнопками (страница, поиск). Выбор — gt:k:<ключ кнопки> (gitKeys). */
|
|
130
155
|
async function reposView(st, host, account, { page = 0, search = '' } = {}, lang) {
|
|
131
156
|
const { items, more } = await listRepos(host, account.token, { page, search });
|
|
132
|
-
st.gitRepos = { host: host.id,
|
|
157
|
+
st.gitRepos = { host: host.id, page, search }; // для перелистывания с тем же поиском
|
|
133
158
|
const base = cloneBase(st);
|
|
134
|
-
const rows = items.map((r
|
|
159
|
+
const rows = items.map((r) => [{ text: [...`${r.private ? '🔒' : '📂'} ${r.name}`].slice(0, 60).join(''), callback_data: `gt:k:${remember(st, { host: host.id, repo: r })}` }]);
|
|
135
160
|
const nav = [];
|
|
136
161
|
if (page > 0) nav.push({ text: '◀', callback_data: `gt:r:${host.id}:${page - 1}` });
|
|
137
162
|
if (more) nav.push({ text: '▶', callback_data: `gt:r:${host.id}:${page + 1}` });
|
|
@@ -261,6 +286,10 @@ export async function onGitCallback(st, cb) {
|
|
|
261
286
|
await ack();
|
|
262
287
|
return edit(hostsView(lang, th('git.hosts.deleted', lang, { label: own.label, n: n ?? 0 })));
|
|
263
288
|
}
|
|
289
|
+
// экраны «Изменения» и «Ветки» — gitRepoUi
|
|
290
|
+
if (REPO_ACTIONS.includes(action)) return onRepoCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), repoOf, gitOpts });
|
|
291
|
+
// «Опубликовать проект» и «Запрос на слияние» — gitPublishUi
|
|
292
|
+
if (PUBLISH_ACTIONS.includes(action)) return onPublishCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), repoOf, gitOpts, view: () => gitView(st, lang) });
|
|
264
293
|
const host = findHost(arg);
|
|
265
294
|
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
266
295
|
try {
|
|
@@ -304,9 +333,9 @@ export async function onGitCallback(st, cb) {
|
|
|
304
333
|
return say(st.to, t('git.searchAsk', lang), { reply_markup: cancelMarkup(lang) });
|
|
305
334
|
}
|
|
306
335
|
if (action === 'k') {
|
|
307
|
-
const
|
|
308
|
-
const repo =
|
|
309
|
-
const h = findHost(
|
|
336
|
+
const chosen = recall(st, arg);
|
|
337
|
+
const repo = chosen?.repo;
|
|
338
|
+
const h = findHost(chosen?.host);
|
|
310
339
|
const acc = h ? db.getGitAccount(st.userId, h.id) : null;
|
|
311
340
|
if (!repo || !acc || !canCreateProject(st.userId)) return ack(t('proj.stale', lang));
|
|
312
341
|
if (hostFor(repo.url)?.id !== h.id) return ack(t('proj.stale', lang)); // адрес обязан принадлежать своему сервису
|
|
@@ -354,7 +383,7 @@ const dropMessage = (st, messageId) => (messageId ? tg('deleteMessage', { chat_i
|
|
|
354
383
|
*/
|
|
355
384
|
export async function onGitInput(st, text, { messageId, now = Date.now() } = {}) {
|
|
356
385
|
const wait = st.pendingInput;
|
|
357
|
-
if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName'].includes(wait?.kind)) return false;
|
|
386
|
+
if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName', 'gitBranch', ...PUBLISH_INPUTS].includes(wait?.kind)) return false;
|
|
358
387
|
const lang = langOf(st.userId);
|
|
359
388
|
const expired = now - wait.at > GIT_WAIT_MS;
|
|
360
389
|
const send = (v) => tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('git:', e.message));
|
|
@@ -373,7 +402,7 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
|
|
|
373
402
|
profile = await fetchProfile(host, token);
|
|
374
403
|
} catch (e) {
|
|
375
404
|
log('git: проверка токена:', e.message, '| пользователь', st.userId);
|
|
376
|
-
const textFail = e instanceof HostError && e.code
|
|
405
|
+
const textFail = e instanceof HostError && ['auth', 'forbidden'].includes(e.code) ? t('git.tokenBad', lang) : t('git.tokenFail', lang, { msg: e.message });
|
|
377
406
|
return (await say(st.to, textFail, { reply_markup: cancelMarkup(lang) }), true); // ожидание остаётся: можно прислать ещё раз
|
|
378
407
|
}
|
|
379
408
|
st.pendingInput = null;
|
|
@@ -394,6 +423,8 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
|
|
|
394
423
|
|
|
395
424
|
st.pendingInput = null;
|
|
396
425
|
if (expired) return false; // адрес сервера, строка поиска и описание изменений — не секреты: позже это обычный запрос агенту
|
|
426
|
+
if (wait.kind === 'gitBranch') return onBranchInput(st, text, { wait, now, lang, project: projectOf(st), repoOf, gitOpts });
|
|
427
|
+
if (PUBLISH_INPUTS.includes(wait.kind)) return onPublishInput(st, text, { wait, now, lang, send, project: projectOf(st), repoOf, gitOpts, view: () => gitView(st, lang) });
|
|
397
428
|
// свои серверы: адрес нового сервера или новое название — только от администратора
|
|
398
429
|
if (wait.kind === 'gitHostUrl' || wait.kind === 'gitHostName') {
|
|
399
430
|
if (!isAdmin(st.userId)) return false;
|