acpgram 1.27.0 → 1.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/README.ru.md +5 -1
- package/package.json +1 -1
- package/src/git.mjs +13 -4
- package/src/gitInspect.mjs +163 -0
- package/src/gitRepoUi.mjs +189 -0
- package/src/gitUi.mjs +7 -1
- package/src/i18n.mjs +25 -0
package/README.md
CHANGED
|
@@ -233,6 +233,8 @@ The `/git` command connects projects to GitHub, GitLab.com and your own servers
|
|
|
233
233
|
- **Connecting an account.** "➕ Connect …" → the bot gives a link to the tokens page and the list of permissions, and the user sends the access token in one message. The message is deleted from the chat right away and is not passed to the agent. The bot checks the token with the service, shows who is connected and until when the token is valid, and warns if permissions are missing. Disconnecting removes the token from the bot.
|
|
234
234
|
- **Cloning.** "⬇️ Clone a repository" (or "⬇️ From Git" in `/project`) lists the user's repositories as buttons, recently changed first, with search by name. The chosen one is cloned into the personal workspace (without it, next to the current project) and becomes the project.
|
|
235
235
|
- **The project repository.** The screen shows the branch, the number of changed files, of commits not pushed and of new commits on the server; it checks the server when opened and on "Refresh". "⬇️ Pull" takes the changes when that is possible without a merge; if the histories diverged, the agent does the merge. "⬆️ Push" sends the commits. "💾 Save and push" asks for a description, commits all changes and pushes.
|
|
236
|
+
- **"📋 Changes".** The list of changed files with marks (new, modified, deleted, renamed) and the number of added and removed lines. Pressing a file shows what changed in it: short changes in the message, long ones as a file. The contents of files with secrets are not shown. The same screen lists the commits that are not pushed yet and those waiting on the server. All of this is visible without the agent and without model requests.
|
|
237
|
+
- **"🌿 Branches".** Local and server branches in one list; pressing a branch switches to it, "➕ New branch" creates one from the current branch. With unsaved changes the bot does not switch and offers to save them first; the same while the agent is working. After switching, the next request starts a new agent session, because the project files have changed. "Push" creates a new branch on the server too.
|
|
236
238
|
- **The commit author** is the account owner: the name and email are given to both the bot and the agent, so the agent's commits are signed by the user.
|
|
237
239
|
- **Secrets do not go to the repository.** On "Save and push", files with secrets (`.env`, keys, credentials) are left out of the commit and appended to `.gitignore`. If the agent committed such a file, the bot warns before pushing and pushes only after "Push anyway".
|
|
238
240
|
|
package/README.ru.md
CHANGED
|
@@ -123,6 +123,8 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
123
123
|
- **Подключение аккаунта.** «➕ Подключить …» → бот даёт ссылку на страницу токенов и список нужных прав, пользователь присылает токен доступа одним сообщением. Сообщение сразу удаляется из чата и агенту не передаётся. Бот проверяет токен в сервисе, показывает, кто подключён и до какого числа токен действует, и предупреждает, если прав не хватает. Отключение удаляет токен из бота.
|
|
124
124
|
- **Клонирование.** «⬇️ Клонировать репозиторий» (или «⬇️ Из Git» в `/project`) показывает репозитории пользователя кнопками, недавно менявшиеся первыми, с поиском по названию. Выбранный клонируется в личное пространство (без него — рядом с текущим проектом) и становится проектом.
|
|
125
125
|
- **Репозиторий проекта.** Экран показывает ветку, число изменённых файлов, неотправленных коммитов и новых коммитов на сервере; при открытии и по кнопке «Обновить» он сверяется с сервером. «⬇️ Получить» забирает изменения, если это возможно без слияния; если истории разошлись, слияние делает агент. «⬆️ Отправить» отправляет коммиты. «💾 Сохранить и отправить» спрашивает описание, коммитит все изменения и отправляет.
|
|
126
|
+
- **«📋 Изменения».** Список изменённых файлов с пометками (новый, изменён, удалён, переименован) и числом добавленных и убранных строк. Нажатие на файл показывает, что в нём изменилось: короткие изменения — в сообщении, длинные — файлом. Содержимое файлов с секретами не показывается. Там же — коммиты, которые ещё не отправлены, и те, что ждут на сервере. Всё это видно без агента и без запросов к модели.
|
|
127
|
+
- **«🌿 Ветки».** Локальные ветки и ветки сервера одним списком; нажатие переключает на ветку, «➕ Новая ветка» создаёт её от текущей. При несохранённых изменениях бот не переключает, а предлагает сначала сохранить их; пока агент выполняет запрос — тоже. После переключения следующий запрос начинает новую сессию агента: файлы проекта сменились. «Отправить» создаёт новую ветку и на сервере.
|
|
126
128
|
- **Автор коммитов** — владелец аккаунта: его имя и почта передаются и боту, и агенту, так что коммиты агента подписаны пользователем.
|
|
127
129
|
- **Секреты не уходят в репозиторий.** При «Сохранить и отправить» файлы с секретами (`.env`, ключи, учётные данные) из коммита исключаются и дописываются в `.gitignore`. Если такой файл закоммитил агент, перед отправкой бот предупреждает и отправляет только после «Отправить всё равно».
|
|
128
130
|
|
|
@@ -421,7 +423,9 @@ src/
|
|
|
421
423
|
git.mjs команды git бота: клонирование, состояние, получение, отправка, коммит без секретов; безопасный запуск
|
|
422
424
|
gitHosts.mjs GitHub и GitLab: профиль и репозитории по токену, вход для git
|
|
423
425
|
gitAccess.mjs аккаунты Git пользователей; что из них получает агент (автор коммитов, вход при GIT_AGENT_AUTH)
|
|
424
|
-
gitUi.mjs команда /git: аккаунты, клонирование, получить / отправить / сохранить
|
|
426
|
+
gitUi.mjs команда /git: аккаунты, свои серверы, клонирование, получить / отправить / сохранить
|
|
427
|
+
gitInspect.mjs что изменилось и какие есть ветки: список файлов, изменения по файлу, коммиты, переключение ветки
|
|
428
|
+
gitRepoUi.mjs экраны /git «Изменения» и «Ветки»
|
|
425
429
|
sessionsUi.mjs команда /sessions: возврат к прошлой сессии
|
|
426
430
|
tools.mjs разбор событий вызовов инструментов агента
|
|
427
431
|
asks.mjs кнопки быстрого ответа от агента: метка [[ask: …]], разметка кнопок, выбор по нажатию
|
package/package.json
CHANGED
package/src/git.mjs
CHANGED
|
@@ -89,7 +89,9 @@ export class GitError extends Error {
|
|
|
89
89
|
* wrap — песочница (sandbox.agentSandbox с командой git); hide — строки, которые нужно вычистить из вывода (токены)
|
|
90
90
|
* @returns {Promise<string>} stdout
|
|
91
91
|
*/
|
|
92
|
-
export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120_000, hide = [] } = {}) {
|
|
92
|
+
export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120_000, hide = [], okCodes = [0], maxOut = 4 * 1024 * 1024 } = {}) {
|
|
93
|
+
// okCodes — коды выхода, которые не считаются ошибкой (git diff --no-index возвращает 1, когда различия есть);
|
|
94
|
+
// maxOut — сколько символов вывода хранить (остальное отбрасывается: большой diff целиком не нужен)
|
|
93
95
|
const command = wrap ? wrap.command : gitCommand();
|
|
94
96
|
const argv = wrap ? [...wrap.args, ...args] : args;
|
|
95
97
|
const clean = (s) => hide.filter(Boolean).reduce((acc, h) => acc.replaceAll(h, '***'), s);
|
|
@@ -107,8 +109,15 @@ export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120
|
|
|
107
109
|
timedOut = true;
|
|
108
110
|
killTree(proc, 1000);
|
|
109
111
|
}, timeoutMs);
|
|
110
|
-
|
|
111
|
-
proc.
|
|
112
|
+
// кодировка задаётся потоку: иначе символ не из латиницы, попавший на границу порций, превращается в мусор
|
|
113
|
+
proc.stdout.setEncoding('utf8');
|
|
114
|
+
proc.stderr.setEncoding('utf8');
|
|
115
|
+
proc.stdout.on('data', (d) => {
|
|
116
|
+
if (out.length < maxOut) out += d;
|
|
117
|
+
});
|
|
118
|
+
proc.stderr.on('data', (d) => {
|
|
119
|
+
if (err.length < 64 * 1024) err += d;
|
|
120
|
+
});
|
|
112
121
|
proc.on('error', (e) => {
|
|
113
122
|
clearTimeout(timer);
|
|
114
123
|
reject(new GitError(e.message));
|
|
@@ -116,7 +125,7 @@ export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120
|
|
|
116
125
|
proc.on('close', (code) => {
|
|
117
126
|
clearTimeout(timer);
|
|
118
127
|
if (timedOut) return reject(new GitError(`git ${args[0]}: нет ответа за ${Math.round(timeoutMs / 1000)} с`, { timeout: true }));
|
|
119
|
-
if (code
|
|
128
|
+
if (!okCodes.includes(code)) {
|
|
120
129
|
const stderr = clean(err.trim());
|
|
121
130
|
// подсказки git («hint: …») пользователю не нужны — в сообщение идут последние содержательные строки
|
|
122
131
|
const lines = stderr.split(/\r?\n/).filter((l) => l.trim() && !/^hint:/i.test(l));
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Git: что изменилось и какие есть ветки — для экранов «Изменения» и «Ветки» в /git.
|
|
2
|
+
// Только чтение репозитория, кроме переключения и создания ветки. Команды запускает runGit (git.mjs) — с теми же
|
|
3
|
+
// безопасными настройками и, при включённой песочнице, внутри неё.
|
|
4
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { GitError, runGit } from './git.mjs';
|
|
7
|
+
|
|
8
|
+
/** Сколько изменённых файлов показывать (в большом несобранном проекте их могут быть тысячи). */
|
|
9
|
+
export const CHANGES_MAX = 300;
|
|
10
|
+
/** Файлы крупнее этого не читаются ради подсчёта строк. */
|
|
11
|
+
const COUNT_MAX_BYTES = 512 * 1024;
|
|
12
|
+
|
|
13
|
+
const kindOf = (xy) => {
|
|
14
|
+
if (xy === '??') return 'new';
|
|
15
|
+
if (xy.includes('U') || xy === 'AA' || xy === 'DD') return 'conflict';
|
|
16
|
+
if (xy.includes('R') || xy.includes('C')) return 'renamed';
|
|
17
|
+
if (xy.includes('D')) return 'deleted';
|
|
18
|
+
if (xy.includes('A')) return 'new';
|
|
19
|
+
return 'modified';
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Разбор `git status --porcelain=v1 -z`: [{path, kind, from?}], kind — new | modified | deleted | renamed | conflict.
|
|
24
|
+
* У переименованного файла следующая запись — прежнее имя.
|
|
25
|
+
*/
|
|
26
|
+
export function parseChanges(text) {
|
|
27
|
+
const parts = String(text ?? '').split('\0');
|
|
28
|
+
const out = [];
|
|
29
|
+
for (let i = 0; i < parts.length; i++) {
|
|
30
|
+
const rec = parts[i];
|
|
31
|
+
if (rec.length < 4) continue;
|
|
32
|
+
const xy = rec.slice(0, 2);
|
|
33
|
+
const item = { path: rec.slice(3), kind: kindOf(xy) };
|
|
34
|
+
if (xy.includes('R') || xy.includes('C')) item.from = parts[++i];
|
|
35
|
+
out.push(item);
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Разбор `git diff --numstat -z`: Map путь → {added, deleted} (у двоичных файлов — null). */
|
|
41
|
+
export function parseNumstat(text) {
|
|
42
|
+
const parts = String(text ?? '').split('\0');
|
|
43
|
+
const map = new Map();
|
|
44
|
+
for (let i = 0; i < parts.length; i++) {
|
|
45
|
+
const m = /^(\d+|-)\t(\d+|-)\t(.*)$/s.exec(parts[i]);
|
|
46
|
+
if (!m) continue;
|
|
47
|
+
let path = m[3];
|
|
48
|
+
if (!path) {
|
|
49
|
+
path = parts[i + 2]; // переименование: далее — прежнее и новое имя
|
|
50
|
+
i += 2;
|
|
51
|
+
}
|
|
52
|
+
if (path) map.set(path, { added: m[1] === '-' ? null : Number(m[1]), deleted: m[2] === '-' ? null : Number(m[2]) });
|
|
53
|
+
}
|
|
54
|
+
return map;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Число строк нового файла (которого git ещё не знает) или null, если он велик, двоичный или не читается. */
|
|
58
|
+
function countLines(file) {
|
|
59
|
+
try {
|
|
60
|
+
if (statSync(file).size > COUNT_MAX_BYTES) return null;
|
|
61
|
+
const buf = readFileSync(file);
|
|
62
|
+
if (buf.includes(0)) return null;
|
|
63
|
+
if (!buf.length) return 0;
|
|
64
|
+
let n = 0;
|
|
65
|
+
for (const b of buf) if (b === 10) n++;
|
|
66
|
+
return buf[buf.length - 1] === 10 ? n : n + 1;
|
|
67
|
+
} catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Несохранённые изменения рабочей папки относительно последнего коммита: [{path, kind, added, deleted, from?}].
|
|
74
|
+
* added / deleted — число строк (null, если неизвестно). total — сколько всего изменённых файлов (список обрезается).
|
|
75
|
+
*/
|
|
76
|
+
export async function changedFiles(cwd, opts = {}) {
|
|
77
|
+
const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
78
|
+
const all = parseChanges(await runGit(['status', '--porcelain=v1', '-z', '--untracked-files=all'], { cwd, ...opts }));
|
|
79
|
+
// в репозитории без коммитов сравнивать не с чем — тогда без числа строк
|
|
80
|
+
const counts = await runGit(['diff', '--numstat', '-z', 'HEAD'], { cwd, ...opts }).then(parseNumstat, () => new Map());
|
|
81
|
+
const files = all.slice(0, CHANGES_MAX).map((f) => {
|
|
82
|
+
const c = counts.get(f.path);
|
|
83
|
+
if (c) return { ...f, ...c };
|
|
84
|
+
return { ...f, added: f.kind === 'new' ? countLines(join(top, f.path)) : null, deleted: f.kind === 'new' ? 0 : null };
|
|
85
|
+
});
|
|
86
|
+
return { files, total: all.length };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Изменения одного файла текстом (unified diff, без служебного начала). Новый файл показывается целиком как добавленный.
|
|
91
|
+
* @param {{path: string, kind: string}} file запись из changedFiles (путь — от корня репозитория)
|
|
92
|
+
*/
|
|
93
|
+
export async function fileDiff(cwd, file, opts = {}) {
|
|
94
|
+
const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
95
|
+
const base = { cwd: top, maxOut: 300_000, ...opts };
|
|
96
|
+
const raw = file.kind === 'new'
|
|
97
|
+
? await runGit(['diff', '--no-color', '--no-ext-diff', '--no-index', '--', '/dev/null', file.path], { ...base, okCodes: [0, 1] })
|
|
98
|
+
: await runGit(['diff', '--no-color', '--no-ext-diff', 'HEAD', '--', file.path], base);
|
|
99
|
+
// «diff --git…», «index…» и подобные строки до первого «---» пользователю ничего не говорят
|
|
100
|
+
const lines = raw.split(/\r?\n/);
|
|
101
|
+
const start = lines.findIndex((l) => l.startsWith('--- ') || l.startsWith('Binary files') || l.startsWith('@@'));
|
|
102
|
+
return (start > 0 ? lines.slice(start) : lines).join('\n').trimEnd();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Коммиты: которые ещё не отправлены ('out') или которые есть на сервере, а локально нет ('in').
|
|
107
|
+
* Без ветки на сервере «не отправлено» — последние коммиты ветки, «на сервере» — пусто.
|
|
108
|
+
* @returns {Promise<{hash: string, author: string, date: string, subject: string}[]>}
|
|
109
|
+
*/
|
|
110
|
+
export async function commitList(cwd, dir, opts = {}, limit = 20) {
|
|
111
|
+
const upstream = await runGit(['rev-parse', '--abbrev-ref', '@{u}'], { cwd, ...opts }).then((s) => s.trim(), () => null);
|
|
112
|
+
if (!upstream && dir === 'in') return [];
|
|
113
|
+
const range = !upstream ? 'HEAD' : dir === 'in' ? 'HEAD..@{u}' : '@{u}..HEAD';
|
|
114
|
+
const out = await runGit(['log', `-n${limit}`, '--format=%h%x09%an%x09%ad%x09%s', '--date=short', range], { cwd, ...opts }).catch(() => '');
|
|
115
|
+
return out.split(/\r?\n/).filter(Boolean).map((l) => {
|
|
116
|
+
const [hash, author, date, ...rest] = l.split('\t');
|
|
117
|
+
return { hash, author, date, subject: rest.join('\t') };
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Ветки: локальные и ветки сервера (origin) одним списком — [{name, local, remote, date, current}], текущая первой,
|
|
123
|
+
* дальше по дате последнего коммита.
|
|
124
|
+
*/
|
|
125
|
+
export async function listBranches(cwd, opts = {}) {
|
|
126
|
+
const current = await runGit(['branch', '--show-current'], { cwd, ...opts }).then((s) => s.trim() || null, () => null);
|
|
127
|
+
const out = await runGit(['for-each-ref', '--format=%(refname)%09%(committerdate:iso-strict)', 'refs/heads', 'refs/remotes/origin'], { cwd, ...opts });
|
|
128
|
+
const map = new Map();
|
|
129
|
+
for (const line of out.split(/\r?\n/).filter(Boolean)) {
|
|
130
|
+
const [ref, date] = line.split('\t');
|
|
131
|
+
const local = ref.startsWith('refs/heads/');
|
|
132
|
+
const name = local ? ref.slice('refs/heads/'.length) : ref.slice('refs/remotes/origin/'.length);
|
|
133
|
+
if (!name || name === 'HEAD') continue;
|
|
134
|
+
const b = map.get(name) ?? { name, local: false, remote: false, date: '' };
|
|
135
|
+
if (local) b.local = true;
|
|
136
|
+
else b.remote = true;
|
|
137
|
+
if (date > b.date) b.date = date;
|
|
138
|
+
map.set(name, b);
|
|
139
|
+
}
|
|
140
|
+
const list = [...map.values()].map((b) => ({ ...b, current: b.name === current }));
|
|
141
|
+
list.sort((a, b) => Number(b.current) - Number(a.current) || b.date.localeCompare(a.date) || a.name.localeCompare(b.name));
|
|
142
|
+
return { current, branches: list };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Название ветки из текста пользователя: пробелы — в «-»; не подходит — null (проверку формата делает сам git). */
|
|
146
|
+
export async function branchName(input, { cwd, ...opts }) {
|
|
147
|
+
const name = String(input ?? '').trim().replace(/\s+/g, '-');
|
|
148
|
+
if (!name || name.length > 100 || name.startsWith('-')) return null;
|
|
149
|
+
return runGit(['check-ref-format', '--branch', name], { cwd, ...opts }).then(() => name, () => null);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Переключается на ветку: локальную — как есть, существующую только на сервере — создаёт локальную, связанную с ней.
|
|
154
|
+
* Вызывающий отвечает за то, что в рабочей папке нет несохранённых изменений.
|
|
155
|
+
*/
|
|
156
|
+
export async function switchBranch(cwd, branch, opts = {}) {
|
|
157
|
+
if (!branch?.name || branch.name.startsWith('-')) throw new GitError('некорректное название ветки');
|
|
158
|
+
if (branch.local) return runGit(['switch', '--quiet', branch.name], { cwd, ...opts });
|
|
159
|
+
return runGit(['switch', '--quiet', '--track', `origin/${branch.name}`], { cwd, ...opts });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Создаёт ветку от текущего коммита и переключается на неё (несохранённые изменения остаются в рабочей папке). */
|
|
163
|
+
export const createBranch = (cwd, name, opts = {}) => runGit(['switch', '--quiet', '-c', name], { cwd, ...opts });
|
|
@@ -0,0 +1,189 @@
|
|
|
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 { branchName, changedFiles, commitList, createBranch, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
|
|
12
|
+
import { errText, t } from './i18n.mjs';
|
|
13
|
+
import { endAgent, userPath } from './state.mjs';
|
|
14
|
+
import { escHtml, sendFile } from './telegram.mjs';
|
|
15
|
+
import { hCode, th } from './ui.mjs';
|
|
16
|
+
|
|
17
|
+
/** Действия кнопок, которые обрабатывает этот модуль (gt:<действие>:<аргумент>). */
|
|
18
|
+
export const REPO_ACTIONS = ['ch', 'cf', 'cm', 'br', 'bs', 'bn'];
|
|
19
|
+
|
|
20
|
+
const PAGE = 10;
|
|
21
|
+
/** Изменения файла длиннее этого приходят файлом: в сообщение Telegram они не помещаются. */
|
|
22
|
+
export const DIFF_INLINE_MAX = 3200;
|
|
23
|
+
const DIFF_FILE_MAX = 1024 * 1024;
|
|
24
|
+
const MARK = { new: '🆕', modified: '✏️', deleted: '🗑', renamed: '🔀', conflict: '⚠️' };
|
|
25
|
+
|
|
26
|
+
const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError ? e.message : errText(e, lang) });
|
|
27
|
+
/** Длинный путь на кнопке показывается хвостом: имя файла важнее начала пути. */
|
|
28
|
+
const tail = (s, n) => ([...s].length > n ? `…${[...s].slice(-(n - 1)).join('')}` : s);
|
|
29
|
+
const counts = (f) => [f.added ? `+${f.added}` : '', f.deleted ? `−${f.deleted}` : ''].filter(Boolean).join(' ');
|
|
30
|
+
const pager = (prefix, page, pages) => {
|
|
31
|
+
const nav = [];
|
|
32
|
+
if (page > 0) nav.push({ text: '◀', callback_data: `${prefix}:${page - 1}` });
|
|
33
|
+
nav.push({ text: `${page + 1}/${pages}`, callback_data: 'nav:n' });
|
|
34
|
+
if (page < pages - 1) nav.push({ text: '▶', callback_data: `${prefix}:${page + 1}` });
|
|
35
|
+
return nav;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** Экран «Изменения»: несохранённые изменения рабочей папки кнопками по файлам и переходы к спискам коммитов. */
|
|
39
|
+
async function changesView(st, project, repo, opts, page, lang) {
|
|
40
|
+
const { files, total } = await changedFiles(project, opts);
|
|
41
|
+
st.gitChanges = files; // кнопки ссылаются на файл номером в этом списке
|
|
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, i) => [{ text: [...`${MARK[f.kind] ?? '✏️'} ${tail(f.path, 40)} ${counts(f)}`.trim()].slice(0, 60).join(''), callback_data: `gt:cf:${page * PAGE + i}` }]);
|
|
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
|
+
rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
56
|
+
return { text: `${head}\n\n${body}`, markup: { inline_keyboard: rows } };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Экран «Ветки»: текущая отмечена, ветки только с сервера помечены облаком; нажатие переключает. */
|
|
60
|
+
async function branchesView(st, project, repo, opts, page, lang, { sync = false } = {}) {
|
|
61
|
+
// ветки сервера узнаём сверкой с ним — нужен подключённый аккаунт; не вышло — показываем то, что известно
|
|
62
|
+
if (sync && repo.account && !st.busy && !st.gitBusy) await fetchRepo(project, opts).catch((e) => log('git: сверка веток:', e.message, '| пользователь', st.userId));
|
|
63
|
+
const { current, branches } = await listBranches(project, opts);
|
|
64
|
+
st.gitBranches = branches;
|
|
65
|
+
const pages = Math.max(1, Math.ceil(branches.length / PAGE));
|
|
66
|
+
page = Math.min(Math.max(page, 0), pages - 1);
|
|
67
|
+
const rows = branches.slice(page * PAGE, (page + 1) * PAGE).map((b, i) => [{ text: [...`${b.current ? '✓' : b.local ? '🌿' : '☁️'} ${b.name}`].slice(0, 60).join(''), callback_data: `gt:bs:${page * PAGE + i}` }]);
|
|
68
|
+
if (pages > 1) rows.push(pager('gt:br', page, pages));
|
|
69
|
+
if (canManageFiles(st.userId)) rows.push([{ text: t('git.br.new', lang), callback_data: 'gt:bn' }]);
|
|
70
|
+
rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
71
|
+
return { text: th('git.br.head', lang, { branch: hCode(current ?? '—') }), markup: { inline_keyboard: rows } };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Изменения одного файла: короткие — в сообщении, длинные — файлом; содержимое файлов с секретами не показывается. */
|
|
75
|
+
async function showDiff(st, project, file, opts, lang, edit) {
|
|
76
|
+
const back = { inline_keyboard: [[{ text: t('git.ch.back', lang), callback_data: 'gt:ch:0' }]] };
|
|
77
|
+
const title = `${MARK[file.kind] ?? '✏️'} ${hCode(file.path).html}`;
|
|
78
|
+
if (isSecretName(`/${file.path}`)) return edit({ text: th('git.diff.secret', lang, { path: hCode(file.path) }), markup: back });
|
|
79
|
+
const diff = await fileDiff(project, file, opts);
|
|
80
|
+
if (!diff) return edit({ text: `${title}\n\n${th('git.diff.empty', lang)}`, markup: back });
|
|
81
|
+
if (diff.length <= DIFF_INLINE_MAX) return edit({ text: `${title}\n<pre><code class="language-diff">${escHtml(diff)}</code></pre>`, markup: back });
|
|
82
|
+
// большой diff — файлом через каталог исходящих пользователя; после отправки файл не нужен
|
|
83
|
+
const dir = outboxDir(st.userId);
|
|
84
|
+
mkdirSync(dir, { recursive: true });
|
|
85
|
+
const path = join(dir, `${safeFileName(basename(file.path))}.diff`);
|
|
86
|
+
writeFileSync(path, diff.length > DIFF_FILE_MAX ? `${diff.slice(0, DIFF_FILE_MAX)}\n… (truncated)\n` : `${diff}\n`);
|
|
87
|
+
try {
|
|
88
|
+
await sendFile(st.to, path);
|
|
89
|
+
} finally {
|
|
90
|
+
rmSync(path, { force: true });
|
|
91
|
+
}
|
|
92
|
+
return edit({ text: th('git.diff.sent', lang, { path: hCode(file.path) }), markup: back });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Список коммитов: ещё не отправленных ('o') или ждущих на сервере ('i'). */
|
|
96
|
+
async function commitsView(project, opts, which, lang) {
|
|
97
|
+
const list = await commitList(project, which === 'i' ? 'in' : 'out', opts);
|
|
98
|
+
const lines = list.map((c) => `<code>${escHtml(c.hash)}</code> ${escHtml(c.date)} · ${escHtml(c.author)}\n${escHtml(c.subject)}`);
|
|
99
|
+
const head = th(which === 'i' ? 'git.cm.in' : 'git.cm.out', lang, { n: list.length });
|
|
100
|
+
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' }]] } };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Кнопки экранов «Изменения» и «Ветки».
|
|
105
|
+
* @param {object} h помощники из gitUi: {action, arg, lang, ack, edit, project, repoOf, gitOpts}
|
|
106
|
+
*/
|
|
107
|
+
export async function onRepoCallback(st, cb, h) {
|
|
108
|
+
const { action, arg, lang, ack, edit, project } = h;
|
|
109
|
+
if (!project) return ack(t('state.projectGone', lang));
|
|
110
|
+
try {
|
|
111
|
+
const repo = await h.repoOf(st, project);
|
|
112
|
+
if (!repo) return (await ack(), edit({ text: th('git.noRepo', lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } }));
|
|
113
|
+
const opts = h.gitOpts(st, project, repo);
|
|
114
|
+
if (action === 'ch') return (await ack(), edit(await changesView(st, project, repo, opts, Number(arg) || 0, lang)));
|
|
115
|
+
if (action === 'cm') return (await ack(), edit(await commitsView(project, opts, arg, lang)));
|
|
116
|
+
if (action === 'cf') {
|
|
117
|
+
const file = st.gitChanges?.[Number(arg)];
|
|
118
|
+
if (!file) return ack(t('git.diff.gone', lang));
|
|
119
|
+
await ack();
|
|
120
|
+
return await showDiff(st, project, file, opts, lang, edit);
|
|
121
|
+
}
|
|
122
|
+
if (action === 'br') return (await ack(), edit(await branchesView(st, project, repo, opts, Number(arg) || 0, lang, { sync: true })));
|
|
123
|
+
// ---- переключение и создание ветки меняют проект ----
|
|
124
|
+
if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
|
|
125
|
+
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
126
|
+
if (st.busy) return ack(t('git.agentBusy', lang));
|
|
127
|
+
if (action === 'bn') {
|
|
128
|
+
await ack();
|
|
129
|
+
st.pendingInput = { kind: 'gitBranch', at: Date.now() };
|
|
130
|
+
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
|
+
}
|
|
132
|
+
const branch = st.gitBranches?.[Number(arg)];
|
|
133
|
+
if (!branch) return ack(t('proj.stale', lang));
|
|
134
|
+
if (branch.current) return ack(t('git.br.same', lang));
|
|
135
|
+
// несохранённые изменения git либо не даст унести, либо молча перенесёт в другую ветку — сначала их нужно сохранить
|
|
136
|
+
if (repo.state.changed) {
|
|
137
|
+
await ack();
|
|
138
|
+
const markup = { inline_keyboard: [[{ text: t('git.save', lang), callback_data: 'gt:save' }], [{ text: t('btn.back', lang), callback_data: 'gt:br:0' }]] };
|
|
139
|
+
return edit({ text: th('git.br.dirty', lang, { n: repo.state.changed, name: hCode(branch.name) }), markup });
|
|
140
|
+
}
|
|
141
|
+
await ack();
|
|
142
|
+
st.gitBusy = true;
|
|
143
|
+
try {
|
|
144
|
+
await switchBranch(project, branch, opts);
|
|
145
|
+
} finally {
|
|
146
|
+
st.gitBusy = false;
|
|
147
|
+
}
|
|
148
|
+
// файлы проекта сменились целиком: сессия агента с прежним представлением о них продолжаться не должна
|
|
149
|
+
endAgent(st, 'branch');
|
|
150
|
+
log('git: ветка переключена:', st.userId, project, '→', branch.name);
|
|
151
|
+
const v = await branchesView(st, project, repo, opts, 0, lang);
|
|
152
|
+
return edit({ text: `${th('git.br.switched', lang, { name: hCode(branch.name) })}\n\n${v.text}`, markup: v.markup });
|
|
153
|
+
} catch (e) {
|
|
154
|
+
log(`git: ${action}:`, e.message, '| пользователь', st.userId);
|
|
155
|
+
await ack();
|
|
156
|
+
return edit({ text: failText(e, lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Название новой ветки от пользователя (после кнопки «Новая ветка»): создаёт ветку от текущей и переключается на неё.
|
|
162
|
+
* Несохранённые изменения остаются в рабочей папке, сессия агента продолжается — файлы те же.
|
|
163
|
+
* @param {object} h {wait, now, lang, project, repoOf, gitOpts}
|
|
164
|
+
* @returns {Promise<boolean>} true — текст обработан здесь
|
|
165
|
+
*/
|
|
166
|
+
export async function onBranchInput(st, text, h) {
|
|
167
|
+
const { lang, project } = h;
|
|
168
|
+
const html = { parse_mode: 'HTML' };
|
|
169
|
+
if (!project || !canManageFiles(st.userId)) return false;
|
|
170
|
+
if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
|
|
171
|
+
try {
|
|
172
|
+
const repo = await h.repoOf(st, project);
|
|
173
|
+
if (!repo) return (await say(st.to, th('git.noRepo', lang), html), true);
|
|
174
|
+
const opts = h.gitOpts(st, project, repo);
|
|
175
|
+
const name = await branchName(text, { cwd: project, ...opts });
|
|
176
|
+
if (!name) {
|
|
177
|
+
st.pendingInput = { ...h.wait, at: h.now }; // название не подошло — ждём другое
|
|
178
|
+
return (await say(st.to, t('git.br.badName', lang), { reply_markup: { inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] } }), true);
|
|
179
|
+
}
|
|
180
|
+
await createBranch(project, name, opts);
|
|
181
|
+
log('git: ветка создана:', st.userId, project, name);
|
|
182
|
+
const markup = { inline_keyboard: [[{ text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }, { text: t('btn.back', lang), callback_data: 'gt:v' }]] };
|
|
183
|
+
await say(st.to, th('git.br.created', lang, { name: hCode(name) }), { ...html, reply_markup: markup });
|
|
184
|
+
} catch (e) {
|
|
185
|
+
log('git: новая ветка:', e.message, '| пользователь', st.userId);
|
|
186
|
+
await say(st.to, failText(e, lang), html);
|
|
187
|
+
}
|
|
188
|
+
return true;
|
|
189
|
+
}
|
package/src/gitUi.mjs
CHANGED
|
@@ -6,6 +6,7 @@ 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
8
|
import { accountsOf, addCustomHost, findHost, hostFor, hosts as allHosts, identityOf, removeCustomHost, renameCustomHost } from './gitAccess.mjs';
|
|
9
|
+
import { REPO_ACTIONS, onBranchInput, onRepoCallback } from './gitRepoUi.mjs';
|
|
9
10
|
import { HostError, authConfig, customHost, fetchProfile, listRepos, missingScopes, probeHost, repoFolder, showRemote } from './gitHosts.mjs';
|
|
10
11
|
import { LOCALES, errText, t } from './i18n.mjs';
|
|
11
12
|
import { ROOT, folderName, insideRoot, isPersonalRoot, navStart } from './projects.mjs';
|
|
@@ -82,6 +83,8 @@ export async function gitView(st, lang = langOf(st.userId), { sync = false } = {
|
|
|
82
83
|
}
|
|
83
84
|
} else if (repo.host) lines.push(th('git.needAccount', lang, { host: repo.host.label }));
|
|
84
85
|
else lines.push(th(s.remote ? 'git.foreign' : 'git.noRemote', lang));
|
|
86
|
+
// что изменено и какие есть ветки — можно смотреть без агента и без аккаунта
|
|
87
|
+
rows.push([{ text: t('git.changesBtn', lang), callback_data: 'gt:ch:0' }, { text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }]);
|
|
85
88
|
} else lines.push(th('git.noRepo', lang));
|
|
86
89
|
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
90
|
if (accounts.length && canCreateProject(st.userId)) rows.push([{ text: t('git.clone', lang), callback_data: 'gt:cl' }]);
|
|
@@ -261,6 +264,8 @@ export async function onGitCallback(st, cb) {
|
|
|
261
264
|
await ack();
|
|
262
265
|
return edit(hostsView(lang, th('git.hosts.deleted', lang, { label: own.label, n: n ?? 0 })));
|
|
263
266
|
}
|
|
267
|
+
// экраны «Изменения» и «Ветки» — gitRepoUi
|
|
268
|
+
if (REPO_ACTIONS.includes(action)) return onRepoCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), repoOf, gitOpts });
|
|
264
269
|
const host = findHost(arg);
|
|
265
270
|
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
266
271
|
try {
|
|
@@ -354,7 +359,7 @@ const dropMessage = (st, messageId) => (messageId ? tg('deleteMessage', { chat_i
|
|
|
354
359
|
*/
|
|
355
360
|
export async function onGitInput(st, text, { messageId, now = Date.now() } = {}) {
|
|
356
361
|
const wait = st.pendingInput;
|
|
357
|
-
if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName'].includes(wait?.kind)) return false;
|
|
362
|
+
if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName', 'gitBranch'].includes(wait?.kind)) return false;
|
|
358
363
|
const lang = langOf(st.userId);
|
|
359
364
|
const expired = now - wait.at > GIT_WAIT_MS;
|
|
360
365
|
const send = (v) => tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('git:', e.message));
|
|
@@ -394,6 +399,7 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
|
|
|
394
399
|
|
|
395
400
|
st.pendingInput = null;
|
|
396
401
|
if (expired) return false; // адрес сервера, строка поиска и описание изменений — не секреты: позже это обычный запрос агенту
|
|
402
|
+
if (wait.kind === 'gitBranch') return onBranchInput(st, text, { wait, now, lang, project: projectOf(st), repoOf, gitOpts });
|
|
397
403
|
// свои серверы: адрес нового сервера или новое название — только от администратора
|
|
398
404
|
if (wait.kind === 'gitHostUrl' || wait.kind === 'gitHostName') {
|
|
399
405
|
if (!isAdmin(st.userId)) return false;
|
package/src/i18n.mjs
CHANGED
|
@@ -357,6 +357,31 @@ const M = {
|
|
|
357
357
|
'git.hosts.nameAsk': { en: "Send the server name for the buttons (up to 40 characters).", ru: "Отправьте название сервера для кнопок (до 40 символов).", uk: "Надішліть назву сервера для кнопок (до 40 символів)." },
|
|
358
358
|
'git.hosts.deleteAsk': { en: "Remove the server {label}? The accounts of all users connected to it will be disconnected and their tokens deleted.", ru: "Убрать сервер {label}? Подключённые к нему аккаунты всех пользователей будут отключены, их токены удалены.", uk: "Прибрати сервер {label}? Підключені до нього акаунти всіх користувачів буде відключено, їхні токени видалено." },
|
|
359
359
|
'git.hosts.deleted': { en: "✅ The server {label} was removed, accounts disconnected: {n}.", ru: "✅ Сервер {label} убран, отключено аккаунтов: {n}.", uk: "✅ Сервер {label} прибрано, відключено акаунтів: {n}." },
|
|
360
|
+
'git.changesBtn': { en: "📋 Changes", ru: "📋 Изменения", uk: "📋 Зміни" },
|
|
361
|
+
'git.branchesBtn': { en: "🌿 Branches", ru: "🌿 Ветки", uk: "🌿 Гілки" },
|
|
362
|
+
'git.ch.head': { en: "📋 Changes in the project {p}\nBranch: {branch}", ru: "📋 Изменения в проекте {p}\nВетка: {branch}", uk: "📋 Зміни в проєкті {p}\nГілка: {branch}" },
|
|
363
|
+
'git.ch.sum': { en: "Changed files: {n} · lines added: {a} · removed: {d}\nPress a file to see what changed in it.", ru: "Изменено файлов: {n} · добавлено строк: {a} · убрано: {d}\nНажмите на файл, чтобы увидеть, что в нём изменилось.", uk: "Змінено файлів: {n} · додано рядків: {a} · прибрано: {d}\nНатисніть на файл, щоб побачити, що в ньому змінилося." },
|
|
364
|
+
'git.ch.cut': { en: "The first {n} files are shown.", ru: "Показаны первые {n} файлов.", uk: "Показано перші {n} файлів." },
|
|
365
|
+
'git.ch.none': { en: "There are no unsaved changes: the files match the last commit.", ru: "Несохранённых изменений нет: файлы совпадают с последним коммитом.", uk: "Незбережених змін немає: файли збігаються з останнім комітом." },
|
|
366
|
+
'git.ch.out': { en: "⬆️ Not pushed: {n}", ru: "⬆️ Не отправлено: {n}", uk: "⬆️ Не надіслано: {n}" },
|
|
367
|
+
'git.ch.in': { en: "⬇️ Waiting on the server: {n}", ru: "⬇️ Ждёт на сервере: {n}", uk: "⬇️ Чекає на сервері: {n}" },
|
|
368
|
+
'git.ch.local': { en: "⬆️ Commits of this branch", ru: "⬆️ Коммиты этой ветки", uk: "⬆️ Коміти цієї гілки" },
|
|
369
|
+
'git.ch.back': { en: "← To the changes", ru: "← К изменениям", uk: "← До змін" },
|
|
370
|
+
'git.diff.secret': { en: "🔒 {path} is a file with secrets — its contents are not shown here.", ru: "🔒 {path} — файл с секретами, его содержимое здесь не показывается.", uk: "🔒 {path} — файл із секретами, його вміст тут не показується." },
|
|
371
|
+
'git.diff.empty': { en: "No differences in the contents.", ru: "Различий в содержимом нет.", uk: "Відмінностей у вмісті немає." },
|
|
372
|
+
'git.diff.sent': { en: "📎 The changes in {path} are large — sent as a file.", ru: "📎 Изменения в файле {path} большие — отправил их файлом.", uk: "📎 Зміни у файлі {path} великі — надіслав їх файлом." },
|
|
373
|
+
'git.diff.gone': { en: "The list of changes is outdated — open it again.", ru: "Список изменений устарел — откройте его заново.", uk: "Список змін застарів — відкрийте його знову." },
|
|
374
|
+
'git.cm.out': { en: "⬆️ Commits that are not on the server yet: {n}", ru: "⬆️ Коммиты, которых ещё нет на сервере: {n}", uk: "⬆️ Коміти, яких ще немає на сервері: {n}" },
|
|
375
|
+
'git.cm.in': { en: "⬇️ Commits on the server that you do not have yet: {n}", ru: "⬇️ Коммиты на сервере, которых у вас ещё нет: {n}", uk: "⬇️ Коміти на сервері, яких у вас ще немає: {n}" },
|
|
376
|
+
'git.cm.none': { en: "(none)", ru: "(нет)", uk: "(немає)" },
|
|
377
|
+
'git.br.head': { en: "🌿 Branches\nCurrent: {branch}\n\n✓ — current, 🌿 — on this server, ☁️ — only on the Git server so far. Press a branch to switch to it.", ru: "🌿 Ветки\nТекущая: {branch}\n\n✓ — текущая, 🌿 — есть здесь, ☁️ — пока только на сервере Git. Нажмите на ветку, чтобы переключиться.", uk: "🌿 Гілки\nПоточна: {branch}\n\n✓ — поточна, 🌿 — є тут, ☁️ — поки лише на сервері Git. Натисніть на гілку, щоб перемкнутися." },
|
|
378
|
+
'git.br.new': { en: "➕ New branch", ru: "➕ Новая ветка", uk: "➕ Нова гілка" },
|
|
379
|
+
'git.br.nameAsk': { en: "🌿 Send the name of the new branch (Latin letters, digits, “-”, “_”, “/”). It is created from the current one — {branch}.", ru: "🌿 Отправьте название новой ветки (латиница, цифры, «-», «_», «/»). Она создаётся от текущей — {branch}.", uk: "🌿 Надішліть назву нової гілки (латиниця, цифри, «-», «_», «/»). Її буде створено від поточної — {branch}." },
|
|
380
|
+
'git.br.badName': { en: "⚠️ This branch name will not work. Send another one.", ru: "⚠️ Такое название ветки не подойдёт. Отправьте другое.", uk: "⚠️ Така назва гілки не підійде. Надішліть іншу." },
|
|
381
|
+
'git.br.created': { en: "✅ The branch {name} was created and selected. “Push” will create it on the server.", ru: "✅ Создана и выбрана ветка {name}. Кнопка «Отправить» создаст её на сервере.", uk: "✅ Створено й обрано гілку {name}. Кнопка «Надіслати» створить її на сервері." },
|
|
382
|
+
'git.br.switched': { en: "✅ You are on the branch {name}. The next request to the agent starts a new session.", ru: "✅ Вы на ветке {name}. Следующий запрос агенту начнёт новую сессию.", uk: "✅ Ви на гілці {name}. Наступний запит агенту почне нову сесію." },
|
|
383
|
+
'git.br.dirty': { en: "⚠️ The project has unsaved changes (files: {n}). Save them first — otherwise they would move to the branch {name} or get lost.", ru: "⚠️ В проекте есть несохранённые изменения (файлов: {n}). Сначала сохраните их — иначе они перейдут в ветку {name} или потеряются.", uk: "⚠️ У проєкті є незбережені зміни (файлів: {n}). Спочатку збережіть їх — інакше вони перейдуть у гілку {name} або загубляться." },
|
|
384
|
+
'git.br.same': { en: "You are already on this branch.", ru: "Вы уже на этой ветке.", uk: "Ви вже на цій гілці." },
|
|
360
385
|
'proj.notFound': { en: '⚠️ The folder was not found or is unavailable', ru: '⚠️ Папка не найдена или недоступна', uk: '⚠️ Папку не знайдено або вона недоступна' },
|
|
361
386
|
'proj.same': { en: '📁 Project already selected: {p}', ru: '📁 Проект уже выбран: {p}', uk: '📁 Проєкт уже обрано: {p}' },
|
|
362
387
|
'proj.set': { en: '📁 Project: {p}\nA new session starts with the next request.', ru: '📁 Проект: {p}\nНовая сессия начнётся со следующего запроса.', uk: '📁 Проєкт: {p}\nНова сесія почнеться з наступного запиту.' },
|