Make git identity configurable in settings

This commit is contained in:
Alex Gleason committed 2025-10-14 20:36:29 -05:00
1 parent 51f7a42d3e
commit e4c3fc8b05
13 files changed
+270 -108

No files matched your search

-4
View File
@@ -206,10 +206,6 @@ ${commitsToRevert.map(c => {
await git.commit({
dir: projectPath,
message: revertMessage,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
toast({
-4
View File
@@ -264,10 +264,6 @@ export function MergeDialog({
const mergeCommitOid = await git.commit({
dir: projectPath,
message: `Merge branch '${sourceBranch}' into ${currentBranch}`,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
parent: [targetOid, sourceOid], // Two parents for merge commit
tree: result.tree,
});
+3
View File
@@ -7,6 +7,9 @@ export interface GitCredential {
export interface GitSettings {
credentials: Record<string, GitCredential>; // keyed by origin
name?: string;
email?: string;
coAuthorEnabled?: boolean;
}
export interface GitSettingsContextType {
-12
View File
@@ -79,10 +79,6 @@ export class ProjectsManager {
await this.git.commit({
dir: project.path,
message: 'New project created with Shakespeare',
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
// Automatically request persistent storage after project creation
@@ -220,10 +216,6 @@ export class ProjectsManager {
await this.git.commit({
dir: projectPath,
message: `Overwrite project from ${zipFile.name}`,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
}
} catch {
@@ -249,10 +241,6 @@ export class ProjectsManager {
await this.git.commit({
dir: projectPath,
message: `Import project from ${zipFile.name}`,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
}
-27
View File
@@ -53,29 +53,6 @@ export class GitCommitCommand implements GitSubcommand {
return createErrorResult('nothing to commit, working tree clean');
}
// Get author info
const author = {
name: 'shakespeare.diy',
email: '[email protected]',
};
try {
const configName = await this.git.getConfig({
dir: this.pwd,
path: 'user.name',
});
const configEmail = await this.git.getConfig({
dir: this.pwd,
path: 'user.email',
});
if (configName) author.name = configName;
if (configEmail) author.email = configEmail;
} catch {
// Use defaults
}
let commitMessage = message;
if (options.amend) {
// Get the last commit message if amending
@@ -111,14 +88,10 @@ export class GitCommitCommand implements GitSubcommand {
const commitOptions: {
dir: string;
message: string;
author: { name: string; email: string };
committer: { name: string; email: string };
parent?: string[];
} = {
dir: this.pwd,
message: commitMessage || 'Empty commit',
author,
committer: author,
};
if (options.amend) {
+1
View File
@@ -164,6 +164,7 @@ describe('configUtils', () => {
expect(result).toEqual({
credentials: {},
coAuthorEnabled: true,
});
});
});
+4
View File
@@ -33,6 +33,9 @@ const gitCredentialSchema = z.object({
const gitSettingsSchema = z.object({
credentials: z.record(z.string(), gitCredentialSchema),
name: z.string().optional(),
email: z.string().optional(),
coAuthorEnabled: z.boolean().optional(),
});
/**
@@ -81,6 +84,7 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Pr
export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
const defaultSettings: GitSettings = {
credentials: {},
coAuthorEnabled: true,
};
// Try to read from VFS first
+131
View File
@@ -19,6 +19,9 @@ vi.mock('@nostrify/nostrify', () => ({
lookup: vi.fn(),
},
}));
vi.mock('./configUtils', () => ({
readGitSettings: vi.fn(),
}));
const mockGit = vi.mocked(git);
@@ -293,4 +296,132 @@ describe('Git', () => {
});
});
});
describe('commit with Git identity settings', () => {
beforeEach(() => {
mockGit.commit = vi.fn().mockResolvedValue('abc123');
});
it('uses shakespeare.diy as default author when no Git identity is configured', async () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
coAuthorEnabled: true,
});
await gitInstance.commit({
dir: '/test',
message: 'Test commit',
});
expect(mockGit.commit).toHaveBeenCalledWith({
fs,
dir: '/test',
message: 'Test commit',
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
committer: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
});
it('uses custom identity when both name and email are configured', async () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
name: 'John Doe',
email: '[email protected]',
coAuthorEnabled: true,
});
await gitInstance.commit({
dir: '/test',
message: 'Test commit',
});
expect(mockGit.commit).toHaveBeenCalledWith({
fs,
dir: '/test',
message: 'Test commit\n\nCo-authored-by: shakespeare.diy <[email protected]>',
author: {
name: 'John Doe',
email: '[email protected]',
},
committer: {
name: 'John Doe',
email: '[email protected]',
},
});
});
it('does not add co-author when coAuthorEnabled is false', async () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
name: 'John Doe',
email: '[email protected]',
coAuthorEnabled: false,
});
await gitInstance.commit({
dir: '/test',
message: 'Test commit',
});
expect(mockGit.commit).toHaveBeenCalledWith({
fs,
dir: '/test',
message: 'Test commit',
author: {
name: 'John Doe',
email: '[email protected]',
},
committer: {
name: 'John Doe',
email: '[email protected]',
},
});
});
it('respects provided author when explicitly passed', async () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
name: 'John Doe',
email: '[email protected]',
coAuthorEnabled: true,
});
await gitInstance.commit({
dir: '/test',
message: 'Test commit',
author: {
name: 'Custom Author',
email: '[email protected]',
},
committer: {
name: 'Custom Committer',
email: '[email protected]',
},
});
expect(mockGit.commit).toHaveBeenCalledWith({
fs,
dir: '/test',
message: 'Test commit',
author: {
name: 'Custom Author',
email: '[email protected]',
},
committer: {
name: 'Custom Committer',
email: '[email protected]',
},
});
});
});
});
+42
View File
@@ -2,6 +2,7 @@ import git, { GitHttpRequest, GitHttpResponse, HttpClient } from 'isomorphic-git
import { NIP05 } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { proxyUrl } from './proxyUrl';
import { readGitSettings } from './configUtils';
import type { NostrEvent, NostrSigner, NPool } from '@nostrify/nostrify';
import type { JSRuntimeFS } from './JSRuntime';
@@ -92,9 +93,50 @@ export class Git {
// Commits and history
async commit(options: Omit<Parameters<typeof git.commit>[0], 'fs'>) {
// If author is not provided, use Git identity settings
let author = options.author;
let committer = options.committer;
let message = options.message;
if (!author || !committer) {
// Read Git identity settings from config
const gitSettings = await readGitSettings(this.fs);
// Determine author based on Git identity settings
const defaultAuthor = {
name: 'shakespeare.diy',
email: '[email protected]',
};
const hasCustomIdentity = gitSettings.name && gitSettings.email;
if (hasCustomIdentity) {
const customAuthor = {
name: gitSettings.name!,
email: gitSettings.email!,
};
// Use custom identity
if (!author) author = customAuthor;
if (!committer) committer = customAuthor;
// Add Shakespeare as co-author if enabled
if (gitSettings.coAuthorEnabled ?? true) {
message = `${message}\n\nCo-authored-by: shakespeare.diy <[email protected]>`;
}
} else {
// Use Shakespeare as default author
if (!author) author = defaultAuthor;
if (!committer) committer = defaultAuthor;
}
}
return git.commit({
fs: this.fs,
...options,
author,
committer,
message,
});
}
+42
View File
@@ -72,6 +72,8 @@ const resources = {
add: 'Add',
remove: 'Remove',
retry: 'Retry',
name: 'Name',
email: 'Email',
// Shakespeare Main Page
buildNostrApps: 'Build apps with AI',
@@ -211,6 +213,11 @@ const resources = {
password: 'Password',
enterPassword: 'Enter your password/token',
credentialsExist: 'Credentials for this origin already exist',
gitIdentity: 'Git Identity',
gitName: 'Git Name',
gitEmail: 'Git Email',
coAuthoredByShakespeare: 'Co-authored by Shakespeare',
gitIdentityDescription: 'If both name and email are configured, they will be used as the commit author. Otherwise, shakespeare.diy will be used. When co-author is enabled, Shakespeare will be added as a co-author.',
// About Settings
aboutShakespeare: 'About Shakespeare',
@@ -385,6 +392,8 @@ const resources = {
add: 'Adicionar',
remove: 'Remover',
retry: 'Tentar novamente',
name: 'Nome',
email: 'Email',
// Shakespeare Main Page
buildNostrApps: 'Construa aplicativos com IA',
@@ -524,6 +533,11 @@ const resources = {
password: 'Senha',
enterPassword: 'Digite sua senha/token',
credentialsExist: 'Credenciais para esta origem já existem',
gitIdentity: 'Identidade Git',
gitName: 'Nome Git',
gitEmail: 'Email Git',
coAuthoredByShakespeare: 'Co-autoria de Shakespeare',
gitIdentityDescription: 'Se nome e email estiverem configurados, eles serão usados como autor do commit. Caso contrário, shakespeare.diy será usado. Quando co-autoria estiver ativada, Shakespeare será adicionado como co-autor.',
projectTemplate: 'Modelo de Projeto',
projectTemplateDescription: 'URL do repositório Git a ser usado como modelo inicial para novos projetos.',
corsProxy: 'Proxy CORS',
@@ -704,6 +718,8 @@ const resources = {
add: '添加',
remove: '移除',
retry: '重试',
name: '名称',
email: '邮箱',
// Shakespeare Main Page
buildNostrApps: '使用AI构建应用',
@@ -843,6 +859,11 @@ const resources = {
password: '密码',
enterPassword: '输入您的密码/令牌',
credentialsExist: '此源的凭据已存在',
gitIdentity: 'Git身份',
gitName: 'Git名称',
gitEmail: 'Git邮箱',
coAuthoredByShakespeare: 'Shakespeare共同作者',
gitIdentityDescription: '如果配置了名称和邮箱,它们将用作提交作者。否则,将使用shakespeare.diy。启用共同作者时,Shakespeare将被添加为共同作者。',
projectTemplate: '项目模板',
projectTemplateDescription: '用作新项目起始模板的Git仓库URL。',
corsProxy: 'CORS代理',
@@ -1023,6 +1044,8 @@ const resources = {
add: 'Ƙara',
remove: 'Cire',
retry: 'Sake gwadawa',
name: 'Suna',
email: 'Imel',
// Shakespeare Main Page
buildNostrApps: 'Gina aikace-aikace da AI',
@@ -1162,6 +1185,11 @@ const resources = {
password: 'Kalmar sirri',
enterPassword: 'Shigar da kalmar sirri/alamar ku',
credentialsExist: 'Bayanan shaidar wannan asali sun riga sun wanzu',
gitIdentity: 'Shaida Git',
gitName: 'Sunan Git',
gitEmail: 'Imel Git',
coAuthoredByShakespeare: 'Haɗin marubuta da Shakespeare',
gitIdentityDescription: 'Idan an saita suna da imel, za a yi amfani da su azaman marubucin aikin. In ba haka ba, za a yi amfani da shakespeare.diy. Lokacin da aka kunna haɗin marubuta, za a ƙara Shakespeare azaman haɗin marubuta.',
projectTemplate: 'Samfurin Aikin',
projectTemplateDescription: 'URL ɗin ma\'ajin Git da za a yi amfani da shi azaman samfurin farawa don sababbin ayyuka.',
corsProxy: 'CORS Proxy',
@@ -1342,6 +1370,8 @@ const resources = {
add: 'Fi kun',
remove: 'Yọ kuro',
retry: 'Tun gbiyanju',
name: 'Orukọ',
email: 'Imeeli',
// Shakespeare Main Page
buildNostrApps: 'Kọ awọn ohun elo pẹlu AI',
@@ -1481,6 +1511,11 @@ const resources = {
password: 'Ọrọ igbaniwọle',
enterPassword: 'Tẹ ọrọ igbaniwọle/token rẹ sinu',
credentialsExist: 'Awọn ẹri fun ipilẹṣẹ yii ti wa tẹlẹ',
gitIdentity: 'Idanimọ Git',
gitName: 'Orukọ Git',
gitEmail: 'Imeeli Git',
coAuthoredByShakespeare: 'Ajọpọ onkọwe pẹlu Shakespeare',
gitIdentityDescription: 'Ti a ba tunto orukọ ati imeeli, wọn yoo jẹ lilo bi onkọwe. Bibẹẹkọ, shakespeare.diy yoo jẹ lilo. Nigbati a ba mu ajọpọ onkọwe ṣiṣẹ, Shakespeare yoo jẹ fifikun bi ajọpọ onkọwe.',
projectTemplate: 'Awoṣe Iṣẹ akanṣe',
projectTemplateDescription: 'URL ibi ipamọ Git lati lo bi awoṣe ibẹrẹ fun awọn iṣẹ akanṣe tuntun.',
corsProxy: 'CORS Proxy',
@@ -1656,6 +1691,8 @@ const resources = {
add: 'Tinye',
remove: 'Wepụ',
retry: 'Nwaa ọzọ',
name: 'Aha',
email: 'Ozi-eletrọniki',
// Shakespeare Main Page
buildNostrApps: 'Wuo ngwa na AI',
@@ -1795,6 +1832,11 @@ const resources = {
password: 'Okwuntughe',
enterPassword: 'Tinye okwuntughe/token gị',
credentialsExist: 'Nzere maka mmalite a adịlarị',
gitIdentity: 'Njirimara Git',
gitName: 'Aha Git',
gitEmail: 'Ozi-eletrọniki Git',
coAuthoredByShakespeare: 'Ndekọ ọnụ na Shakespeare',
gitIdentityDescription: 'Ọ bụrụ na ahaziri aha na ozi-eletrọniki, a ga-eji ha dị ka onye dere ya. Ma ọ bụghị, a ga-eji shakespeare.diy. Mgbe emere ndekọ ọnụ, a ga-etinye Shakespeare dị ka ndekọ ọnụ.',
projectTemplate: 'Ụdịdị Ọrụ',
projectTemplateDescription: 'URL nchekwa Git iji mee ka ụdịdị mmalite maka ọrụ ọhụrụ.',
corsProxy: 'CORS Proxy',
-35
View File
@@ -75,14 +75,6 @@ describe('GitCommitTool', () => {
expect(mockGitInstance.commit).toHaveBeenCalledWith({
dir: '/test/project',
message: 'Add new feature',
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
committer: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
expect(result).toContain('✅ Successfully committed 2 files (abcd123)');
expect(result).toContain('Add new feature');
@@ -179,34 +171,7 @@ describe('GitCommitTool', () => {
expect(result).toContain('📊 Changes:');
});
it('should use git config when available', async () => {
// Mock .git directory exists
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock git config
vi.mocked(mockGitInstance.getConfig)
.mockResolvedValueOnce('John Doe') // user.name
.mockResolvedValueOnce('[email protected]'); // user.email
const result = await tool.execute({ message: 'Test commit' });
expect(mockGitInstance.commit).toHaveBeenCalledWith({
dir: '/test/project',
message: 'Test commit',
author: {
name: 'John Doe',
email: '[email protected]',
},
committer: {
name: 'John Doe',
email: '[email protected]',
},
});
expect(result).toContain('✅ Successfully committed');
});
it('should handle very long commit message', async () => {
// Mock .git directory exists
+1 -25
View File
@@ -89,34 +89,10 @@ export class GitCommitTool implements Tool<GitCommitParams> {
// Default to 'main' if we can't get the current branch
}
// Get author info (use default if not configured)
const author = {
name: 'shakespeare.diy',
email: '[email protected]',
};
// Try to get configured author from git config
try {
const configName = await this.git.getConfig({
dir: this.cwd,
path: 'user.name',
});
const configEmail = await this.git.getConfig({
dir: this.cwd,
path: 'user.email',
});
if (configName) author.name = configName;
if (configEmail) author.email = configEmail;
} catch {
// Use defaults if config is not set
}
// Commit the changes
// Commit the changes (author/committer will be set automatically by Git class)
const commitSha = await this.git.commit({
dir: this.cwd,
message: message.trim(),
author,
committer: author,
});
// Get short hash (first 7 characters)
+46 -1
View File
@@ -6,6 +6,7 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Switch } from '@/components/ui/switch';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
import { useIsMobile } from '@/hooks/useIsMobile';
@@ -40,7 +41,7 @@ const PRESET_PROVIDERS: PresetProvider[] = [
export function GitSettings() {
const { t } = useTranslation();
const { settings, addCredential, removeCredential, updateCredential } = useGitSettings();
const { settings, addCredential, removeCredential, updateCredential, updateSettings } = useGitSettings();
const { initiateOAuth, isLoading: isOAuthLoading, error: oauthError, isOAuthConfigured } = useGitHubOAuth();
const isMobile = useIsMobile();
const navigate = useNavigate();
@@ -375,6 +376,50 @@ export function GitSettings() {
</AccordionItem>
</Accordion>
</div>
{/* Git Identity */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="git-identity" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('gitIdentity')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-4">
<div className="grid gap-2">
<Label htmlFor="git-name">{t('name')}</Label>
<Input
id="git-name"
placeholder="Your Name"
value={settings.name || ''}
onChange={(e) => updateSettings({ name: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="git-email">{t('email')}</Label>
<Input
id="git-email"
type="email"
placeholder="[email protected]"
value={settings.email || ''}
onChange={(e) => updateSettings({ email: e.target.value })}
/>
</div>
<div className="flex items-center justify-between space-x-2">
<Label htmlFor="co-author" className="flex-1 cursor-pointer">
{t('coAuthoredByShakespeare')}
</Label>
<Switch
id="co-author"
checked={settings.coAuthorEnabled ?? true}
onCheckedChange={(checked) => updateSettings({ coAuthorEnabled: checked })}
/>
</div>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
</div>
</div>
);