mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
refac
This commit is contained in:
1 parent
5e65d0a150
commit
fcc26371f9
12 files changed
+1382
-260
No files matched your search
@@ -3,6 +3,59 @@
|
||||
*/
|
||||
import { fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
export interface GitIdentity {
|
||||
name?: string;
|
||||
email?: string;
|
||||
name_source?: string;
|
||||
email_source?: string;
|
||||
}
|
||||
|
||||
export interface GhAccount {
|
||||
state?: string;
|
||||
active?: boolean;
|
||||
host?: string;
|
||||
login?: string;
|
||||
tokenSource?: string;
|
||||
scopes?: string;
|
||||
gitProtocol?: string;
|
||||
}
|
||||
|
||||
export interface GitSettingsConfig {
|
||||
root: string;
|
||||
git: {
|
||||
installed: boolean;
|
||||
version?: string | null;
|
||||
is_repo: boolean;
|
||||
identity?: GitIdentity;
|
||||
credential_helpers?: string[];
|
||||
remote_url?: string;
|
||||
};
|
||||
app_identity?: GitIdentity;
|
||||
gh: {
|
||||
installed: boolean;
|
||||
version?: string | null;
|
||||
hosts?: Record<string, GhAccount[]>;
|
||||
message?: string;
|
||||
};
|
||||
permissions: {
|
||||
can_manage_gh: boolean;
|
||||
can_manage_commit_model: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface GhLoginStatus {
|
||||
session_id: string;
|
||||
status: 'pending' | 'complete' | 'failed' | 'expired';
|
||||
verification_uri?: string;
|
||||
user_code?: string;
|
||||
auth?: GitSettingsConfig['gh'];
|
||||
}
|
||||
|
||||
export interface GitOperationResult {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// Deduplicate concurrent getGitStatus calls.
|
||||
// Multiple components (layout, GitBar, FileEditor × N) all fetch on mount;
|
||||
// this ensures they share a single in-flight request and a brief result cache.
|
||||
@@ -56,6 +109,29 @@ export const createGitWorktree = (root: string, branch: string, path?: string) =
|
||||
export const getGitStashes = (root: string) =>
|
||||
fetchJSON(`/api/git/stashes?root=${encodeURIComponent(root)}`);
|
||||
|
||||
export const getGitConfig = (root?: string) =>
|
||||
fetchJSON<GitSettingsConfig>(
|
||||
`/api/git/config${root ? `?root=${encodeURIComponent(root)}` : ''}`
|
||||
);
|
||||
|
||||
export const startGhLogin = (hostname = 'github.com', git_protocol = 'https') =>
|
||||
fetchJSON<GhLoginStatus>('/api/git/gh/login/start', jsonBody({ hostname, git_protocol }));
|
||||
|
||||
export const getGhLoginStatus = (session_id: string) =>
|
||||
fetchJSON<GhLoginStatus>('/api/git/gh/login/status', jsonBody({ session_id }));
|
||||
|
||||
export const cancelGhLogin = (session_id: string) =>
|
||||
fetchJSON('/api/git/gh/login/cancel', jsonBody({ session_id }));
|
||||
|
||||
export const ghLogout = (hostname = 'github.com', user?: string) =>
|
||||
fetchJSON('/api/git/gh/logout', jsonBody({ hostname, user }));
|
||||
|
||||
export const ghSwitch = (hostname: string, user: string) =>
|
||||
fetchJSON('/api/git/gh/switch', jsonBody({ hostname, user }));
|
||||
|
||||
export const ghSetupGit = (hostname = 'github.com') =>
|
||||
fetchJSON('/api/git/gh/setup-git', jsonBody({ hostname }));
|
||||
|
||||
export const stageFiles = (root: string, files: string[]) =>
|
||||
fetchJSON('/api/git/stage', jsonBody({ root, files }));
|
||||
|
||||
@@ -74,9 +150,11 @@ export const generateGitCommitMessage = (root: string, modelId?: string) =>
|
||||
jsonBody({ root, model_id: modelId || undefined })
|
||||
);
|
||||
|
||||
export const gitPull = (root: string) => fetchJSON('/api/git/pull', jsonBody({ root }));
|
||||
export const gitPull = (root: string) =>
|
||||
fetchJSON<GitOperationResult>('/api/git/pull', jsonBody({ root }));
|
||||
|
||||
export const gitFetch = (root: string) => fetchJSON('/api/git/fetch', jsonBody({ root }));
|
||||
export const gitFetch = (root: string) =>
|
||||
fetchJSON<GitOperationResult>('/api/git/fetch', jsonBody({ root }));
|
||||
|
||||
export const gitPush = (
|
||||
root: string,
|
||||
@@ -85,7 +163,7 @@ export const gitPush = (
|
||||
set_upstream = false,
|
||||
branch
|
||||
}: { force?: boolean; set_upstream?: boolean; branch?: string } = {}
|
||||
) => fetchJSON('/api/git/push', jsonBody({ root, force, set_upstream, branch }));
|
||||
) => fetchJSON<GitOperationResult>('/api/git/push', jsonBody({ root, force, set_upstream, branch }));
|
||||
|
||||
export const gitUncommit = (root: string) => fetchJSON('/api/git/uncommit', jsonBody({ root }));
|
||||
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { getAdminConfig, updateConfig } from '$lib/apis/admin';
|
||||
import { t } from '$lib/i18n';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ModelSelector from '$lib/components/common/ModelSelector.svelte';
|
||||
|
||||
let loading = $state(true);
|
||||
let saving = $state(false);
|
||||
let commitMessageModel = $state<string | null>(null);
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const config = await getAdminConfig();
|
||||
commitMessageModel =
|
||||
typeof config['git.commit_message_generation.model'] === 'string'
|
||||
? config['git.commit_message_generation.model']
|
||||
: null;
|
||||
} catch {
|
||||
toast.error($t('admin.failedToLoadConfig'));
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function save() {
|
||||
saving = true;
|
||||
try {
|
||||
await updateConfig({ 'git.commit_message_generation.model': commitMessageModel });
|
||||
toast.success($t('settings.saved'));
|
||||
} catch {
|
||||
toast.error($t('admin.failedToSave'));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8"><Spinner size={16} /></div>
|
||||
{:else}
|
||||
<div class="flex-1 min-h-0 overflow-y-auto scrollbar-hover pr-1.5 -mr-1.5">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">{$t('admin.git')}</h2>
|
||||
|
||||
<div>
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<span class="min-w-0 text-xs text-gray-600 dark:text-gray-400">
|
||||
{$t('admin.gitCommitMessageModel')}
|
||||
</span>
|
||||
<div class="shrink-0">
|
||||
<ModelSelector
|
||||
bind:selectedModel={commitMessageModel}
|
||||
nullable
|
||||
nullLabel={$t('modelSelector.defaultModel')}
|
||||
preferAbove={false}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
{$t('admin.gitCommitMessageModelHint')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 pt-3 flex justify-end">
|
||||
<button
|
||||
class="text-[0.8125rem] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-50"
|
||||
disabled={saving}
|
||||
onclick={save}
|
||||
>
|
||||
{saving ? $t('settings.saving') : $t('settings.save')}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -361,21 +361,26 @@
|
||||
async function doCommit() {
|
||||
if (!commitSummary.trim() || !stagedFiles.length) return;
|
||||
loading = true;
|
||||
await stageFiles(
|
||||
workspacePath,
|
||||
stagedFiles.map((f) => f.path)
|
||||
);
|
||||
const msg = commitDescription.trim()
|
||||
? `${commitSummary.trim()}\n\n${commitDescription.trim()}`
|
||||
: commitSummary.trim();
|
||||
await gitCommit(workspacePath, msg);
|
||||
commitSummary = '';
|
||||
commitDescription = '';
|
||||
flash($t('git.committed'));
|
||||
selectedFile = null;
|
||||
fileDiff = [];
|
||||
loading = false;
|
||||
await refresh();
|
||||
try {
|
||||
await stageFiles(
|
||||
workspacePath,
|
||||
stagedFiles.map((f) => f.path)
|
||||
);
|
||||
const msg = commitDescription.trim()
|
||||
? `${commitSummary.trim()}\n\n${commitDescription.trim()}`
|
||||
: commitSummary.trim();
|
||||
await gitCommit(workspacePath, msg);
|
||||
commitSummary = '';
|
||||
commitDescription = '';
|
||||
flash($t('git.committed'));
|
||||
selectedFile = null;
|
||||
fileDiff = [];
|
||||
} catch (e) {
|
||||
flash(e instanceof Error ? e.message : 'Commit failed');
|
||||
} finally {
|
||||
loading = false;
|
||||
await refresh();
|
||||
}
|
||||
}
|
||||
|
||||
async function generateCommitMessage() {
|
||||
@@ -407,10 +412,15 @@
|
||||
|
||||
async function doPull() {
|
||||
loading = true;
|
||||
const d = await gitPull(workspacePath);
|
||||
flash(d.ok ? $t('git.pulled') : d.message);
|
||||
loading = false;
|
||||
await refresh({ force: true });
|
||||
try {
|
||||
const d = await gitPull(workspacePath);
|
||||
flash(d.ok ? $t('git.pulled') : d.message);
|
||||
} catch (e) {
|
||||
flash(e instanceof Error ? e.message : 'Pull failed');
|
||||
} finally {
|
||||
loading = false;
|
||||
await refresh({ force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function doFetch() {
|
||||
@@ -431,13 +441,18 @@
|
||||
|
||||
async function doPush() {
|
||||
loading = true;
|
||||
const d = await gitPush(workspacePath, {
|
||||
set_upstream: needsPublish,
|
||||
branch: needsPublish ? gitStatus?.branch : undefined
|
||||
});
|
||||
flash(d.ok ? $t('git.pushed') : d.message);
|
||||
loading = false;
|
||||
await refresh({ force: true });
|
||||
try {
|
||||
const d = await gitPush(workspacePath, {
|
||||
set_upstream: needsPublish,
|
||||
branch: needsPublish ? gitStatus?.branch : undefined
|
||||
});
|
||||
flash(d.ok ? $t('git.pushed') : d.message);
|
||||
} catch (e) {
|
||||
flash(e instanceof Error ? e.message : 'Push failed');
|
||||
} finally {
|
||||
loading = false;
|
||||
await refresh({ force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function switchBranch(branch: string) {
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { activeWorkspace } from '$lib/stores';
|
||||
import { session } from '$lib/session';
|
||||
import { getAdminConfig, updateConfig } from '$lib/apis/admin';
|
||||
import { getPreferences, savePreferences } from '$lib/apis/state';
|
||||
import {
|
||||
cancelGhLogin,
|
||||
getGhLoginStatus,
|
||||
getGitConfig,
|
||||
ghLogout,
|
||||
ghSetupGit,
|
||||
ghSwitch,
|
||||
startGhLogin,
|
||||
type GhAccount,
|
||||
type GhLoginStatus,
|
||||
type GitIdentity,
|
||||
type GitSettingsConfig
|
||||
} from '$lib/apis/git';
|
||||
import { t } from '$lib/i18n';
|
||||
import Collapsible from '$lib/components/Collapsible.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ModelSelector from '$lib/components/common/ModelSelector.svelte';
|
||||
|
||||
let loading = $state(true);
|
||||
let saving = $state(false);
|
||||
let ghBusy = $state(false);
|
||||
let config = $state<GitSettingsConfig | null>(null);
|
||||
let gitName = $state('');
|
||||
let gitEmail = $state('');
|
||||
let commitMessageModel = $state<string | null>(null);
|
||||
let login = $state<GhLoginStatus | null>(null);
|
||||
let pollTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const workspacePath = $derived($activeWorkspace?.path ?? '');
|
||||
const isAdmin = $derived($session?.role === 'admin');
|
||||
const detectedIdentity = $derived(config?.git.identity ?? {});
|
||||
const identityComplete = $derived(Boolean(detectedIdentity.name && detectedIdentity.email));
|
||||
const ghHosts = $derived.by((): [string, GhAccount[]][] =>
|
||||
Object.entries((config?.gh.hosts ?? {}) as Record<string, GhAccount[]>)
|
||||
);
|
||||
const tr = (key: string) => (get(t) as (key: string) => string)(key);
|
||||
|
||||
onMount(load);
|
||||
onDestroy(() => {
|
||||
if (pollTimer) clearTimeout(pollTimer);
|
||||
});
|
||||
|
||||
async function load() {
|
||||
loading = true;
|
||||
try {
|
||||
const [nextConfig, prefs] = await Promise.all([
|
||||
getGitConfig(workspacePath || undefined),
|
||||
getPreferences()
|
||||
]);
|
||||
config = nextConfig;
|
||||
const gitPrefs = prefs.git && typeof prefs.git === 'object' ? prefs.git : {};
|
||||
const identity =
|
||||
'identity' in gitPrefs && typeof gitPrefs.identity === 'object' ? gitPrefs.identity : {};
|
||||
gitName =
|
||||
typeof (identity as Record<string, unknown>).name === 'string'
|
||||
? ((identity as Record<string, string>).name ?? '')
|
||||
: nextConfig.app_identity?.name || '';
|
||||
gitEmail =
|
||||
typeof (identity as Record<string, unknown>).email === 'string'
|
||||
? ((identity as Record<string, string>).email ?? '')
|
||||
: nextConfig.app_identity?.email || '';
|
||||
if (isAdmin) {
|
||||
const adminConfig = await getAdminConfig();
|
||||
commitMessageModel =
|
||||
typeof adminConfig['git.commit_message_generation.model'] === 'string'
|
||||
? adminConfig['git.commit_message_generation.model']
|
||||
: null;
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : tr('admin.failedToLoadConfig'));
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saving = true;
|
||||
try {
|
||||
await savePreferences({
|
||||
git: { identity: { name: gitName.trim(), email: gitEmail.trim() } }
|
||||
});
|
||||
if (isAdmin) {
|
||||
await updateConfig({ 'git.commit_message_generation.model': commitMessageModel });
|
||||
}
|
||||
toast.success(tr('settings.saved'));
|
||||
config = await getGitConfig(workspacePath || undefined);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : tr('admin.failedToSave'));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function beginLogin(hostname = 'github.com') {
|
||||
if (!config?.permissions.can_manage_gh) return;
|
||||
ghBusy = true;
|
||||
try {
|
||||
login = await startGhLogin(hostname);
|
||||
pollLogin();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'GitHub login failed');
|
||||
} finally {
|
||||
ghBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function pollLogin() {
|
||||
if (!login || login.status !== 'pending') return;
|
||||
if (pollTimer) clearTimeout(pollTimer);
|
||||
pollTimer = setTimeout(async () => {
|
||||
if (!login) return;
|
||||
try {
|
||||
login = await getGhLoginStatus(login.session_id);
|
||||
if (login.status === 'complete') {
|
||||
toast.success('GitHub signed in');
|
||||
config = await getGitConfig(workspacePath || undefined);
|
||||
return;
|
||||
}
|
||||
if (login.status === 'pending') pollLogin();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'GitHub login failed');
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async function cancelLogin() {
|
||||
if (!login) return;
|
||||
try {
|
||||
await cancelGhLogin(login.session_id);
|
||||
} catch {}
|
||||
login = null;
|
||||
}
|
||||
|
||||
async function runGhAction(action: () => Promise<unknown>) {
|
||||
ghBusy = true;
|
||||
try {
|
||||
await action();
|
||||
config = await getGitConfig(workspacePath || undefined);
|
||||
toast.success(tr('settings.saved'));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'GitHub CLI action failed');
|
||||
} finally {
|
||||
ghBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function activeAccount(accounts: GhAccount[]) {
|
||||
return accounts.find((account) => account.active) ?? accounts[0];
|
||||
}
|
||||
|
||||
function accountKey(account: GhAccount, index: number) {
|
||||
return account.login || account.host || String(index);
|
||||
}
|
||||
|
||||
function identityLabel(identity?: GitIdentity) {
|
||||
const name = identity?.name?.trim();
|
||||
const email = identity?.email?.trim();
|
||||
if (name && email) return `${name} <${email}>`;
|
||||
if (name) return name;
|
||||
if (email) return email;
|
||||
return 'Not configured';
|
||||
}
|
||||
|
||||
function identitySource(identity?: GitIdentity) {
|
||||
const sources = [identity?.name_source, identity?.email_source].filter(Boolean);
|
||||
return sources.length ? Array.from(new Set(sources)).join(' / ') : 'No git config found';
|
||||
}
|
||||
|
||||
function fallbackIdentityLabel() {
|
||||
return gitName || gitEmail ? identityLabel({ name: gitName, email: gitEmail }) : 'Not set';
|
||||
}
|
||||
|
||||
function ghSummary() {
|
||||
if (!config?.gh.installed) return 'Not installed';
|
||||
if (!ghHosts.length) return 'Not signed in';
|
||||
const [host, accounts] = ghHosts[0];
|
||||
const active = activeAccount(accounts);
|
||||
return active?.login ? `${active.login} on ${host}` : `Not signed in on ${host}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8"><Spinner size={16} /></div>
|
||||
{:else}
|
||||
<div class="flex-1 min-h-0 overflow-y-auto scrollbar-hover pr-1.5 -mr-1.5">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">{tr('admin.git')}</h2>
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2">Git</h3>
|
||||
<div class="border-y border-gray-100 dark:border-white/5">
|
||||
<div class="py-2.5 flex items-center justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs text-gray-700 dark:text-gray-300">Commit author</div>
|
||||
<div class="text-xs text-gray-700 dark:text-gray-300 truncate mt-0.5">
|
||||
{identityLabel(detectedIdentity)}
|
||||
</div>
|
||||
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600 truncate">
|
||||
{identitySource(detectedIdentity)}
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
class="shrink-0 text-[0.625rem] {identityComplete
|
||||
? 'text-gray-400 dark:text-gray-600'
|
||||
: 'text-amber-600 dark:text-amber-400'}"
|
||||
>
|
||||
{identityComplete ? 'Git config' : 'Needs identity'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<Collapsible title="Commit identity fallback" summary={fallbackIdentityLabel()}>
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
|
||||
<div>
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="git-user-name"
|
||||
>Name</label
|
||||
>
|
||||
<input
|
||||
id="git-user-name"
|
||||
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
placeholder="Jane Developer"
|
||||
bind:value={gitName}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="git-user-email"
|
||||
>Email</label
|
||||
>
|
||||
<input
|
||||
id="git-user-email"
|
||||
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
placeholder="jane@example.com"
|
||||
bind:value={gitEmail}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
Git config wins. This fallback only fills missing commit author details.
|
||||
</p>
|
||||
</div>
|
||||
</Collapsible>
|
||||
</div>
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">GitHub</h3>
|
||||
<div class="border-y border-gray-100 dark:border-white/5 divide-y divide-gray-100 dark:divide-white/5">
|
||||
<div class="py-2.5 flex items-center justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs text-gray-700 dark:text-gray-300">GitHub CLI</div>
|
||||
<div class="text-xs text-gray-700 dark:text-gray-300 truncate mt-0.5">
|
||||
{ghSummary()}
|
||||
</div>
|
||||
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600 truncate">
|
||||
{config?.gh.message || config?.gh.version || 'GitHub CLI'}
|
||||
</div>
|
||||
</div>
|
||||
{#if config?.gh.installed && !ghHosts.length && config.permissions.can_manage_gh}
|
||||
<button
|
||||
class="shrink-0 text-[0.6875rem] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-50"
|
||||
disabled={ghBusy}
|
||||
onclick={() => beginLogin()}
|
||||
>
|
||||
{ghBusy ? 'Starting...' : 'Sign in'}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if login}
|
||||
<div class="py-2.5 flex items-center justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs text-gray-700 dark:text-gray-300 truncate">
|
||||
{login.verification_uri || 'Waiting for GitHub CLI...'}
|
||||
</div>
|
||||
<div class="font-mono text-[0.8125rem] text-gray-900 dark:text-white">
|
||||
{login.user_code}
|
||||
</div>
|
||||
</div>
|
||||
<div class="shrink-0 flex gap-3">
|
||||
{#if login.verification_uri}
|
||||
<a
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
href={login.verification_uri}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer">Open</a
|
||||
>
|
||||
{/if}
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => navigator.clipboard.writeText(login?.user_code || '')}
|
||||
>Copy code</button
|
||||
>
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={cancelLogin}>Cancel</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<Collapsible title="Accounts and actions" summary={ghSummary()}>
|
||||
<div class="border-y border-gray-100 dark:border-white/5 divide-y divide-gray-100 dark:divide-white/5">
|
||||
{#if !config?.gh.installed}
|
||||
<div class="py-2.5 text-xs text-gray-700 dark:text-gray-300">
|
||||
{config?.gh.message || 'GitHub CLI is not installed.'}
|
||||
</div>
|
||||
{:else if ghHosts.length}
|
||||
{#each ghHosts as [host, accounts]}
|
||||
{@const active = activeAccount(accounts)}
|
||||
<div class="py-2.5 flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate text-xs text-gray-700 dark:text-gray-300">
|
||||
{active?.login || 'Not signed in'}
|
||||
</div>
|
||||
<div class="truncate text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{host} · {active?.state || 'unknown'} · {active?.gitProtocol || 'git'}
|
||||
</div>
|
||||
{#if accounts.length > 1}
|
||||
<div class="mt-1 flex flex-wrap gap-x-2 gap-y-1">
|
||||
{#each accounts as account, index (accountKey(account, index))}
|
||||
<span class="text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{account.login || 'unknown'}
|
||||
{#if account.active}
|
||||
(active)
|
||||
{:else if config.permissions.can_manage_gh && account.login}
|
||||
<button
|
||||
class="ml-1 text-gray-500 hover:text-gray-900 dark:hover:text-white"
|
||||
disabled={ghBusy}
|
||||
onclick={() =>
|
||||
runGhAction(() => ghSwitch(host, account.login as string))}
|
||||
>Switch</button
|
||||
>
|
||||
{/if}
|
||||
</span>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if config.permissions.can_manage_gh}
|
||||
<div class="shrink-0 flex flex-wrap justify-end gap-x-2 gap-y-1">
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
disabled={ghBusy}
|
||||
onclick={() => beginLogin(host)}>Add account</button
|
||||
>
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
disabled={ghBusy}
|
||||
onclick={() => runGhAction(() => ghSetupGit(host))}>Setup Git</button
|
||||
>
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
disabled={ghBusy}
|
||||
onclick={() => runGhAction(() => ghLogout(host, active?.login))}
|
||||
>Logout</button
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{:else}
|
||||
<div class="py-2.5 flex items-center justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs text-gray-700 dark:text-gray-300">
|
||||
{config.permissions.can_manage_gh ? 'Not signed in' : 'Managed by admin'}
|
||||
</div>
|
||||
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600 truncate">
|
||||
{config.gh.version}
|
||||
</div>
|
||||
</div>
|
||||
{#if config.permissions.can_manage_gh}
|
||||
<button
|
||||
class="shrink-0 text-[0.6875rem] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-50"
|
||||
disabled={ghBusy}
|
||||
onclick={() => beginLogin()}
|
||||
>
|
||||
{ghBusy ? 'Starting...' : 'Sign in'}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</Collapsible>
|
||||
</div>
|
||||
|
||||
{#if isAdmin}
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">
|
||||
{tr('sidebar.admin')}
|
||||
</h3>
|
||||
<div class="border-y border-gray-100 dark:border-white/5">
|
||||
<div class="py-2.5 flex items-center justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs text-gray-700 dark:text-gray-300">
|
||||
{tr('admin.gitCommitMessageModel')}
|
||||
</div>
|
||||
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600 truncate mt-0.5">
|
||||
{tr('admin.gitCommitMessageModelHint')}
|
||||
</div>
|
||||
</div>
|
||||
<div class="shrink-0">
|
||||
<ModelSelector
|
||||
bind:selectedModel={commitMessageModel}
|
||||
nullable
|
||||
nullLabel={tr('modelSelector.defaultModel')}
|
||||
preferAbove={false}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 pt-3 flex justify-end">
|
||||
<button
|
||||
class="text-[0.8125rem] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-50"
|
||||
disabled={saving}
|
||||
onclick={save}
|
||||
>
|
||||
{saving ? tr('settings.saving') : tr('settings.save')}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { onMount, untrack } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
import Icon from './Icon.svelte';
|
||||
import Modal from './Modal.svelte';
|
||||
import General from './Settings/General.svelte';
|
||||
@@ -16,7 +17,7 @@
|
||||
import Models from './Admin/Models.svelte';
|
||||
import Chat from './Admin/Chat.svelte';
|
||||
import Tools from './Admin/Tools.svelte';
|
||||
import Git from './Admin/Git.svelte';
|
||||
import Git from './Settings/Git.svelte';
|
||||
import Skills from './Admin/Skills.svelte';
|
||||
import Messaging from './Admin/Messaging.svelte';
|
||||
import Gateway from './Admin/Gateway.svelte';
|
||||
@@ -57,15 +58,53 @@
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
initialTab?: Tab;
|
||||
initialTab?: string;
|
||||
gitSettingsAvailable?: boolean;
|
||||
}
|
||||
|
||||
let { onclose, initialTab = 'general' }: Props = $props();
|
||||
let { onclose, initialTab = 'general', gitSettingsAvailable = false }: Props = $props();
|
||||
|
||||
let activeTab = $state<Tab>(untrack(() => (initialTab === 'pwa' ? 'general' : initialTab)));
|
||||
function normalizeTab(tab: string): Tab {
|
||||
const validTabs: Tab[] = [
|
||||
'general',
|
||||
'notifications',
|
||||
'appearance',
|
||||
'usage',
|
||||
'memory',
|
||||
'pwa',
|
||||
'keyboard',
|
||||
'account',
|
||||
'users',
|
||||
'connections',
|
||||
'agents',
|
||||
'models',
|
||||
'chat',
|
||||
'tools',
|
||||
'git',
|
||||
'skills',
|
||||
'messaging',
|
||||
'gateway',
|
||||
'audio',
|
||||
'images',
|
||||
'web',
|
||||
'toolservers',
|
||||
'subagents',
|
||||
'workspace'
|
||||
];
|
||||
return validTabs.includes(tab as Tab) ? (tab as Tab) : 'general';
|
||||
}
|
||||
|
||||
let activeTab = $state<Tab>(
|
||||
untrack(() =>
|
||||
initialTab === 'pwa' || (initialTab === 'git' && !gitSettingsAvailable)
|
||||
? 'general'
|
||||
: normalizeTab(initialTab)
|
||||
)
|
||||
);
|
||||
let showPwaSettings = $state(false);
|
||||
|
||||
const isAdmin = $derived($session?.role === 'admin');
|
||||
const tr = (key: string) => (get(t) as (key: string) => string)(key);
|
||||
|
||||
type SettingsTab = { id: Tab; label: string; icon: string };
|
||||
|
||||
@@ -76,7 +115,6 @@
|
||||
'models',
|
||||
'chat',
|
||||
'tools',
|
||||
'git',
|
||||
'messaging',
|
||||
'gateway',
|
||||
'audio',
|
||||
@@ -91,45 +129,51 @@
|
||||
|
||||
const personalTabs: SettingsTab[] = $derived.by(() => {
|
||||
const tabs: SettingsTab[] = [
|
||||
{ id: 'general', label: $t('settings.general'), icon: 'settings' },
|
||||
{ id: 'appearance', label: $t('settings.appearance'), icon: 'sun-light' },
|
||||
{ id: 'general', label: tr('settings.general'), icon: 'settings' },
|
||||
{ id: 'appearance', label: tr('settings.appearance'), icon: 'sun-light' },
|
||||
{ id: 'usage', label: 'Usage', icon: 'usage' },
|
||||
{ id: 'notifications', label: $t('general.notifications'), icon: 'chat-bubble' },
|
||||
{ id: 'keyboard', label: $t('settings.keyboard'), icon: 'terminal' },
|
||||
{ id: 'account', label: $t('settings.account'), icon: 'user' }
|
||||
{ id: 'notifications', label: tr('general.notifications'), icon: 'chat-bubble' },
|
||||
{ id: 'keyboard', label: tr('settings.keyboard'), icon: 'terminal' },
|
||||
{ id: 'account', label: tr('settings.account'), icon: 'user' }
|
||||
];
|
||||
if (gitSettingsAvailable)
|
||||
tabs.splice(tabs.length - 1, 0, { id: 'git', label: tr('admin.git'), icon: 'git-branch' });
|
||||
if (showPwaSettings) tabs.push({ id: 'pwa', label: 'PWA', icon: 'phone' });
|
||||
return tabs;
|
||||
});
|
||||
|
||||
const adminTabs: { id: Tab; label: string; icon: string }[] = $derived([
|
||||
{ id: 'users', label: $t('admin.users'), icon: 'user' },
|
||||
{ id: 'connections', label: $t('admin.connections'), icon: 'plug' },
|
||||
{ id: 'agents', label: $t('admin.agents'), icon: 'terminal' },
|
||||
{ id: 'models', label: $t('admin.models'), icon: 'cube' },
|
||||
{ id: 'chat', label: $t('admin.chat'), icon: 'chat-bubble' },
|
||||
{ id: 'tools', label: $t('admin.tools'), icon: 'tools' },
|
||||
{ id: 'git', label: $t('admin.git'), icon: 'git-branch' },
|
||||
{ id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' },
|
||||
{ id: 'gateway', label: $t('admin.gateway.tab'), icon: 'gateway' },
|
||||
{ id: 'audio', label: $t('admin.audio.title'), icon: 'microphone' },
|
||||
{ id: 'images', label: $t('admin.images.title'), icon: 'image' },
|
||||
{ id: 'web', label: $t('admin.web'), icon: 'globe' },
|
||||
{ id: 'toolservers', label: $t('admin.toolServers'), icon: 'plug' },
|
||||
{ id: 'subagents', label: $t('admin.subagents'), icon: 'user' },
|
||||
{ id: 'workspace', label: $t('admin.workspace'), icon: 'folder' },
|
||||
{ id: 'memory', label: $t('settings.memory'), icon: 'brain' },
|
||||
{ id: 'skills', label: $t('chat.skills'), icon: 'spark' }
|
||||
{ id: 'users', label: tr('admin.users'), icon: 'user' },
|
||||
{ id: 'connections', label: tr('admin.connections'), icon: 'plug' },
|
||||
{ id: 'agents', label: tr('admin.agents'), icon: 'terminal' },
|
||||
{ id: 'models', label: tr('admin.models'), icon: 'cube' },
|
||||
{ id: 'chat', label: tr('admin.chat'), icon: 'chat-bubble' },
|
||||
{ id: 'tools', label: tr('admin.tools'), icon: 'tools' },
|
||||
{ id: 'messaging', label: tr('admin.messaging'), icon: 'chat-bubble' },
|
||||
{ id: 'gateway', label: tr('admin.gateway.tab'), icon: 'gateway' },
|
||||
{ id: 'audio', label: tr('admin.audio.title'), icon: 'microphone' },
|
||||
{ id: 'images', label: tr('admin.images.title'), icon: 'image' },
|
||||
{ id: 'web', label: tr('admin.web'), icon: 'globe' },
|
||||
{ id: 'toolservers', label: tr('admin.toolServers'), icon: 'plug' },
|
||||
{ id: 'subagents', label: tr('admin.subagents'), icon: 'user' },
|
||||
{ id: 'workspace', label: tr('admin.workspace'), icon: 'folder' },
|
||||
{ id: 'memory', label: tr('settings.memory'), icon: 'brain' },
|
||||
{ id: 'skills', label: tr('chat.skills'), icon: 'spark' }
|
||||
]);
|
||||
|
||||
onMount(() => {
|
||||
showPwaSettings = isInstalledPwa();
|
||||
if (showPwaSettings && initialTab === 'pwa') {
|
||||
activeTab = 'pwa';
|
||||
} else if (!$session || ($session.role !== 'admin' && adminTabIds.includes(initialTab))) {
|
||||
} else if (
|
||||
!$session ||
|
||||
($session.role !== 'admin' && adminTabIds.includes(normalizeTab(initialTab)))
|
||||
) {
|
||||
activeTab = 'general';
|
||||
} else if (initialTab === 'git' && !gitSettingsAvailable) {
|
||||
activeTab = 'general';
|
||||
} else if (initialTab !== 'pwa') {
|
||||
activeTab = initialTab;
|
||||
activeTab = normalizeTab(initialTab);
|
||||
} else {
|
||||
activeTab = 'general';
|
||||
}
|
||||
@@ -158,7 +202,7 @@
|
||||
onclick={onclose}
|
||||
>
|
||||
<Icon name="chevron-left" size={12} />
|
||||
<span>{$t('settings.back')}</span>
|
||||
<span>{tr('settings.back')}</span>
|
||||
</button>
|
||||
|
||||
<!-- Personal -->
|
||||
@@ -179,7 +223,7 @@
|
||||
{#if isAdmin}
|
||||
<span
|
||||
class="hidden md:block text-[0.625rem] text-gray-400 dark:text-gray-600 px-2 mt-2 mb-0.5"
|
||||
>{$t('sidebar.admin')}</span
|
||||
>{tr('sidebar.admin')}</span
|
||||
>
|
||||
|
||||
{#each adminTabs as tab}
|
||||
|
||||
@@ -9,6 +9,11 @@
|
||||
import SystemInfoModal from './SystemInfoModal.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
gitSettingsAvailable?: boolean;
|
||||
}
|
||||
|
||||
let { gitSettingsAvailable = false }: Props = $props();
|
||||
let showPicker = $state(false);
|
||||
let showSettings = $state(false);
|
||||
let showSystemInfo = $state(false);
|
||||
@@ -90,6 +95,7 @@
|
||||
|
||||
{#if showSettings}
|
||||
<SettingsModal
|
||||
{gitSettingsAvailable}
|
||||
initialTab={settingsTab}
|
||||
onclose={() => {
|
||||
showSettings = false;
|
||||
|
||||
@@ -131,6 +131,12 @@ export interface UserPreferences {
|
||||
expandToolDetails?: boolean;
|
||||
homeGroup?: EditorGroup;
|
||||
homeState?: HomeState;
|
||||
git?: {
|
||||
identity?: {
|
||||
name?: string;
|
||||
email?: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
// ── ID generation ───────────────────────────────────────────────
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
import { setSession, clearSession, session } from '$lib/session';
|
||||
import { getSession, getConfig } from '$lib/apis/auth';
|
||||
import { fetchJSON } from '$lib/apis';
|
||||
import { getGitConfig } from '$lib/apis/git';
|
||||
import { gitStatusStore } from '$lib/stores/gitStatus.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import {
|
||||
@@ -55,6 +56,7 @@
|
||||
let showSettings = $state(false);
|
||||
let showUpdateToast = $state(false);
|
||||
let showSetup = $state(false);
|
||||
let gitSettingsAvailable = $state(false);
|
||||
let connectionToast: string | number | undefined;
|
||||
let applyingServiceWorkerUpdate = false;
|
||||
let lastGitRefreshFsTick = 0;
|
||||
@@ -185,6 +187,7 @@
|
||||
role: auth.role!,
|
||||
profile_image_url: auth.profile_image_url
|
||||
});
|
||||
await refreshGitSettingsAvailability();
|
||||
authState = 'authenticated';
|
||||
initState();
|
||||
refreshChatState();
|
||||
@@ -199,6 +202,7 @@
|
||||
authState = cfg.needs_setup ? 'needs_setup' : 'needs_login';
|
||||
}
|
||||
} catch {
|
||||
await refreshGitSettingsAvailability();
|
||||
authState = 'authenticated';
|
||||
initState();
|
||||
refreshChatState();
|
||||
@@ -218,6 +222,7 @@
|
||||
role: auth.role!,
|
||||
profile_image_url: auth.profile_image_url
|
||||
});
|
||||
await refreshGitSettingsAvailability();
|
||||
authState = 'authenticated';
|
||||
initState();
|
||||
refreshChatState();
|
||||
@@ -229,6 +234,14 @@
|
||||
authState = 'needs_login';
|
||||
}
|
||||
|
||||
async function refreshGitSettingsAvailability() {
|
||||
try {
|
||||
gitSettingsAvailable = (await getGitConfig()).git.installed;
|
||||
} catch {
|
||||
gitSettingsAvailable = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function checkForUpdates() {
|
||||
try {
|
||||
const sess = $session;
|
||||
@@ -461,7 +474,7 @@
|
||||
class="app-theme h-screen max-h-[100dvh] flex overflow-hidden font-sans antialiased text-gray-900 bg-white dark:text-gray-100 dark:bg-black"
|
||||
style="background: var(--app-bg); color: var(--app-fg);"
|
||||
>
|
||||
<Sidebar />
|
||||
<Sidebar gitSettingsAvailable={gitSettingsAvailable} />
|
||||
|
||||
<div
|
||||
id="main-col"
|
||||
@@ -484,7 +497,7 @@
|
||||
|
||||
<SearchModal onclose={() => showSearch.set(false)} />
|
||||
{#if showSettings}
|
||||
<SettingsModal onclose={() => (showSettings = false)} />
|
||||
<SettingsModal {gitSettingsAvailable} onclose={() => (showSettings = false)} />
|
||||
{/if}
|
||||
<ChangelogModal />
|
||||
{#if $updateAvailable && showUpdateToast}
|
||||
|
||||
+288
-55
@@ -11,7 +11,15 @@ from typing import List, Optional
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from cptr.models import UserStates
|
||||
from cptr.utils.ai import generate_text
|
||||
from cptr.utils.identity import (
|
||||
ExecutionIdentity,
|
||||
IdentityUnavailable,
|
||||
expand_user_path,
|
||||
identity_for_request,
|
||||
)
|
||||
from cptr.utils import gh
|
||||
from cptr.utils.json_parser import extract_json
|
||||
from cptr.utils.git import (
|
||||
GitError,
|
||||
@@ -23,7 +31,9 @@ from cptr.utils.git import (
|
||||
delete_branch,
|
||||
diff,
|
||||
discard,
|
||||
effective_config,
|
||||
fetch,
|
||||
version,
|
||||
is_repo,
|
||||
log,
|
||||
pull,
|
||||
@@ -48,30 +58,142 @@ def _handle_git_error(e: GitError) -> None:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
async def _require_repo(root: str) -> None:
|
||||
def _handle_gh_error(e: gh.GhError) -> None:
|
||||
status = 404 if e.returncode == 404 else 400
|
||||
raise HTTPException(status_code=status, detail=str(e))
|
||||
|
||||
|
||||
async def _identity(request: Request) -> ExecutionIdentity:
|
||||
try:
|
||||
return await identity_for_request(request)
|
||||
except IdentityUnavailable as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
|
||||
|
||||
|
||||
def _resolve_root(root: str | None, identity: ExecutionIdentity) -> str:
|
||||
return str(expand_user_path(root or identity.home, identity).resolve())
|
||||
|
||||
|
||||
async def _root_identity(request: Request, root: str | None) -> tuple[str, ExecutionIdentity]:
|
||||
identity = await _identity(request)
|
||||
return _resolve_root(root, identity), identity
|
||||
|
||||
|
||||
async def _require_repo(root: str, identity: ExecutionIdentity) -> None:
|
||||
"""Raise 400 if root is not a git repository."""
|
||||
if not await is_repo(root):
|
||||
if not await is_repo(root, identity):
|
||||
raise HTTPException(status_code=400, detail="Not a git repository")
|
||||
|
||||
|
||||
def _is_admin(request: Request) -> bool:
|
||||
auth = getattr(request.state, "auth", None)
|
||||
return bool(auth and getattr(auth, "role", None) == "admin")
|
||||
|
||||
|
||||
def _require_gh_mutation_allowed(request: Request, identity: ExecutionIdentity) -> None:
|
||||
if identity.is_pam or _is_admin(request):
|
||||
return
|
||||
raise HTTPException(status_code=403, detail="admin required")
|
||||
|
||||
|
||||
async def _user_git_identity(identity: ExecutionIdentity) -> dict[str, str]:
|
||||
if not identity.app_user_id:
|
||||
return {}
|
||||
prefs = await UserStates.get_data(identity.app_user_id)
|
||||
git_prefs = prefs.get("git") if isinstance(prefs, dict) else None
|
||||
ident = git_prefs.get("identity") if isinstance(git_prefs, dict) else None
|
||||
if not isinstance(ident, dict):
|
||||
return {}
|
||||
name = ident.get("name")
|
||||
email = ident.get("email")
|
||||
return {
|
||||
"name": name.strip() if isinstance(name, str) else "",
|
||||
"email": email.strip() if isinstance(email, str) else "",
|
||||
}
|
||||
|
||||
|
||||
async def _commit_author_env(root: str, identity: ExecutionIdentity) -> dict[str, str] | None:
|
||||
config = await effective_config(root, identity)
|
||||
git_identity = config.get("identity") or {}
|
||||
if git_identity.get("name") and git_identity.get("email"):
|
||||
return None
|
||||
fallback = await _user_git_identity(identity)
|
||||
name = str(git_identity.get("name") or fallback.get("name") or "").strip()
|
||||
email = str(git_identity.get("email") or fallback.get("email") or "").strip()
|
||||
if not name or not email:
|
||||
return None
|
||||
return {
|
||||
"GIT_AUTHOR_NAME": name,
|
||||
"GIT_AUTHOR_EMAIL": email,
|
||||
"GIT_COMMITTER_NAME": name,
|
||||
"GIT_COMMITTER_EMAIL": email,
|
||||
}
|
||||
|
||||
|
||||
# -- Query endpoints --
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def git_status(root: str):
|
||||
async def git_status(request: Request, root: str):
|
||||
"""Get branch info and changed files. Returns empty for non-git dirs."""
|
||||
if not await is_repo(root):
|
||||
root, identity = await _root_identity(request, root)
|
||||
if not await is_repo(root, identity):
|
||||
return {"is_repo": False, "branch": "", "ahead": 0, "behind": 0, "files": []}
|
||||
try:
|
||||
result = await status(root)
|
||||
result = await status(root, identity)
|
||||
result["is_repo"] = True
|
||||
return result
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.get("/config")
|
||||
async def git_config(request: Request, root: str | None = None):
|
||||
"""Get Git and gh settings data for the Settings UI."""
|
||||
root, identity = await _root_identity(request, root)
|
||||
git_version = await version(identity.home, identity)
|
||||
git_data: dict = {
|
||||
"installed": bool(git_version),
|
||||
"version": git_version,
|
||||
"is_repo": False,
|
||||
"identity": {},
|
||||
"credential_helpers": [],
|
||||
"remote_url": "",
|
||||
}
|
||||
if not git_version:
|
||||
return {
|
||||
"root": root,
|
||||
"git": git_data,
|
||||
"app_identity": await _user_git_identity(identity),
|
||||
"gh": {"installed": False, "version": None, "hosts": {}, "message": "Git is not installed."},
|
||||
"permissions": {
|
||||
"can_manage_gh": identity.is_pam or _is_admin(request),
|
||||
"can_manage_commit_model": _is_admin(request),
|
||||
},
|
||||
}
|
||||
if await is_repo(root, identity):
|
||||
git_data = {**git_data, "is_repo": True, **await effective_config(root, identity)}
|
||||
else:
|
||||
git_data = {**git_data, "is_repo": False, **await effective_config(identity.home, identity)}
|
||||
try:
|
||||
gh_status = await gh.auth_status(identity)
|
||||
except gh.GhError as e:
|
||||
gh_status = {"installed": False, "version": None, "hosts": {}, "message": str(e)}
|
||||
return {
|
||||
"root": root,
|
||||
"git": git_data,
|
||||
"app_identity": await _user_git_identity(identity),
|
||||
"gh": gh_status,
|
||||
"permissions": {
|
||||
"can_manage_gh": identity.is_pam or _is_admin(request),
|
||||
"can_manage_commit_model": _is_admin(request),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/diff")
|
||||
async def git_diff(
|
||||
request: Request,
|
||||
root: str,
|
||||
file: Optional[str] = None,
|
||||
staged: bool = False,
|
||||
@@ -79,59 +201,65 @@ async def git_diff(
|
||||
ignore_whitespace: bool = False,
|
||||
):
|
||||
"""Get diff for working tree or staged changes."""
|
||||
await _require_repo(root)
|
||||
root, identity = await _root_identity(request, root)
|
||||
await _require_repo(root, identity)
|
||||
try:
|
||||
return await diff(root, file, staged, untracked, ignore_whitespace)
|
||||
return await diff(root, file, staged, untracked, ignore_whitespace, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.get("/log")
|
||||
async def git_log(root: str, limit: int = 50, offset: int = 0):
|
||||
async def git_log(request: Request, root: str, limit: int = 50, offset: int = 0):
|
||||
"""Get commit history."""
|
||||
await _require_repo(root)
|
||||
root, identity = await _root_identity(request, root)
|
||||
await _require_repo(root, identity)
|
||||
try:
|
||||
return await log(root, limit, offset)
|
||||
return await log(root, limit, offset, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.get("/show")
|
||||
async def git_show(root: str, ref: str, ignore_whitespace: bool = False):
|
||||
async def git_show(request: Request, root: str, ref: str, ignore_whitespace: bool = False):
|
||||
"""Show a single commit with its diff."""
|
||||
await _require_repo(root)
|
||||
root, identity = await _root_identity(request, root)
|
||||
await _require_repo(root, identity)
|
||||
try:
|
||||
return await show(root, ref, ignore_whitespace)
|
||||
return await show(root, ref, ignore_whitespace, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.get("/branches")
|
||||
async def git_branches(root: str):
|
||||
async def git_branches(request: Request, root: str):
|
||||
"""List local and remote branches."""
|
||||
await _require_repo(root)
|
||||
root, identity = await _root_identity(request, root)
|
||||
await _require_repo(root, identity)
|
||||
try:
|
||||
return await branches(root)
|
||||
return await branches(root, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.get("/worktrees")
|
||||
async def git_worktrees(root: str):
|
||||
async def git_worktrees(request: Request, root: str):
|
||||
"""List git worktrees for the active repository."""
|
||||
await _require_repo(root)
|
||||
root, identity = await _root_identity(request, root)
|
||||
await _require_repo(root, identity)
|
||||
try:
|
||||
return await worktrees(root)
|
||||
return await worktrees(root, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.get("/stashes")
|
||||
async def git_stashes(root: str):
|
||||
async def git_stashes(request: Request, root: str):
|
||||
"""List stashes."""
|
||||
await _require_repo(root)
|
||||
root, identity = await _root_identity(request, root)
|
||||
await _require_repo(root, identity)
|
||||
try:
|
||||
return await stash_list(root)
|
||||
return await stash_list(root, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
@@ -225,41 +353,62 @@ class StashPopRequest(BaseModel):
|
||||
index: int = 0
|
||||
|
||||
|
||||
class GhLoginStartRequest(BaseModel):
|
||||
hostname: str = "github.com"
|
||||
git_protocol: str = "https"
|
||||
|
||||
|
||||
class GhLoginStatusRequest(BaseModel):
|
||||
session_id: str
|
||||
|
||||
|
||||
class GhHostRequest(BaseModel):
|
||||
hostname: str = "github.com"
|
||||
|
||||
|
||||
class GhUserHostRequest(GhHostRequest):
|
||||
user: Optional[str] = None
|
||||
|
||||
|
||||
@router.post("/stage")
|
||||
async def git_stage(body: StageRequest):
|
||||
async def git_stage(request: Request, body: StageRequest):
|
||||
"""Stage files for commit."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
await stage(body.root, body.files)
|
||||
await stage(root, body.files, identity)
|
||||
return {"ok": True}
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/unstage")
|
||||
async def git_unstage(body: StageRequest):
|
||||
async def git_unstage(request: Request, body: StageRequest):
|
||||
"""Unstage files."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
await unstage(body.root, body.files)
|
||||
await unstage(root, body.files, identity)
|
||||
return {"ok": True}
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/discard")
|
||||
async def git_discard(body: StageRequest):
|
||||
async def git_discard(request: Request, body: StageRequest):
|
||||
"""Discard unstaged changes."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
await discard(body.root, body.files)
|
||||
await discard(root, body.files, identity)
|
||||
return {"ok": True}
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/commit")
|
||||
async def git_commit(body: CommitRequest):
|
||||
async def git_commit(request: Request, body: CommitRequest):
|
||||
"""Create a commit."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
return await commit(body.root, body.message)
|
||||
return await commit(root, body.message, identity, await _commit_author_env(root, identity))
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
@@ -267,9 +416,10 @@ async def git_commit(body: CommitRequest):
|
||||
@router.post("/message")
|
||||
async def generate_commit_message(request: Request, body: CommitMessageRequest):
|
||||
"""Generate a commit summary and description from the staged diff."""
|
||||
await _require_repo(body.root)
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
await _require_repo(root, identity)
|
||||
try:
|
||||
patch = await staged_diff(body.root)
|
||||
patch = await staged_diff(root, identity=identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
if not patch:
|
||||
@@ -300,104 +450,187 @@ async def generate_commit_message(request: Request, body: CommitMessageRequest):
|
||||
|
||||
|
||||
@router.post("/checkout")
|
||||
async def git_checkout(body: CheckoutRequest):
|
||||
async def git_checkout(request: Request, body: CheckoutRequest):
|
||||
"""Switch branch."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
await checkout(body.root, body.branch)
|
||||
await checkout(root, body.branch, identity)
|
||||
return {"ok": True}
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/branch")
|
||||
async def git_create_branch(body: CreateBranchRequest):
|
||||
async def git_create_branch(request: Request, body: CreateBranchRequest):
|
||||
"""Create and switch to a new branch."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
await create_branch(body.root, body.name, body.from_ref)
|
||||
await create_branch(root, body.name, body.from_ref, identity)
|
||||
return {"ok": True}
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.delete("/branch")
|
||||
async def git_delete_branch(body: DeleteBranchRequest):
|
||||
async def git_delete_branch(request: Request, body: DeleteBranchRequest):
|
||||
"""Delete a local branch."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
await delete_branch(body.root, body.name)
|
||||
await delete_branch(root, body.name, identity)
|
||||
return {"ok": True}
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/worktrees")
|
||||
async def git_create_worktree(body: CreateWorktreeRequest):
|
||||
async def git_create_worktree(request: Request, body: CreateWorktreeRequest):
|
||||
"""Create a new branch-backed worktree."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
return await create_worktree(body.root, body.branch, body.path)
|
||||
return await create_worktree(root, body.branch, body.path, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.patch("/branch")
|
||||
async def git_rename_branch(body: RenameBranchRequest):
|
||||
async def git_rename_branch(request: Request, body: RenameBranchRequest):
|
||||
"""Rename a local branch."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
await rename_branch(body.root, body.old_name, body.new_name)
|
||||
await rename_branch(root, body.old_name, body.new_name, identity)
|
||||
return {"ok": True}
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/pull")
|
||||
async def git_pull(body: RootRequest):
|
||||
async def git_pull(request: Request, body: RootRequest):
|
||||
"""Pull from remote."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
return await pull(body.root)
|
||||
return await pull(root, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/fetch")
|
||||
async def git_fetch(body: RootRequest):
|
||||
async def git_fetch(request: Request, body: RootRequest):
|
||||
"""Fetch from remote without merging."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
return await fetch(body.root)
|
||||
return await fetch(root, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/push")
|
||||
async def git_push(body: PushRequest):
|
||||
async def git_push(request: Request, body: PushRequest):
|
||||
"""Push to remote."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
return await push(body.root, body.force, body.set_upstream, body.branch)
|
||||
return await push(root, body.force, body.set_upstream, body.branch, identity=identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/uncommit")
|
||||
async def git_uncommit(body: RootRequest):
|
||||
async def git_uncommit(request: Request, body: RootRequest):
|
||||
"""Undo the last commit, moving changes back to staging."""
|
||||
await _require_repo(body.root)
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
await _require_repo(root, identity)
|
||||
try:
|
||||
return await uncommit(body.root)
|
||||
return await uncommit(root, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/stash")
|
||||
async def git_stash(body: StashSaveRequest):
|
||||
async def git_stash(request: Request, body: StashSaveRequest):
|
||||
"""Stash changes."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
return await stash_save(body.root, body.message)
|
||||
return await stash_save(root, body.message, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/unstash")
|
||||
async def git_stash_pop(body: StashPopRequest):
|
||||
async def git_stash_pop(request: Request, body: StashPopRequest):
|
||||
"""Pop a stash."""
|
||||
root, identity = await _root_identity(request, body.root)
|
||||
try:
|
||||
return await stash_pop(body.root, body.index)
|
||||
return await stash_pop(root, body.index, identity)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/gh/login/start")
|
||||
async def gh_login_start(request: Request, body: GhLoginStartRequest):
|
||||
identity = await _identity(request)
|
||||
_require_gh_mutation_allowed(request, identity)
|
||||
try:
|
||||
return await gh.start_login(
|
||||
identity,
|
||||
hostname=body.hostname.strip() or "github.com",
|
||||
git_protocol=body.git_protocol if body.git_protocol in {"https", "ssh"} else "https",
|
||||
)
|
||||
except gh.GhError as e:
|
||||
_handle_gh_error(e)
|
||||
|
||||
|
||||
@router.post("/gh/login/status")
|
||||
async def gh_login_status(request: Request, body: GhLoginStatusRequest):
|
||||
identity = await _identity(request)
|
||||
try:
|
||||
result = gh.login_status(identity, body.session_id)
|
||||
if result["status"] == "complete":
|
||||
result["auth"] = await gh.auth_status(identity)
|
||||
return result
|
||||
except gh.GhError as e:
|
||||
_handle_gh_error(e)
|
||||
|
||||
|
||||
@router.post("/gh/login/cancel")
|
||||
async def gh_login_cancel(request: Request, body: GhLoginStatusRequest):
|
||||
identity = await _identity(request)
|
||||
_require_gh_mutation_allowed(request, identity)
|
||||
try:
|
||||
gh.cancel_login(identity, body.session_id)
|
||||
return {"ok": True}
|
||||
except gh.GhError as e:
|
||||
_handle_gh_error(e)
|
||||
|
||||
|
||||
@router.post("/gh/logout")
|
||||
async def gh_logout(request: Request, body: GhUserHostRequest):
|
||||
identity = await _identity(request)
|
||||
_require_gh_mutation_allowed(request, identity)
|
||||
try:
|
||||
await gh.logout(identity, body.hostname.strip() or "github.com", body.user)
|
||||
return {"ok": True, "auth": await gh.auth_status(identity)}
|
||||
except gh.GhError as e:
|
||||
_handle_gh_error(e)
|
||||
|
||||
|
||||
@router.post("/gh/switch")
|
||||
async def gh_switch(request: Request, body: GhUserHostRequest):
|
||||
identity = await _identity(request)
|
||||
_require_gh_mutation_allowed(request, identity)
|
||||
if not body.user:
|
||||
raise HTTPException(status_code=400, detail="user is required")
|
||||
try:
|
||||
await gh.switch(identity, body.hostname.strip() or "github.com", body.user)
|
||||
return {"ok": True, "auth": await gh.auth_status(identity)}
|
||||
except gh.GhError as e:
|
||||
_handle_gh_error(e)
|
||||
|
||||
|
||||
@router.post("/gh/setup-git")
|
||||
async def gh_setup_git(request: Request, body: GhHostRequest):
|
||||
identity = await _identity(request)
|
||||
_require_gh_mutation_allowed(request, identity)
|
||||
try:
|
||||
await gh.setup_git(identity, body.hostname.strip() or "github.com")
|
||||
return {"ok": True}
|
||||
except gh.GhError as e:
|
||||
_handle_gh_error(e)
|
||||
+12
-1
@@ -21,7 +21,18 @@ class AuditLevel(str, Enum):
|
||||
REQUEST_RESPONSE = "REQUEST_RESPONSE"
|
||||
|
||||
|
||||
_SENSITIVE_KEYS = {"password", "api_key", "token", "authorization", "cookie", "secret"}
|
||||
_SENSITIVE_KEYS = {
|
||||
"password",
|
||||
"api_key",
|
||||
"token",
|
||||
"authorization",
|
||||
"cookie",
|
||||
"secret",
|
||||
"device_code",
|
||||
"user_code",
|
||||
"verification_uri",
|
||||
"verification_uri_complete",
|
||||
}
|
||||
|
||||
|
||||
def _redact(value: Any) -> Any:
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
"""GitHub CLI operations via subprocess."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from cptr.utils.identity import ExecutionIdentity, env_for, preexec_for
|
||||
|
||||
|
||||
class GhError(Exception):
|
||||
def __init__(self, message: str, returncode: int = 1):
|
||||
super().__init__(message)
|
||||
self.returncode = returncode
|
||||
|
||||
|
||||
@dataclass
|
||||
class GhLoginSession:
|
||||
id: str
|
||||
owner_key: str
|
||||
proc: asyncio.subprocess.Process
|
||||
started_at: float
|
||||
verification_uri: str = ""
|
||||
user_code: str = ""
|
||||
output: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
_login_sessions: dict[str, GhLoginSession] = {}
|
||||
|
||||
|
||||
def _owner_key(identity: ExecutionIdentity) -> str:
|
||||
return f"{identity.app_user_id or ''}:{identity.username}:{identity.uid or ''}"
|
||||
|
||||
|
||||
def _gh_path() -> str | None:
|
||||
return shutil.which("gh")
|
||||
|
||||
|
||||
async def run_gh(
|
||||
args: list[str],
|
||||
*,
|
||||
identity: ExecutionIdentity,
|
||||
cwd: str | None = None,
|
||||
check: bool = True,
|
||||
timeout: float = 20,
|
||||
) -> tuple[int, str, str]:
|
||||
gh = _gh_path()
|
||||
if not gh:
|
||||
raise GhError("GitHub CLI is not installed")
|
||||
work_dir = cwd or identity.home
|
||||
env = env_for(identity, work_dir) if identity.is_pam else os.environ.copy()
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
gh,
|
||||
*args,
|
||||
cwd=work_dir,
|
||||
env=env,
|
||||
preexec_fn=preexec_for(identity) if identity.is_pam else None,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
stdout_bytes, stderr_bytes = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
||||
except asyncio.TimeoutError as exc:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
raise GhError("GitHub CLI command timed out") from exc
|
||||
stdout = stdout_bytes.decode("utf-8", errors="replace")
|
||||
stderr = stderr_bytes.decode("utf-8", errors="replace")
|
||||
if check and proc.returncode != 0:
|
||||
raise GhError((stderr or stdout).strip() or "GitHub CLI command failed", proc.returncode)
|
||||
return proc.returncode or 0, stdout, stderr
|
||||
|
||||
|
||||
async def version(identity: ExecutionIdentity) -> str | None:
|
||||
if not _gh_path():
|
||||
return None
|
||||
code, out, _ = await run_gh(["--version"], identity=identity, check=False, timeout=5)
|
||||
if code != 0:
|
||||
return None
|
||||
return out.splitlines()[0].strip() if out.strip() else None
|
||||
|
||||
|
||||
async def auth_status(identity: ExecutionIdentity, hostname: str | None = None) -> dict[str, Any]:
|
||||
gh_version = await version(identity)
|
||||
if gh_version is None:
|
||||
return {"installed": False, "version": None, "hosts": {}}
|
||||
args = ["auth", "status", "--json", "hosts"]
|
||||
if hostname:
|
||||
args.extend(["--hostname", hostname])
|
||||
code, out, err = await run_gh(args, identity=identity, check=False, timeout=10)
|
||||
if not out.strip():
|
||||
return {"installed": True, "version": gh_version, "hosts": {}, "message": err.strip()}
|
||||
try:
|
||||
data = json.loads(out)
|
||||
except json.JSONDecodeError:
|
||||
return {"installed": True, "version": gh_version, "hosts": {}, "message": err.strip()}
|
||||
return {"installed": True, "version": gh_version, "hosts": data.get("hosts") or {}}
|
||||
|
||||
|
||||
def parse_device_prompt(text: str) -> tuple[str, str]:
|
||||
uri_match = re.search(r"https://\S+/login/device\b", text)
|
||||
code_match = re.search(r"\b[A-Z0-9]{4}-[A-Z0-9]{4}\b", text)
|
||||
return (
|
||||
uri_match.group(0).rstrip(".,)") if uri_match else "",
|
||||
code_match.group(0) if code_match else "",
|
||||
)
|
||||
|
||||
|
||||
async def _read_login_stream(session: GhLoginSession, stream: asyncio.StreamReader | None) -> None:
|
||||
if stream is None:
|
||||
return
|
||||
while True:
|
||||
chunk = await stream.readline()
|
||||
if not chunk:
|
||||
return
|
||||
text = chunk.decode("utf-8", errors="replace")
|
||||
session.output.append(text)
|
||||
uri, code = parse_device_prompt("".join(session.output))
|
||||
if uri:
|
||||
session.verification_uri = uri
|
||||
if code:
|
||||
session.user_code = code
|
||||
|
||||
|
||||
async def start_login(
|
||||
identity: ExecutionIdentity,
|
||||
*,
|
||||
hostname: str = "github.com",
|
||||
git_protocol: str = "https",
|
||||
) -> dict[str, Any]:
|
||||
gh = _gh_path()
|
||||
if not gh:
|
||||
raise GhError("GitHub CLI is not installed")
|
||||
work_dir = identity.home
|
||||
env = env_for(identity, work_dir) if identity.is_pam else os.environ.copy()
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
gh,
|
||||
"auth",
|
||||
"login",
|
||||
"--web",
|
||||
"--hostname",
|
||||
hostname,
|
||||
"--git-protocol",
|
||||
git_protocol,
|
||||
cwd=work_dir,
|
||||
env=env,
|
||||
preexec_fn=preexec_for(identity) if identity.is_pam else None,
|
||||
stdin=asyncio.subprocess.DEVNULL,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
session = GhLoginSession(
|
||||
id=uuid.uuid4().hex,
|
||||
owner_key=_owner_key(identity),
|
||||
proc=proc,
|
||||
started_at=time.time(),
|
||||
)
|
||||
_login_sessions[session.id] = session
|
||||
asyncio.create_task(_read_login_stream(session, proc.stdout))
|
||||
asyncio.create_task(_read_login_stream(session, proc.stderr))
|
||||
|
||||
deadline = time.time() + 8
|
||||
while time.time() < deadline and proc.returncode is None:
|
||||
if session.verification_uri and session.user_code:
|
||||
break
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
if proc.returncode is not None and proc.returncode != 0:
|
||||
_login_sessions.pop(session.id, None)
|
||||
raise GhError("".join(session.output).strip() or "GitHub CLI login failed", proc.returncode)
|
||||
|
||||
return login_status(identity, session.id)
|
||||
|
||||
|
||||
def login_status(identity: ExecutionIdentity, session_id: str) -> dict[str, Any]:
|
||||
session = _login_sessions.get(session_id)
|
||||
if not session or session.owner_key != _owner_key(identity):
|
||||
raise GhError("Login session not found", 404)
|
||||
state = "pending"
|
||||
if session.proc.returncode == 0:
|
||||
state = "complete"
|
||||
_login_sessions.pop(session_id, None)
|
||||
elif session.proc.returncode is not None:
|
||||
state = "failed"
|
||||
_login_sessions.pop(session_id, None)
|
||||
elif time.time() - session.started_at > 900:
|
||||
session.proc.kill()
|
||||
state = "expired"
|
||||
_login_sessions.pop(session_id, None)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"status": state,
|
||||
"verification_uri": session.verification_uri,
|
||||
"user_code": session.user_code,
|
||||
}
|
||||
|
||||
|
||||
def cancel_login(identity: ExecutionIdentity, session_id: str) -> None:
|
||||
session = _login_sessions.get(session_id)
|
||||
if not session or session.owner_key != _owner_key(identity):
|
||||
raise GhError("Login session not found", 404)
|
||||
if session.proc.returncode is None:
|
||||
session.proc.kill()
|
||||
_login_sessions.pop(session_id, None)
|
||||
|
||||
|
||||
async def logout(identity: ExecutionIdentity, hostname: str, user: str | None = None) -> None:
|
||||
args = ["auth", "logout", "--hostname", hostname]
|
||||
if user:
|
||||
args.extend(["--user", user])
|
||||
await run_gh(args, identity=identity, timeout=15)
|
||||
|
||||
|
||||
async def switch(identity: ExecutionIdentity, hostname: str, user: str) -> None:
|
||||
await run_gh(["auth", "switch", "--hostname", hostname, "--user", user], identity=identity)
|
||||
|
||||
|
||||
async def setup_git(identity: ExecutionIdentity, hostname: str | None = None) -> None:
|
||||
args = ["auth", "setup-git"]
|
||||
if hostname:
|
||||
args.extend(["--hostname", hostname])
|
||||
await run_gh(args, identity=identity)
|
||||
+197
-65
@@ -11,23 +11,39 @@ import os
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from cptr.utils.identity import ExecutionIdentity, env_for, preexec_for
|
||||
|
||||
|
||||
async def _run(
|
||||
*args: str,
|
||||
cwd: str,
|
||||
check: bool = True,
|
||||
identity: ExecutionIdentity | None = None,
|
||||
extra_env: dict[str, str] | None = None,
|
||||
) -> tuple[int, str, str]:
|
||||
"""Run a git command and return (returncode, stdout, stderr)."""
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"git",
|
||||
"-c",
|
||||
"core.quotePath=false",
|
||||
*args,
|
||||
cwd=cwd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
env={**os.environ, "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C"},
|
||||
env_extra = {"GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C", **(extra_env or {})}
|
||||
env = (
|
||||
env_for(identity, cwd, env_extra)
|
||||
if identity and identity.is_pam
|
||||
else {**os.environ, **env_extra}
|
||||
)
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"git",
|
||||
"-c",
|
||||
"core.quotePath=false",
|
||||
*args,
|
||||
cwd=cwd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
env=env,
|
||||
preexec_fn=preexec_for(identity) if identity and identity.is_pam else None,
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
if exc.filename != "git":
|
||||
raise
|
||||
raise GitError("Git is not installed", 127) from exc
|
||||
stdout_bytes, stderr_bytes = await proc.communicate()
|
||||
stdout = stdout_bytes.decode("utf-8", errors="replace")
|
||||
stderr = stderr_bytes.decode("utf-8", errors="replace")
|
||||
@@ -44,25 +60,44 @@ class GitError(Exception):
|
||||
self.returncode = returncode
|
||||
|
||||
|
||||
async def is_repo(root: str) -> bool:
|
||||
async def is_repo(root: str, identity: ExecutionIdentity | None = None) -> bool:
|
||||
"""Check if directory is inside a git repo."""
|
||||
code, _, _ = await _run(
|
||||
"rev-parse",
|
||||
"--is-inside-work-tree",
|
||||
cwd=root,
|
||||
check=False,
|
||||
)
|
||||
try:
|
||||
code, _, _ = await _run(
|
||||
"rev-parse",
|
||||
"--is-inside-work-tree",
|
||||
cwd=root,
|
||||
check=False,
|
||||
identity=identity,
|
||||
)
|
||||
except GitError:
|
||||
return False
|
||||
return code == 0
|
||||
|
||||
|
||||
async def status(root: str) -> dict[str, Any]:
|
||||
async def version(root: str, identity: ExecutionIdentity | None = None) -> str | None:
|
||||
"""Return the installed git version, if git is available."""
|
||||
cwd = root if os.path.isdir(root) else "/"
|
||||
try:
|
||||
code, out, _ = await _run("--version", cwd=cwd, check=False, identity=identity)
|
||||
except GitError:
|
||||
return None
|
||||
return out.strip() if code == 0 else None
|
||||
|
||||
|
||||
async def status(root: str, identity: ExecutionIdentity | None = None) -> dict[str, Any]:
|
||||
"""Get repo status using porcelain v2 format."""
|
||||
# Refresh Git's cached file metadata first so status catches edits whose
|
||||
# filesystem stat information was stale.
|
||||
await _run("update-index", "-q", "--refresh", cwd=root, check=False)
|
||||
await _run("update-index", "-q", "--refresh", cwd=root, check=False, identity=identity)
|
||||
|
||||
_, out, _ = await _run(
|
||||
"status", "--porcelain=v2", "--branch", "--untracked-files=all", cwd=root
|
||||
"status",
|
||||
"--porcelain=v2",
|
||||
"--branch",
|
||||
"--untracked-files=all",
|
||||
cwd=root,
|
||||
identity=identity,
|
||||
)
|
||||
|
||||
branch = ""
|
||||
@@ -98,7 +133,9 @@ async def status(root: str) -> dict[str, Any]:
|
||||
entry["status"] = status_text
|
||||
|
||||
async def add_numstat(*args: str) -> None:
|
||||
code, numstat, _ = await _run("diff", "--numstat", *args, cwd=root, check=False)
|
||||
code, numstat, _ = await _run(
|
||||
"diff", "--numstat", *args, cwd=root, check=False, identity=identity
|
||||
)
|
||||
if code != 0:
|
||||
return
|
||||
for line in numstat.splitlines():
|
||||
@@ -168,7 +205,9 @@ async def status(root: str) -> dict[str, Any]:
|
||||
await add_numstat("--staged")
|
||||
|
||||
# Get remote URL for "View on GitHub/GitLab" link
|
||||
code, remote_out, _ = await _run("remote", "get-url", "origin", cwd=root, check=False)
|
||||
code, remote_out, _ = await _run(
|
||||
"remote", "get-url", "origin", cwd=root, check=False, identity=identity
|
||||
)
|
||||
remote_url = remote_out.strip() if code == 0 else ""
|
||||
|
||||
return {
|
||||
@@ -206,12 +245,61 @@ def _count_text_lines(path: str) -> int | None:
|
||||
return data.count(b"\n") + (0 if data.endswith(b"\n") else 1)
|
||||
|
||||
|
||||
async def _config_value(
|
||||
root: str,
|
||||
scope: str,
|
||||
key: str,
|
||||
identity: ExecutionIdentity | None = None,
|
||||
) -> str:
|
||||
code, out, _ = await _run(
|
||||
"config", scope, "--get", key, cwd=root, check=False, identity=identity
|
||||
)
|
||||
return out.strip() if code == 0 else ""
|
||||
|
||||
|
||||
async def _config_values(
|
||||
root: str,
|
||||
key: str,
|
||||
identity: ExecutionIdentity | None = None,
|
||||
) -> list[str]:
|
||||
code, out, _ = await _run(
|
||||
"config", "--get-all", key, cwd=root, check=False, identity=identity
|
||||
)
|
||||
if code != 0:
|
||||
return []
|
||||
return [line.strip() for line in out.splitlines() if line.strip()]
|
||||
|
||||
|
||||
async def effective_config(
|
||||
root: str, identity: ExecutionIdentity | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""Return the Git config fields the settings UI needs."""
|
||||
local_name = await _config_value(root, "--local", "user.name", identity)
|
||||
global_name = await _config_value(root, "--global", "user.name", identity)
|
||||
local_email = await _config_value(root, "--local", "user.email", identity)
|
||||
global_email = await _config_value(root, "--global", "user.email", identity)
|
||||
code, remote_out, _ = await _run(
|
||||
"remote", "get-url", "origin", cwd=root, check=False, identity=identity
|
||||
)
|
||||
return {
|
||||
"identity": {
|
||||
"name": local_name or global_name,
|
||||
"name_source": "local" if local_name else "global" if global_name else "",
|
||||
"email": local_email or global_email,
|
||||
"email_source": "local" if local_email else "global" if global_email else "",
|
||||
},
|
||||
"credential_helpers": await _config_values(root, "credential.helper", identity),
|
||||
"remote_url": remote_out.strip() if code == 0 else "",
|
||||
}
|
||||
|
||||
|
||||
async def diff(
|
||||
root: str,
|
||||
file: str | None = None,
|
||||
staged: bool = False,
|
||||
untracked: bool = False,
|
||||
ignore_whitespace: bool = False,
|
||||
identity: ExecutionIdentity | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Get diff output as structured data."""
|
||||
if untracked and file:
|
||||
@@ -221,7 +309,7 @@ async def diff(
|
||||
if ignore_whitespace:
|
||||
args.append("--ignore-all-space")
|
||||
args.extend(["--", null_device, file])
|
||||
_, out, _ = await _run(*args, cwd=root, check=False)
|
||||
_, out, _ = await _run(*args, cwd=root, check=False, identity=identity)
|
||||
return _parse_diff(out)
|
||||
|
||||
args = ["diff", "--unified=3"]
|
||||
@@ -232,13 +320,15 @@ async def diff(
|
||||
if file:
|
||||
args.extend(["--", file])
|
||||
|
||||
_, out, _ = await _run(*args, cwd=root)
|
||||
_, out, _ = await _run(*args, cwd=root, identity=identity)
|
||||
return _parse_diff(out)
|
||||
|
||||
|
||||
async def staged_diff(root: str, max_chars: int = 30000) -> str:
|
||||
async def staged_diff(
|
||||
root: str, max_chars: int = 30000, identity: ExecutionIdentity | None = None
|
||||
) -> str:
|
||||
"""Return the staged patch, capped for lightweight AI requests."""
|
||||
_, out, _ = await _run("diff", "--staged", "--unified=3", cwd=root)
|
||||
_, out, _ = await _run("diff", "--staged", "--unified=3", cwd=root, identity=identity)
|
||||
return out[:max_chars]
|
||||
|
||||
|
||||
@@ -282,21 +372,27 @@ def _parse_diff(raw: str) -> dict[str, Any]:
|
||||
return {"files": files}
|
||||
|
||||
|
||||
async def stage(root: str, files: list[str]) -> None:
|
||||
async def stage(
|
||||
root: str, files: list[str], identity: ExecutionIdentity | None = None
|
||||
) -> None:
|
||||
"""Stage files for commit."""
|
||||
if not files:
|
||||
return
|
||||
await _run("add", "--", *files, cwd=root)
|
||||
await _run("add", "--", *files, cwd=root, identity=identity)
|
||||
|
||||
|
||||
async def unstage(root: str, files: list[str]) -> None:
|
||||
async def unstage(
|
||||
root: str, files: list[str], identity: ExecutionIdentity | None = None
|
||||
) -> None:
|
||||
"""Unstage files."""
|
||||
if not files:
|
||||
return
|
||||
await _run("restore", "--staged", "--", *files, cwd=root)
|
||||
await _run("restore", "--staged", "--", *files, cwd=root, identity=identity)
|
||||
|
||||
|
||||
async def discard(root: str, files: list[str]) -> None:
|
||||
async def discard(
|
||||
root: str, files: list[str], identity: ExecutionIdentity | None = None
|
||||
) -> None:
|
||||
"""Fully discard all changes for files — both staged and unstaged.
|
||||
|
||||
Tracked modified/deleted files are unstaged then restored via checkout.
|
||||
@@ -314,6 +410,7 @@ async def discard(root: str, files: list[str]) -> None:
|
||||
"--untracked-files=all",
|
||||
cwd=root,
|
||||
check=False,
|
||||
identity=identity,
|
||||
)
|
||||
|
||||
to_unstage: list[str] = [] # staged changes that need unstaging first
|
||||
@@ -351,11 +448,11 @@ async def discard(root: str, files: list[str]) -> None:
|
||||
|
||||
# 1. Unstage any staged changes (reverts index to HEAD)
|
||||
if to_unstage:
|
||||
await _run("restore", "--staged", "--", *to_unstage, cwd=root)
|
||||
await _run("restore", "--staged", "--", *to_unstage, cwd=root, identity=identity)
|
||||
|
||||
# 2. Restore working-tree files from HEAD
|
||||
if to_checkout:
|
||||
await _run("checkout", "--", *to_checkout, cwd=root)
|
||||
await _run("checkout", "--", *to_checkout, cwd=root, identity=identity)
|
||||
|
||||
# 3. Remove untracked / newly-added files
|
||||
for f in to_delete:
|
||||
@@ -364,9 +461,14 @@ async def discard(root: str, files: list[str]) -> None:
|
||||
os.remove(full)
|
||||
|
||||
|
||||
async def commit(root: str, message: str) -> dict[str, str]:
|
||||
async def commit(
|
||||
root: str,
|
||||
message: str,
|
||||
identity: ExecutionIdentity | None = None,
|
||||
author_env: dict[str, str] | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Create a commit. Returns hash and message."""
|
||||
_, out, _ = await _run("commit", "-m", message, cwd=root)
|
||||
_, out, _ = await _run("commit", "-m", message, cwd=root, identity=identity, extra_env=author_env)
|
||||
# Parse "main abc1234] message"
|
||||
hash_short = ""
|
||||
for line in out.splitlines():
|
||||
@@ -383,6 +485,7 @@ async def log(
|
||||
root: str,
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
identity: ExecutionIdentity | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get commit log."""
|
||||
fmt = "%H%x00%h%x00%an%x00%aI%x00%s"
|
||||
@@ -394,6 +497,7 @@ async def log(
|
||||
"--no-merges",
|
||||
cwd=root,
|
||||
check=False,
|
||||
identity=identity,
|
||||
)
|
||||
|
||||
commits = []
|
||||
@@ -412,13 +516,18 @@ async def log(
|
||||
return commits
|
||||
|
||||
|
||||
async def show(root: str, ref: str, ignore_whitespace: bool = False) -> dict[str, Any]:
|
||||
async def show(
|
||||
root: str,
|
||||
ref: str,
|
||||
ignore_whitespace: bool = False,
|
||||
identity: ExecutionIdentity | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Show a commit's diff."""
|
||||
fmt = "%H%x00%h%x00%an%x00%aI%x00%s"
|
||||
args = ["show", ref, f"--format={fmt}", "--patch"]
|
||||
if ignore_whitespace:
|
||||
args.append("--ignore-all-space")
|
||||
_, out, _ = await _run(*args, cwd=root)
|
||||
_, out, _ = await _run(*args, cwd=root, identity=identity)
|
||||
|
||||
# First line is the formatted header, rest is diff
|
||||
lines = out.split("\n", 1)
|
||||
@@ -439,7 +548,7 @@ async def show(root: str, ref: str, ignore_whitespace: bool = False) -> dict[str
|
||||
return info
|
||||
|
||||
|
||||
async def branches(root: str) -> dict[str, Any]:
|
||||
async def branches(root: str, identity: ExecutionIdentity | None = None) -> dict[str, Any]:
|
||||
"""List branches."""
|
||||
# Local branches
|
||||
_, local_out, _ = await _run(
|
||||
@@ -447,6 +556,7 @@ async def branches(root: str) -> dict[str, Any]:
|
||||
"--format=%(refname:short)\t%(HEAD)",
|
||||
cwd=root,
|
||||
check=False,
|
||||
identity=identity,
|
||||
)
|
||||
# Remote branches
|
||||
_, remote_out, _ = await _run(
|
||||
@@ -455,6 +565,7 @@ async def branches(root: str) -> dict[str, Any]:
|
||||
"--format=%(refname:short)",
|
||||
cwd=root,
|
||||
check=False,
|
||||
identity=identity,
|
||||
)
|
||||
|
||||
current = ""
|
||||
@@ -550,11 +661,13 @@ def _parse_worktree_list(raw: str, current_root: str = "") -> list[dict[str, Any
|
||||
return worktrees
|
||||
|
||||
|
||||
async def worktrees(root: str) -> dict[str, Any]:
|
||||
async def worktrees(root: str, identity: ExecutionIdentity | None = None) -> dict[str, Any]:
|
||||
"""List worktrees for the current repository."""
|
||||
_, repo_root_out, _ = await _run("rev-parse", "--show-toplevel", cwd=root)
|
||||
_, repo_root_out, _ = await _run(
|
||||
"rev-parse", "--show-toplevel", cwd=root, identity=identity
|
||||
)
|
||||
repo_root = repo_root_out.strip() or root
|
||||
_, out, _ = await _run("worktree", "list", "--porcelain", cwd=root)
|
||||
_, out, _ = await _run("worktree", "list", "--porcelain", cwd=root, identity=identity)
|
||||
items = _parse_worktree_list(out, repo_root)
|
||||
|
||||
relpath = os.path.relpath(os.path.abspath(root), os.path.abspath(repo_root))
|
||||
@@ -578,51 +691,57 @@ async def create_worktree(
|
||||
root: str,
|
||||
branch: str,
|
||||
path: str | None = None,
|
||||
identity: ExecutionIdentity | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Create a new branch-backed worktree beside the current repository."""
|
||||
_, repo_root_out, _ = await _run("rev-parse", "--show-toplevel", cwd=root)
|
||||
_, repo_root_out, _ = await _run(
|
||||
"rev-parse", "--show-toplevel", cwd=root, identity=identity
|
||||
)
|
||||
repo_root = repo_root_out.strip() or root
|
||||
target_path = path or _worktree_path_for_branch(repo_root, branch)
|
||||
await _run("worktree", "add", "-b", branch, target_path, cwd=root)
|
||||
await _run("worktree", "add", "-b", branch, target_path, cwd=root, identity=identity)
|
||||
return {"path": target_path}
|
||||
|
||||
|
||||
async def checkout(root: str, branch: str) -> None:
|
||||
async def checkout(root: str, branch: str, identity: ExecutionIdentity | None = None) -> None:
|
||||
"""Switch branch."""
|
||||
await _run("checkout", branch, cwd=root)
|
||||
await _run("checkout", branch, cwd=root, identity=identity)
|
||||
|
||||
|
||||
async def create_branch(
|
||||
root: str,
|
||||
name: str,
|
||||
from_ref: str | None = None,
|
||||
identity: ExecutionIdentity | None = None,
|
||||
) -> None:
|
||||
"""Create and switch to a new branch."""
|
||||
args = ["checkout", "-b", name]
|
||||
if from_ref:
|
||||
args.append(from_ref)
|
||||
await _run(*args, cwd=root)
|
||||
await _run(*args, cwd=root, identity=identity)
|
||||
|
||||
|
||||
async def delete_branch(root: str, name: str) -> None:
|
||||
async def delete_branch(root: str, name: str, identity: ExecutionIdentity | None = None) -> None:
|
||||
"""Delete a local branch."""
|
||||
await _run("branch", "-d", name, cwd=root)
|
||||
await _run("branch", "-d", name, cwd=root, identity=identity)
|
||||
|
||||
|
||||
async def rename_branch(root: str, old_name: str, new_name: str) -> None:
|
||||
async def rename_branch(
|
||||
root: str, old_name: str, new_name: str, identity: ExecutionIdentity | None = None
|
||||
) -> None:
|
||||
"""Rename a local branch."""
|
||||
await _run("branch", "-m", old_name, new_name, cwd=root)
|
||||
await _run("branch", "-m", old_name, new_name, cwd=root, identity=identity)
|
||||
|
||||
|
||||
async def pull(root: str) -> dict[str, Any]:
|
||||
async def pull(root: str, identity: ExecutionIdentity | None = None) -> dict[str, Any]:
|
||||
"""Pull from remote."""
|
||||
code, out, err = await _run("pull", cwd=root, check=False)
|
||||
code, out, err = await _run("pull", cwd=root, check=False, identity=identity)
|
||||
return {"ok": code == 0, "message": (out + err).strip()}
|
||||
|
||||
|
||||
async def fetch(root: str) -> dict[str, Any]:
|
||||
async def fetch(root: str, identity: ExecutionIdentity | None = None) -> dict[str, Any]:
|
||||
"""Fetch remote refs without merging."""
|
||||
code, out, err = await _run("fetch", "--prune", cwd=root, check=False)
|
||||
code, out, err = await _run("fetch", "--prune", cwd=root, check=False, identity=identity)
|
||||
return {"ok": code == 0, "message": (out + err).strip()}
|
||||
|
||||
|
||||
@@ -632,6 +751,7 @@ async def push(
|
||||
set_upstream: bool = False,
|
||||
branch: str | None = None,
|
||||
remote: str = "origin",
|
||||
identity: ExecutionIdentity | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Push to remote. Use *set_upstream* for first-time branch publish."""
|
||||
args = ["push"]
|
||||
@@ -639,36 +759,42 @@ async def push(
|
||||
args.extend(["-u", remote, branch or "HEAD"])
|
||||
if force:
|
||||
args.append("--force-with-lease")
|
||||
code, out, err = await _run(*args, cwd=root, check=False)
|
||||
code, out, err = await _run(*args, cwd=root, check=False, identity=identity)
|
||||
return {"ok": code == 0, "message": (out + err).strip()}
|
||||
|
||||
|
||||
async def uncommit(root: str) -> dict[str, str]:
|
||||
async def uncommit(root: str, identity: ExecutionIdentity | None = None) -> dict[str, str]:
|
||||
"""Undo the last commit, moving its changes back to the staging area.
|
||||
|
||||
Uses ``git reset --soft HEAD~1``, or ``git update-ref -d HEAD`` for root
|
||||
commits (no parent).
|
||||
"""
|
||||
# Grab info about the commit we're about to undo
|
||||
_, log_out, _ = await _run("log", "-1", "--format=%H%x00%h%x00%s", cwd=root, check=False)
|
||||
_, log_out, _ = await _run(
|
||||
"log", "-1", "--format=%H%x00%h%x00%s", cwd=root, check=False, identity=identity
|
||||
)
|
||||
parts = log_out.strip().split("\x00")
|
||||
undone_hash = parts[1] if len(parts) >= 2 else ""
|
||||
undone_msg = parts[2] if len(parts) >= 3 else ""
|
||||
|
||||
# Check if HEAD~1 exists (root commits have no parent)
|
||||
code, _, _ = await _run("rev-parse", "--verify", "HEAD~1", cwd=root, check=False)
|
||||
code, _, _ = await _run(
|
||||
"rev-parse", "--verify", "HEAD~1", cwd=root, check=False, identity=identity
|
||||
)
|
||||
if code != 0:
|
||||
# Root commit: remove HEAD ref, keeps index (staged files) intact
|
||||
await _run("update-ref", "-d", "HEAD", cwd=root)
|
||||
await _run("update-ref", "-d", "HEAD", cwd=root, identity=identity)
|
||||
else:
|
||||
await _run("reset", "--soft", "HEAD~1", cwd=root)
|
||||
await _run("reset", "--soft", "HEAD~1", cwd=root, identity=identity)
|
||||
|
||||
return {"hash": undone_hash, "message": undone_msg}
|
||||
|
||||
|
||||
async def stash_list(root: str) -> list[dict[str, str]]:
|
||||
async def stash_list(root: str, identity: ExecutionIdentity | None = None) -> list[dict[str, str]]:
|
||||
"""List stashes."""
|
||||
_, out, _ = await _run("stash", "list", "--format=%gd%x00%s", cwd=root, check=False)
|
||||
_, out, _ = await _run(
|
||||
"stash", "list", "--format=%gd%x00%s", cwd=root, check=False, identity=identity
|
||||
)
|
||||
stashes = []
|
||||
for line in out.strip().splitlines():
|
||||
parts = line.split("\x00", 1)
|
||||
@@ -677,16 +803,22 @@ async def stash_list(root: str) -> list[dict[str, str]]:
|
||||
return stashes
|
||||
|
||||
|
||||
async def stash_save(root: str, message: str | None = None) -> dict[str, Any]:
|
||||
async def stash_save(
|
||||
root: str, message: str | None = None, identity: ExecutionIdentity | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""Stash changes."""
|
||||
args = ["stash", "push", "--include-untracked"]
|
||||
if message:
|
||||
args.extend(["-m", message])
|
||||
code, out, err = await _run(*args, cwd=root, check=False)
|
||||
code, out, err = await _run(*args, cwd=root, check=False, identity=identity)
|
||||
return {"ok": code == 0, "message": (out + err).strip()}
|
||||
|
||||
|
||||
async def stash_pop(root: str, index: int = 0) -> dict[str, Any]:
|
||||
async def stash_pop(
|
||||
root: str, index: int = 0, identity: ExecutionIdentity | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""Pop a stash."""
|
||||
code, out, err = await _run("stash", "pop", f"stash@{{{index}}}", cwd=root, check=False)
|
||||
code, out, err = await _run(
|
||||
"stash", "pop", f"stash@{{{index}}}", cwd=root, check=False, identity=identity
|
||||
)
|
||||
return {"ok": code == 0, "message": (out + err).strip()}
|
||||
Reference in new issue
Block a user