rob-revisited/ide/ui/js/vcs-setup.js

244 lines
19 KiB
JavaScript

// Version control of the project, in the interface: which one the IDE uses (Git, Subversion, none), where its repository lives (GitHub, GitLab,
// the JumPHP forge, Bitbucket, another URL, a Subversion URL), a test of the connection, and the "Source control" step of New Project.
// The commands are vcs.* (ide/src/Vcs/VcsCommands.php); secrets go through the Git credentials of the IDE, never into the project.
import { backend } from './backend.js';
import { el, clear, notify, confirm, dialog, t } from './ui.js';
import { HOSTS, hostOf, hostLabel, remoteUrl, serverName, urlProblem, stepSpec, stepProblem, stepNeedsHost } from './vcs-model.js';
const row = { display: 'flex', gap: '8px', alignItems: 'center', margin: '6px 0', flexWrap: 'wrap' };
/** The project changed its version control: its windows are built for the old one, so the project is opened again. */
async function reload(app, message) {
notify(message, 'success', { title: t('Version control') });
await app.editors?.saveAll?.(true);
setTimeout(() => location.reload(), 700);
}
const fail = (e) => notify(e.message || String(e), 'error', { title: t('Version control') });
/** The dialog behind the branch widget, the VCS menu and Settings: pick Git, Subversion or none, with what each one does. */
export async function openVcsSetup(app) {
const body = el('div');
dialog({ title: t('Version control'), wide: true, body, buttons: [{ label: 'Close' }] });
const draw = async () => {
let state;
try { state = await backend.invoke('vcs.state'); } catch (e) { clear(body).append(el('p.pub-faint', {}, e.message)); return; }
clear(body);
const current = state.kind === 'git' ? 'Git' : state.kind === 'svn' ? 'Subversion' : t('None');
body.append(el('p', {}, t('Choose what this project uses to keep its history. Nothing is ever deleted unless you tick it and confirm twice.')),
el('p', {}, el('b', {}, t('In use') + ': '), current, state.kind === 'git' && state.remotes[0] ? el('span.pub-faint', {}, ` · ${state.remotes[0].name} → ${t(hostLabel(state.remotes[0].host))}`) : null,
state.kind === 'svn' && state.svnUrl ? el('span.pub-faint', {}, ' · ' + state.svnUrl) : null));
const card = (title, active, text, ...buttons) => el('div', { style: { border: '1px solid var(--border)', borderRadius: '6px', padding: '10px 12px', margin: '8px 0', background: active ? 'var(--bg-2)' : '' } },
el('div', { style: { display: 'flex', alignItems: 'center', gap: '8px' } }, el('b', {}, title), active ? el('span.p-tag', {}, t('In use')) : null),
el('div.pub-faint', { style: { margin: '4px 0 8px' } }, text), el('div', { style: { display: 'flex', gap: '8px', flexWrap: 'wrap' } }, ...buttons.filter(Boolean)));
const act = (label, fn, cls = '') => el(`button.btn${cls}`, { onclick: async () => { try { await fn(); } catch (e) { fail(e); } } }, label);
body.append(
card('Git', state.kind === 'git', t('Local history and branches, with a remote on GitHub, GitLab, the JumPHP forge or any server.'),
!state.hasGit ? act(t('Initialise Git here'), async () => {
if (!(await confirm(t('Initialise Git here'), t('Creates a .git folder in this project (git init). Your files are not changed and nothing is committed.'), { ok: t('Initialise Git here') }))) return;
await backend.invoke('vcs.init');
await reload(app, t('Git is ready in this project.'));
}, '.primary') : null,
state.hasGit && state.kind !== 'git' ? act(t('Use Git'), async () => { await backend.invoke('vcs.use', { kind: 'git' }); await reload(app, t('The IDE now uses Git.')); }, '.primary') : null),
card(t('Subversion (SVN)'), state.kind === 'svn', t('A working copy of a Subversion repository: update, commit, log, revert. A checkout keeps the files of this folder as local changes: nothing is committed.'),
state.hasSvn && state.kind !== 'svn' ? act(t('Use Subversion'), async () => { await backend.invoke('vcs.use', { kind: 'svn' }); await reload(app, t('The IDE now uses Subversion.')); }, '.primary') : null,
!state.hasSvn ? act(t('Check out a repository…'), () => svnCheckout(app, state)) : null),
card(t('None'), state.kind === null, t('The IDE stops showing Git or Subversion for this project. The .git and .svn folders and the history stay where they are.'),
state.kind !== null ? act(t('Detach'), () => detach(app, state)) : null));
if (state.kind) body.append(el('div', { style: row }, el('b', {}, t('Where the repository lives')), el('span.pub-faint', {}, state.kind === 'git' ? (state.remotes.length ? state.remotes.map((r) => r.name).join(', ') : t('no remote yet')) : state.kind === 'svn' ? (state.svnUrl || '') : ''),
act(t('Remotes and hosting…'), () => openRemotes(app), '.primary')));
};
await draw();
}
/** Stops the IDE's integration; deleting the repository folders is a separate tick and a typed word. */
async function detach(app, state) {
const names = [state.hasGit ? '.git' : null, state.hasSvn || state.svnHere ? '.svn' : null].filter(Boolean).join(' + ');
const erase = el('input', { type: 'checkbox' });
const word = el('input.input', { placeholder: 'DELETE', style: { width: '120px' } });
const wordRow = el('div', { style: { ...row, display: 'none' } }, el('span', {}, t('Type DELETE to confirm deleting {names}: there is no way back.', { names })), word);
erase.addEventListener('change', () => { wordRow.style.display = erase.checked ? 'flex' : 'none'; });
const body = el('div', {}, el('p', {}, t('The IDE stops using {names} for this project. The files and the history stay on disk: you can use it again later.', { names })),
el('label.checkbox', { style: { color: 'var(--red)' } }, erase, ' ', t('Also delete the {names} folder (the history is lost for good)', { names })), wordRow);
await new Promise((resolve) => {
dialog({ title: t('Detach'), body, buttons: [{ label: 'Cancel' }, { label: 'Detach', primary: true, action: async () => {
if (erase.checked && word.value !== 'DELETE') { notify(t('Deleting needs the exact word DELETE.'), 'warning', { title: t('Version control') }); return false; }
const r = await backend.invoke('vcs.detach', erase.checked ? { delete: true, confirm: word.value } : {});
await reload(app, r.deleted?.length ? t('Detached: {names} deleted.', { names: r.deleted.join(' + ') }) : t('Detached: nothing was deleted.'));
} }], onClose: resolve });
});
}
/** svn checkout into the project's folder, after a test of the address and the explanation of what happens to the files. */
async function svnCheckout(app, state) {
const url = el('input.input', { placeholder: 'https://svn.example.org/repo/trunk', style: { flex: 1 } });
const result = el('div.pub-faint');
const body = el('div', {}, el('p', {}, t('Checks the repository out into this folder (svn checkout). The files already here stay and show as local changes: nothing is committed.') + (state.hasGit ? ' ' + t('The .git folder is kept, only set aside.') : '')),
el('div', { style: row }, url, el('button.btn', { onclick: () => testInto(result, url.value, 'svn', app) }, t('Test connection'))), result);
dialog({ title: t('Check out a repository…'), wide: true, body, buttons: [{ label: 'Cancel' }, { label: 'Check out', primary: true, action: async () => {
const problem = urlProblem(url.value, 'svn');
if (problem) { notify(t(problem), 'warning', { title: t('Version control') }); return false; }
const task = app.task?.(t('Checking out…'));
try {
await backend.invoke('vcs.svnCheckout', { url: url.value.trim() });
await reload(app, t('The IDE now uses Subversion.'));
} catch (e) { fail(e); return false; } finally { task?.(); }
} }] });
}
/** A line of result under a field: the connection works, or why not (with the way to add a token when it is a sign-in problem). */
async function testInto(node, url, vcs, app, host) {
clear(node).append(el('span.spinner'), ' ', t('Testing…'));
const problem = urlProblem(url, vcs);
if (problem) { clear(node).append(el('span', { style: { color: 'var(--red)' } }, t(problem))); return false; }
const r = await backend.invoke('vcs.testRemote', { url: url.trim(), vcs }).catch((e) => ({ ok: false, message: e.message }));
clear(node);
if (r.ok) { node.append(el('span', { style: { color: 'var(--green)' } }, '✓ ' + r.message + (r.branches?.length ? ' (' + r.branches.slice(0, 4).join(', ') + ')' : ''))); return true; }
node.append(el('span', { style: { color: 'var(--red)' } }, t('Connection failed: {message}', { message: (r.message || '').split('\n')[0].slice(0, 300) })),
r.auth ? el('button.btn.small', { style: { marginLeft: '8px' }, onclick: () => tokenDialog(app, host || hostOf(url.trim()), null) }, t('Add a token…')) : null);
return false;
}
/** The token of a host, asked in a password field and kept by the IDE (Git credentials) for that host only: never in the project. */
export function tokenDialog(app, host, tokenUrl) {
return new Promise((resolve) => {
const h = el('input.input', { value: host || '', placeholder: 'gitlab.com' });
const user = el('input.input', { placeholder: 'oauth2' });
const token = el('input.input', { type: 'password', placeholder: t('Token'), autocomplete: 'off' });
let saved = false;
dialog({ title: t('Access token for {host}', { host: host || '…' }), wide: true, onClose: () => resolve(saved),
body: el('div', {}, el('p', {}, t('A personal access token with the right to create and push repositories. It stays on this computer, in the IDE\'s settings, never in the project.')),
tokenUrl ? el('p', {}, el('a', { href: '#', onclick: (e) => { e.preventDefault(); app.openUrl(tokenUrl); } }, t('Create a token on {host}…', { host }))) : null,
el('label.field', {}, el('span', {}, t('Host')), h), el('label.field', {}, el('span', {}, t('User (optional)')), user), el('label.field', {}, el('span', {}, t('Token')), token)),
buttons: [{ label: 'Cancel' }, { label: 'Save', primary: true, action: async () => {
if (!h.value.trim() || !token.value.trim()) { notify(t('A host (e.g. gitlab.com) and a token are needed.'), 'warning', { title: t('Version control') }); return false; }
await backend.invoke('git.credentialSet', { host: h.value.trim(), user: user.value.trim(), token: token.value.trim() });
saved = true;
} }] });
});
}
/** Remotes and hosting: the repository's host (Git remotes, or the Subversion URL), change it, test it. */
export async function openRemotes(app) {
const body = el('div');
dialog({ title: t('Remotes and hosting'), wide: true, body, buttons: [{ label: 'Close' }] });
const draw = async () => {
const state = await backend.invoke('vcs.state').catch((e) => { clear(body).append(el('p.pub-faint', {}, e.message)); return null; });
if (!state) return;
clear(body);
if (state.kind === 'svn') return drawSvn(body, state, app, draw);
if (!state.hasGit) { body.append(el('p.pub-faint', {}, t('This project has no Git repository: choose Git first.'))); return; }
for (const r of state.remotes) {
const result = el('div.pub-faint', { style: { margin: '0 0 6px 0' } });
body.append(el('div', { style: row }, el('b', { style: { minWidth: '70px' } }, r.name), el('span.p-tag', {}, t(hostLabel(r.host))), el('span', { style: { flex: 1, wordBreak: 'break-all' } }, r.url),
el('button.btn.small', { onclick: () => testInto(result, r.url, 'git', app, r.hostName) }, t('Test connection')),
el('button.btn.small', { onclick: () => form(r) }, t('Change…')),
el('button.btn.small.danger', { onclick: async () => {
if (!(await confirm(t('Remove the remote'), t('Remove {name}? The repository on the server stays.', { name: r.name }), { ok: t('Remove'), danger: true }))) return;
await backend.invoke('vcs.remoteRemove', { name: r.name }).catch(fail);
draw();
} }, t('Remove'))), result);
}
if (!state.remotes.length) body.append(el('p.pub-faint', {}, t('No remote yet: nothing can be pushed. Pick a host below and save.')));
const slot = el('div', { style: { borderTop: '1px solid var(--border)', marginTop: '10px', paddingTop: '8px' } });
body.append(slot);
const form = (existing) => addForm(slot, existing, app, draw);
form(null);
};
await draw();
}
function drawSvn(body, state, app, draw) {
const result = el('div.pub-faint');
body.append(el('div', { style: row }, el('b', {}, t('Repository URL')), el('span', { style: { flex: 1, wordBreak: 'break-all' } }, state.svnUrl || '?'),
el('button.btn.small', { onclick: () => testInto(result, state.svnUrl || '', 'svn', app) }, t('Test connection')),
el('button.btn.small', { onclick: async () => {
const url = el('input.input', { value: state.svnUrl || '', style: { width: '100%' } });
dialog({ title: t('Change…'), body: el('div', {}, el('p', {}, t('Points the working copy at another address of the same repository (svn relocate).')), url),
buttons: [{ label: 'Cancel' }, { label: 'Save', primary: true, action: async () => {
const problem = urlProblem(url.value, 'svn');
if (problem) { notify(t(problem), 'warning', { title: t('Version control') }); return false; }
await backend.invoke('vcs.svnRelocate', { url: url.value.trim() }).catch((e) => { fail(e); return false; });
draw();
} }] });
} }, t('Change…'))), result);
}
/** Add a remote or change one: a host, owner and name (or the whole address), a test, then Save. */
function addForm(slot, existing, app, draw) {
clear(slot);
const name = el('input.input', { value: existing?.name || (existing === null ? 'origin' : ''), style: { width: '110px' }, disabled: !!existing });
const host = el('select.input', {}, ...HOSTS.map((h) => el('option', { value: h.id }, t(h.label))));
host.value = existing ? existing.host : 'forgejo';
const server = el('input.input', { placeholder: 'git.example.org', style: { width: '200px' } });
const owner = el('input.input', { placeholder: t('Owner (user or group)'), style: { width: '170px' } });
const repo = el('input.input', { placeholder: t('Repository name'), style: { width: '170px' } });
const url = el('input.input', { value: existing?.url || '', placeholder: 'https://… / git@…', style: { flex: 1, minWidth: '260px' } });
const result = el('div.pub-faint', { style: { margin: '6px 0' } });
const preview = () => {
const u = host.value === 'url' ? null : remoteUrl(host.value, owner.value, repo.value, server.value);
if (u) url.value = u;
};
const sync = () => { server.style.display = host.value === 'gitlab' ? '' : 'none'; owner.style.display = repo.style.display = host.value === 'url' ? 'none' : ''; };
host.onchange = () => { sync(); preview(); };
for (const i of [owner, repo, server]) i.oninput = preview;
sync();
slot.append(el('b', {}, existing ? t('Change the address of {name}', { name: existing.name }) : t('Add a remote')),
el('div', { style: row }, name, host, server, owner, repo), el('div', { style: row }, url),
result, el('div', { style: row },
el('button.btn', { onclick: () => testInto(result, url.value, 'git', app, host.value === 'gitlab' ? serverName(server.value) : HOSTS.find((h) => h.id === host.value)?.host) }, t('Test connection')),
el('button.btn', { onclick: () => { const h = HOSTS.find((x) => x.id === host.value); tokenDialog(app, host.value === 'gitlab' ? serverName(server.value) : h?.host, h?.tokenUrl); } }, t('Add a token…')),
el('button.btn.primary', { onclick: async () => {
const problem = urlProblem(url.value);
if (problem) { notify(t(problem), 'warning', { title: t('Version control') }); return; }
try { await backend.invoke('vcs.remoteSet', { name: name.value.trim() || 'origin', url: url.value.trim() }); } catch (e) { fail(e); return; }
notify(t('The remote is saved.'), 'success', { title: t('Version control') });
draw();
} }, t('Save'))));
}
/** The "Source control" step of New Project: a node to put in the form, and a function that checks it (token of the host) and gives what projects.create takes. */
export function sourceControlStep(app, getFolder, initial = {}) {
const form = { mode: 'git', host: 'forgejo', private: true, url: '', gitlabHost: '', ...initial };
const node = el('div', { style: { margin: '12px 0', padding: '10px 12px', border: '1px solid var(--border)', borderRadius: '6px' } });
const draw = () => {
clear(node);
const radio = (mode, label, hint, ...extra) => el('div', { style: { margin: '6px 0' } },
el('label.checkbox', {}, el('input', { type: 'radio', name: 'vcs-mode', checked: form.mode === mode, onchange: () => { form.mode = mode; draw(); } }), ' ', el('b', {}, label)),
hint ? el('div.pub-faint', { style: { marginLeft: '24px' } }, hint) : null, form.mode === mode ? el('div', { style: { margin: '6px 0 0 24px' } }, ...extra.filter(Boolean)) : null);
const host = el('select.input', {}, ...HOSTS.filter((h) => h.creates).map((h) => el('option', { value: h.id }, t(h.label))), el('option', { value: 'existing' }, t('An existing remote URL')));
host.value = form.host;
host.onchange = () => { form.host = host.value; draw(); };
const bind = (input, key) => { input.value = form[key] || ''; input.oninput = () => { form[key] = input.value; }; return input; };
node.append(el('b', {}, t('Source control')),
radio('git', t('Git, local only'), t('Nothing goes online until you want it.')),
radio('remote', t('Git and a repository on a host'), t('The repository is made empty, the project is pushed to it. The IDE needs a token for that host.'),
host, form.host === 'gitlab' ? bind(el('input.input', { placeholder: 'gitlab.com', style: { marginLeft: '8px', width: '200px' } }), 'gitlabHost') : null,
form.host === 'existing' ? el('div', { style: { marginTop: '6px' } }, bind(el('input.input', { placeholder: 'https://… / git@…', style: { width: '100%' } }), 'url'), el('div.pub-faint', {}, t('Only added as origin: nothing is pushed, the repository may not be empty.')))
: el('label.checkbox', { style: { marginLeft: '8px' } }, el('input', { type: 'checkbox', checked: form.private, onchange: (e) => { form.private = e.target.checked; } }), ' ', t('Private repository'))),
radio('svn', t('Subversion: check out an existing repository'), t('The files of the new project stay as local changes: nothing is committed.'),
bind(el('input.input', { placeholder: 'https://svn.example.org/repo/trunk', style: { width: '100%' } }), 'url')),
radio('none', t('No version control'), t('A plain folder: you can start Git later from the branch widget.')));
};
draw();
return {
node,
spec: () => stepSpec(form),
/** The step as projects.create takes it, or null when something is missing (said to the user); asks for the token the host needs. */
async validate() {
const spec = stepSpec(form);
const problem = stepProblem(spec);
if (problem) { notify(t(problem), 'warning', { title: t('Source control') }); return null; }
const need = stepNeedsHost(spec);
if (!need) return spec;
for (let tries = 0; tries < 2; tries++) {
const st = await backend.invoke('projects.vcsHost', { vcs: spec, folder: getFolder?.() || undefined }).catch((e) => { notify(e.message, 'error', { title: t('Source control') }); return null; });
if (!st) return null;
if (st.hasToken) return spec;
if (!(await tokenDialog(app, need.host, st.tokenUrl))) return null;
}
return null;
},
};
}