diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index ef6daf151..438013ad3 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -5,3 +5,4 @@ /src/renderer/utils/forges/github/ @afonsojramos @setchy /src/renderer/utils/forges/gitea/ @afonsojramos @bircni /src/renderer/utils/forges/gitlab/ @afonsojramos +/src/renderer/utils/forges/gerrit/ @QuentinBtd diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 984cbf39f..613cd2112 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -292,7 +292,7 @@ Gitify supports notifications from multiple Git forges. New forges may be added - **Capability-honest UI:** features unsupported by a forge (e.g. mark-as-done) must hide gracefully, not silently no-op. - **No core-platform churn:** Octicons, Octokit, and the Primer Design System remain in place. Octokit is scoped to the GitHub adapter; other adapters use plain `fetch`. -Currently supported forges: **GitHub** (Cloud, Enterprise Server, Enterprise Cloud with Data Residency), **Gitea** (incl. Forgejo, Codeberg), **Bitbucket Cloud** and **GitLab** (Cloud and Self-Managed). +Currently supported forges: **GitHub** (Cloud, Enterprise Server, Enterprise Cloud with Data Residency), **Gitea** (incl. Forgejo, Codeberg), **Bitbucket Cloud**, **GitLab** (Cloud and Self-Managed), and **Gerrit** (3.12 or later recommended; older versions warn in logs but are not blocked). #### 🚫 Things we won't do diff --git a/MAINTAINERS.md b/MAINTAINERS.md index 9a116880d..42603dc81 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -9,11 +9,13 @@ Gitify is maintained by a small team. Each forge adapter has at least one design ## Forge adapter maintainers -| Forge | Maintainer | Source | -| ------ | -------------------------------------------------------------------------------------- | ----------------------------------- | -| GitHub | [@setchy](https://github.com/setchy), [@afonsojramos](https://github.com/afonsojramos) | `src/renderer/utils/forges/github/` | -| Gitea | [@bircni](https://github.com/bircni), [@afonsojramos](https://github.com/afonsojramos) | `src/renderer/utils/forges/gitea/` | -| GitLab | [@afonsojramos](https://github.com/afonsojramos) | `src/renderer/utils/forges/gitlab/` | +| Forge | Maintainer | Source | +| --------- | -------------------------------------------------------------------------------------- | -------------------------------------- | +| GitHub | [@setchy](https://github.com/setchy), [@afonsojramos](https://github.com/afonsojramos) | `src/renderer/utils/forges/github/` | +| Gitea | [@bircni](https://github.com/bircni), [@afonsojramos](https://github.com/afonsojramos) | `src/renderer/utils/forges/gitea/` | +| GitLab | [@afonsojramos](https://github.com/afonsojramos) | `src/renderer/utils/forges/gitlab/` | +| Bitbucket | [@setchy](https://github.com/setchy) | `src/renderer/utils/forges/bitbucket/` | +| Gerrit | [@QuentinBtd](https://github.com/QuentinBtd) | `src/renderer/utils/forges/gerrit/` | ## Adding a new forge diff --git a/README.md b/README.md index 73d918ccb..fa2aca0fe 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ ## 📦 Features - 🔔 Unified notifications from your Git platforms -- ⚒️ Multi-forge: GitHub Cloud, GitHub Enterprise, Gitea, Forgejo, Codeberg, Bitbucket Cloud, GitLab +- ⚒️ Multi-forge: GitHub Cloud, GitHub Enterprise, Gitea, Forgejo, Codeberg, Bitbucket Cloud, GitLab, Gerrit - 💻 Cross-platform: macOS, Windows, and Linux - 🎨 Customizable settings, filters and themes - 🖥️ Tray/menu bar integration @@ -31,7 +31,7 @@ Gitify uses a forge adapter pattern so notifications can come from any compatibl | **Bitbucket** Cloud | ✅ | ✅ | ✅ | — | — | — | | **GitLab** Cloud & Self-Managed | ✅ | ✅ | ✅ | ✅ | — | ✅ | | **Azure DevOps** | 💭 | — | — | — | — | — | -| **Gerrit** | 💭 | — | — | — | — | — | +| **Gerrit** | ✅ | ✅ | ✅ | — | — | — |
Status legend @@ -49,6 +49,8 @@ Gitify uses a forge adapter pattern so notifications can come from any compatibl > [!NOTE] > _A new forge needs an [adapter](src/renderer/utils/forges/) plus a designated maintainer. See [our contributing guide](CONTRIBUTING.md#multi-forge-support) for the full policy._ +Gerrit 3.12 or later is recommended. Older detected versions produce a log warning but can still sign in; compatibility is not guaranteed. Unknown versions are also allowed. + ## 🚀 Quick Start 1. **Download** Gitify for free from [gitify.io][website]. diff --git a/package.json b/package.json index d44682ba2..eba3714f5 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "electron", "electron-menubar", "forgejo", + "gerrit", "gitea", "github", "gitify", diff --git a/src/__helpers__/gitify-bridge.ts b/src/__helpers__/gitify-bridge.ts index 4a49820a7..3820c822b 100644 --- a/src/__helpers__/gitify-bridge.ts +++ b/src/__helpers__/gitify-bridge.ts @@ -21,6 +21,7 @@ export function createGitifyBridgeApi(platform: TestPlatform = 'macos'): Window[ decryptValue: vi.fn().mockResolvedValue({ token: 'decrypted' }), encryptValue: vi.fn().mockResolvedValue('encrypted'), githubCliToken: vi.fn().mockResolvedValue({ token: 'gh-cli-token' }), + gerritRequest: vi.fn(), setWindowVibrancy: vi.fn().mockResolvedValue(undefined), setNativeTheme: vi.fn().mockResolvedValue(undefined), platform: { diff --git a/src/main/handlers/gerrit.test.ts b/src/main/handlers/gerrit.test.ts new file mode 100644 index 000000000..42bfd3c18 --- /dev/null +++ b/src/main/handlers/gerrit.test.ts @@ -0,0 +1,53 @@ +import { net } from 'electron'; + +import type { IGerritRequest } from '../../shared/events'; + +import { gerritRequest } from './gerrit'; + +vi.mock('electron', () => ({ + ipcMain: { handle: vi.fn() }, + net: { fetch: vi.fn() }, +})); + +const request: IGerritRequest = { + url: 'https://gerrit.example.com/a/changes/proj~1/attention/self/delete', + method: 'POST', + authorization: 'Basic abc', + body: '{"reason":"x"}', +}; + +describe('main/handlers/gerrit.ts', () => { + beforeEach(() => { + vi.mocked(net.fetch).mockReset(); + }); + + it('sends the request with Basic auth, JSON body and no redirects', async () => { + vi.mocked(net.fetch).mockResolvedValueOnce( + new Response(")]}'\n{}", { status: 200, statusText: 'OK' }), + ); + + const result = await gerritRequest(request); + + expect(result).toEqual({ status: 200, statusText: 'OK', body: ")]}'\n{}" }); + expect(net.fetch).toHaveBeenCalledWith(request.url, { + method: 'POST', + headers: { + Accept: 'application/json', + Authorization: 'Basic abc', + 'Content-Type': 'application/json; charset=UTF-8', + }, + body: request.body, + redirect: 'error', + }); + }); + + it.each([ + ['plain http', { url: 'http://gerrit.example.com/a/changes/' }], + ['a path outside the /a/ API', { url: 'https://example.com/anything' }], + ['an unsupported method', { method: 'DELETE' as IGerritRequest['method'] }], + ['non-Basic credentials', { authorization: 'Bearer abc' }], + ])('refuses %s without sending it', async (_, override) => { + await expect(gerritRequest({ ...request, ...override })).rejects.toThrow(/Refusing/); + expect(net.fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/src/main/handlers/gerrit.ts b/src/main/handlers/gerrit.ts new file mode 100644 index 000000000..b74b2f8cc --- /dev/null +++ b/src/main/handlers/gerrit.ts @@ -0,0 +1,54 @@ +import { net } from 'electron'; + +import type { IGerritRequest, IGerritResponse } from '../../shared/events'; +import { EVENTS } from '../../shared/events'; + +import { handleMainEvent } from '../events'; + +/** + * Only Gerrit's authenticated REST API (`https:///a/...`) with HTTP + * Basic credentials is proxied, so this cannot become a general-purpose fetch. + * The renderer validates the host against the signed-in account. + */ +export function assertGerritRequest(request: IGerritRequest): URL { + const url = new URL(request.url); + if (url.protocol !== 'https:' || !url.pathname.startsWith('/a/')) { + throw new Error('Refusing non-Gerrit API request.'); + } + if (request.method !== 'GET' && request.method !== 'POST') { + throw new Error('Refusing unsupported Gerrit request method.'); + } + if (!request.authorization.startsWith('Basic ')) { + throw new Error('Refusing Gerrit request without Basic credentials.'); + } + return url; +} + +export async function gerritRequest(request: IGerritRequest): Promise { + const url = assertGerritRequest(request); + const headers: Record = { + Accept: 'application/json', + Authorization: request.authorization, + }; + if (request.body !== undefined) { + headers['Content-Type'] = 'application/json; charset=UTF-8'; + } + + const response = await net.fetch(url.toString(), { + method: request.method, + headers, + body: request.body, + // Never replay credentials to wherever a redirect points. + redirect: 'error', + }); + + return { + status: response.status, + statusText: response.statusText, + body: await response.text(), + }; +} + +export function registerGerritHandlers(): void { + handleMainEvent(EVENTS.GERRIT_REQUEST, (_, request) => gerritRequest(request)); +} diff --git a/src/main/handlers/index.ts b/src/main/handlers/index.ts index ea0632c50..721722042 100644 --- a/src/main/handlers/index.ts +++ b/src/main/handlers/index.ts @@ -1,4 +1,5 @@ export * from './app'; +export * from './gerrit'; export * from './github-cli'; export * from './native-notifications'; export * from './storage'; diff --git a/src/main/index.test.ts b/src/main/index.test.ts index 6aa838524..f36d8ef75 100644 --- a/src/main/index.test.ts +++ b/src/main/index.test.ts @@ -43,6 +43,7 @@ vi.mock('./config', () => ({ vi.mock('./handlers', () => ({ registerAppHandlers: vi.fn(), registerGitHubCliHandlers: vi.fn(), + registerGerritHandlers: vi.fn(), registerNativeNotificationHandlers: vi.fn(), registerStorageHandlers: vi.fn(), registerSystemHandlers: vi.fn(), diff --git a/src/main/index.ts b/src/main/index.ts index e30af66b9..59f8c0fe4 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -7,6 +7,7 @@ import { logError, toError } from '../shared/logger'; import { Paths, WindowConfig } from './config'; import { registerAppHandlers, + registerGerritHandlers, registerGitHubCliHandlers, registerNativeNotificationHandlers, registerStorageHandlers, @@ -78,6 +79,7 @@ app registerSystemHandlers(mb); registerStorageHandlers(); registerGitHubCliHandlers(); + registerGerritHandlers(); registerAppHandlers(mb); registerUpdaterHandlers(appUpdater); }) diff --git a/src/preload/index.ts b/src/preload/index.ts index 75f02623b..5025ba14a 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,6 +1,7 @@ import { contextBridge, webFrame } from 'electron'; import type { + IGerritRequest, IKeyboardShortcut, INativeNotificationActionEvent, INativeNotificationClickEvent, @@ -61,6 +62,14 @@ export const api = { */ githubCliToken: (hostname: string) => invokeMainEvent(EVENTS.GITHUB_CLI_TOKEN, hostname), + /** + * Run an authenticated Gerrit REST call from the main process (avoids CORS). + * + * @param request - The `/a/` API URL, method, Basic auth header and optional JSON body. + * @returns The response status and raw body text. + */ + gerritRequest: (request: IGerritRequest) => invokeMainEvent(EVENTS.GERRIT_REQUEST, request), + /** * Enable or disable launching the application at system login. * diff --git a/src/renderer/__mocks__/account-mocks.ts b/src/renderer/__mocks__/account-mocks.ts index 6229c78ad..b57f71a55 100644 --- a/src/renderer/__mocks__/account-mocks.ts +++ b/src/renderer/__mocks__/account-mocks.ts @@ -102,6 +102,17 @@ export const mockBitbucketAccount: Account = { user: mockGitifyUser, }; +export const mockGerritAccount: Account = { + forge: 'gerrit', + platform: 'Gerrit', + method: 'Personal Access Token', + token: 'token-gerrit' as Token, + hostname: 'gerrit.example.com' as Hostname, + username: 'jdoe', + user: { ...mockGitifyUser, login: 'jdoe' }, + version: '3.12.0', +}; + export function mockAccountWithError(error: GitifyError): AccountNotifications { return { account: mockGitHubCloudAccount, diff --git a/src/renderer/__mocks__/notifications-mocks.ts b/src/renderer/__mocks__/notifications-mocks.ts index 95560abc0..f382445e0 100644 --- a/src/renderer/__mocks__/notifications-mocks.ts +++ b/src/renderer/__mocks__/notifications-mocks.ts @@ -20,6 +20,7 @@ import { } from '../types'; import { + mockGerritAccount, mockGiteaAccount, mockGitifyOAuthAppAccount, mockGitHubCloudAccount, @@ -306,6 +307,12 @@ export const mockGiteaGitifyNotification: GitifyNotification = { account: mockGiteaAccount, }; +/** Same shape as cloud notification, but bound to a Gerrit account. */ +export const mockGerritGitifyNotification: GitifyNotification = { + ...mockGitifyNotification, + account: mockGerritAccount, +}; + export const mockMultipleAccountNotifications: AccountNotifications[] = [ { account: mockGitHubCloudAccount, diff --git a/src/renderer/components/Sidebar.test.tsx b/src/renderer/components/Sidebar.test.tsx index 4cb2fd714..1c7ebf88a 100644 --- a/src/renderer/components/Sidebar.test.tsx +++ b/src/renderer/components/Sidebar.test.tsx @@ -2,7 +2,7 @@ import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { navigateMock, renderWithProviders } from '../__helpers__/test-utils'; -import { mockGitHubCloudAccount } from '../__mocks__/account-mocks'; +import { mockGerritAccount, mockGitHubCloudAccount } from '../__mocks__/account-mocks'; import { mockSettings } from '../__mocks__/state-mocks'; import { APPLICATION } from '../../shared/constants'; @@ -338,4 +338,16 @@ describe('renderer/components/Sidebar.tsx', () => { expect(quitAppSpy).toHaveBeenCalledTimes(1); }); // Keyboard bindings moved to App.test.tsx + it('opens Gerrit changes and hides the unsupported issues link', async () => { + renderWithProviders(, { accounts: [mockGerritAccount] }); + expect(screen.queryByRole('button', { name: /^My issues/ })).not.toBeInTheDocument(); + await userEvent.click(screen.getByRole('button', { name: /^My pull requests/ })); + expect(openExternalLinkSpy).toHaveBeenLastCalledWith( + 'https://gerrit.example.com/q/status:open+owner:jdoe', + ); + await userEvent.click(screen.getByRole('button', { name: /^Notifications/ })); + expect(openExternalLinkSpy).toHaveBeenLastCalledWith( + 'https://gerrit.example.com/q/attention:jdoe', + ); + }); }); diff --git a/src/renderer/components/Sidebar.tsx b/src/renderer/components/Sidebar.tsx index 685f8a844..0ad51dea6 100644 --- a/src/renderer/components/Sidebar.tsx +++ b/src/renderer/components/Sidebar.tsx @@ -130,15 +130,17 @@ export function Sidebar() { variant={hasFilters ? 'primary' : 'invisible'} /> - shortcuts.myIssues.action()} - size="small" - tooltipDirection="e" - variant="invisible" - /> + {shortcuts.myIssues.isAllowed && ( + shortcuts.myIssues.action()} + size="small" + tooltipDirection="e" + variant="invisible" + /> + )} ) { const { t } = useTranslation(); @@ -170,7 +174,7 @@ export function LoginWithPersonalAccessTokenForm({ {showUsernameField && ( - {t('login.pat.atlassian_email', 'Atlassian Email')} + {usernameLabel ?? t('login.pat.username', 'Username')} {usernameCaption && ( @@ -179,11 +183,12 @@ export function LoginWithPersonalAccessTokenForm({ )} {errors.username && ( diff --git a/src/renderer/components/notifications/AccountHeader.test.tsx b/src/renderer/components/notifications/AccountHeader.test.tsx index 13e96383e..6984674fd 100644 --- a/src/renderer/components/notifications/AccountHeader.test.tsx +++ b/src/renderer/components/notifications/AccountHeader.test.tsx @@ -2,7 +2,7 @@ import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { renderWithProviders } from '../../__helpers__/test-utils'; -import { mockGitHubCloudAccount } from '../../__mocks__/account-mocks'; +import { mockGerritAccount, mockGitHubCloudAccount } from '../../__mocks__/account-mocks'; import * as links from '../../utils/system/links'; import { AccountHeader, type AccountHeaderProps } from './AccountHeader'; @@ -58,6 +58,13 @@ describe('renderer/components/notifications/AccountHeader.tsx', () => { expect(openHostIssuesSpy).toHaveBeenCalledWith(mockGitHubCloudAccount); }); + it('hides issues for Gerrit while retaining the account and changes links', () => { + renderWithProviders(); + expect(screen.queryByTestId('account-issues')).not.toBeInTheDocument(); + expect(screen.getByTestId('account-profile')).toBeInTheDocument(); + expect(screen.getByTestId('account-pull-requests')).toBeInTheDocument(); + }); + it('opens my pull requests when clicked', async () => { const openHostPullsSpy = vi.spyOn(links, 'openHostPulls').mockImplementation(vi.fn()); diff --git a/src/renderer/components/notifications/AccountHeader.tsx b/src/renderer/components/notifications/AccountHeader.tsx index 17eb7384f..aedcc155b 100644 --- a/src/renderer/components/notifications/AccountHeader.tsx +++ b/src/renderer/components/notifications/AccountHeader.tsx @@ -11,7 +11,7 @@ import { HoverGroup } from '../primitives/HoverGroup'; import { type Account, type GitifyError, Size } from '../../types'; -import { getAdapter } from '../../utils/forges/registry'; +import { getAccountAdapter, getAdapter } from '../../utils/forges/registry'; import { openAccountProfile, openHostIssues, openHostPulls } from '../../utils/system/links'; import { getChevronDetails } from '../../utils/ui/display'; import { getChevronIcon } from '../../utils/ui/icons'; @@ -69,12 +69,14 @@ export function AccountHeader({ error ? 'group-hover:bg-gitify-account-error' : 'group-hover:bg-gitify-account-rest' } > - openHostIssues(account)} - icon={IssueOpenedIcon} - label={t('accounts.my_issues', 'My issues ↗')} - testid="account-issues" - /> + {getAccountAdapter(account).getIssuesUrl() && ( + openHostIssues(account)} + icon={IssueOpenedIcon} + label={t('accounts.my_issues', 'My issues ↗')} + testid="account-issues" + /> + )} openHostPulls(account)} diff --git a/src/renderer/hooks/useShortcutActions.ts b/src/renderer/hooks/useShortcutActions.ts index c35c7bac1..869475190 100644 --- a/src/renderer/hooks/useShortcutActions.ts +++ b/src/renderer/hooks/useShortcutActions.ts @@ -4,6 +4,7 @@ import { useLocation, useNavigate } from 'react-router'; import { useAccountsStore, useSettingsStore } from '../stores'; import { getNavItem } from '../nav'; +import { getAccountAdapter } from '../utils/forges/registry'; import { quitApp } from '../utils/system/comms'; import { openHostIssues, openHostNotifications, openHostPulls } from '../utils/system/links'; import { useNotifications } from './useNotifications'; @@ -85,7 +86,8 @@ export function useShortcutActions(): { shortcuts: ShortcutConfigs } { }, myIssues: { key: 'i', - isAllowed: isLoggedIn, + isAllowed: + isLoggedIn && Boolean(primaryAccount && getAccountAdapter(primaryAccount).getIssuesUrl()), action: () => primaryAccount && openHostIssues(primaryAccount), }, myPullRequests: { diff --git a/src/renderer/i18n/locales/en.json b/src/renderer/i18n/locales/en.json index 80d42fa9f..ea9472314 100644 --- a/src/renderer/i18n/locales/en.json +++ b/src/renderer/i18n/locales/en.json @@ -254,12 +254,14 @@ "atlassian_email": "Atlassian Email", "atlassian_email_required": "Atlassian email is required", "docs_tooltip_bitbucket": "Atlassian API token documentation", + "docs_tooltip_gerrit": "Gerrit HTTP credentials documentation", "docs_tooltip_gitea": "Gitea API documentation", "docs_tooltip_github": "GitHub documentation", "docs_tooltip_gitlab": "GitLab To-Do API documentation", "form_errors": "Form errors", "hostname": "Hostname", "hostname_caption_enterprise": "Change only if you are using GitHub Enterprise Server", + "hostname_caption_gerrit": "The hostname of your self-hosted Gerrit instance.", "hostname_caption_gitea": "Your instance hostname or origin, e.g. gitea.example.com or http://git.internal:3000. Defaults to HTTPS.", "hostname_caption_gitlab": "Your GitLab instance hostname (for example gitlab.com)", "hostname_invalid": "Hostname format is invalid", @@ -268,22 +270,29 @@ "scopes_note": "Use a classic personal access token; fine-grained tokens are not supported. The <0>recommended scopes will be automatically selected for you.", "scopes_note_gitlab": "Requires the <0>api scope, or a fine-grained token with <1>Todo (read, update) and <2>User (read) permissions. GitLab shows your To-Do items, so you will see fewer notifications than on GitHub.", "title_bitbucket": "Login to Bitbucket Cloud with API Token", + "title_gerrit": "Login to Gerrit with HTTP Credentials", "title_gitea": "Login to Gitea with Personal Access Token", "title_github": "Login with Personal Access Token", "title_gitlab": "Login to GitLab with Personal Access Token", "token": "Token", "token_invalid": "Token format is invalid", "token_placeholder_bitbucket": "Your Atlassian API token", + "token_placeholder_gerrit": "Your Gerrit HTTP password or authentication token", "token_placeholder_gitea": "Your Gitea personal access token", "token_placeholder_github": "Your classic token (40 characters)", "token_placeholder_gitlab": "Your GitLab personal access token", "token_required": "Token is required", "token_settings_caption_bitbucket": "on your Atlassian account to create an API token, then paste it below.", + "token_settings_caption_gerrit": "on your Gerrit account to generate an HTTP password / authentication token, then paste it below.", "token_settings_caption_gitea": "on your Gitea instance to create a token, then paste it below.", "token_settings_caption_github": "on GitHub to paste the token below.", "token_settings_label": "Open token settings", + "token_settings_label_gerrit": "Open HTTP credentials settings", "token_settings_label_github": "Generate a PAT", - "username_caption_bitbucket": "Your Atlassian account email address" + "username": "Username", + "username_caption_bitbucket": "Your Atlassian account email address", + "username_caption_gerrit": "Your Gerrit username", + "username_required": "Username is required" }, "show_token": "Show token", "subtitle": "on your menu bar", diff --git a/src/renderer/icons/GerritIcon.tsx b/src/renderer/icons/GerritIcon.tsx new file mode 100644 index 000000000..253491ce0 --- /dev/null +++ b/src/renderer/icons/GerritIcon.tsx @@ -0,0 +1,33 @@ +import type { OcticonProps } from '@primer/octicons-react'; + +/** + * Gerrit brand icon. + * + * An original, simplified cherry-shaped mark (referencing Gerrit's own + * "cherry pick" mascot/terminology) rather than a pixel-accurate + * reproduction of any official Gerrit logo asset. + * + * Accepts OcticonProps so it is a drop-in for any place that expects + * an octicon-shaped component (see `BitbucketIcon` for the same pattern). + */ +export function GerritIcon({ + size = 16, + fill = 'currentColor', + className, + ...props +}: Readonly) { + return ( + + ); +} diff --git a/src/renderer/router.tsx b/src/renderer/router.tsx index bbb945da2..e00335235 100644 --- a/src/renderer/router.tsx +++ b/src/renderer/router.tsx @@ -4,6 +4,7 @@ import { AccountsRoute } from './routes/Accounts'; import { AccountScopesRoute } from './routes/AccountScopes'; import { BitbucketLoginWithPersonalAccessTokenRoute } from './routes/bitbucket/LoginWithPersonalAccessToken'; import { FiltersRoute } from './routes/Filters'; +import { GerritLoginWithPersonalAccessTokenRoute } from './routes/gerrit/LoginWithPersonalAccessToken'; import { GiteaLoginWithPersonalAccessTokenRoute } from './routes/gitea/LoginWithPersonalAccessToken'; import { GitHubLoginWithCustomOAuthAppRoute } from './routes/github/LoginWithCustomOAuthApp'; import { GitHubLoginWithDeviceFlowRoute } from './routes/github/LoginWithDeviceFlow'; @@ -53,6 +54,10 @@ export const routes: RouteObject[] = [ element: , path: 'login/gitlab/personal-access-token', }, + { + element: , + path: 'login/gerrit/personal-access-token', + }, { element: , errorElement: , diff --git a/src/renderer/routes/Login.tsx b/src/renderer/routes/Login.tsx index 4fe1bae5f..214e8881b 100644 --- a/src/renderer/routes/Login.tsx +++ b/src/renderer/routes/Login.tsx @@ -181,10 +181,10 @@ export function LoginRoute() { aria-controls={`forge-panel-${adapter.id}`} aria-selected={isActive} className={cn( - 'relative z-10 inline-flex flex-1 cursor-pointer items-center justify-center gap-2', - 'px-2.5 py-1.5 text-sm font-medium', + 'relative z-10 inline-flex flex-1 cursor-pointer items-center justify-center gap-1', + 'px-1 py-1.5 text-sm font-medium', 'transition-[color] duration-[280ms] ease-login-out', - 'max-[30rem]:px-2 max-[30rem]:text-xs', + 'max-[30rem]:text-xs', 'outline-hidden focus-visible:ring-2 focus-visible:ring-[var(--focus-outlineColor)]', isActive ? 'text-[var(--fgColor-default)]' diff --git a/src/renderer/routes/LoginComposition.visual.test.tsx b/src/renderer/routes/LoginComposition.visual.test.tsx index 917526c43..353b8532d 100644 --- a/src/renderer/routes/LoginComposition.visual.test.tsx +++ b/src/renderer/routes/LoginComposition.visual.test.tsx @@ -33,6 +33,27 @@ function topOf(locator: ReturnType): number { } describe('renderer/routes/Login composition visual regression', () => { + it('keeps every forge tab inside the selector', async () => { + renderLogin(Theme.LIGHT, DesignLanguage.CLASSIC); + + try { + // The window is at least 500px wide; 465px is its CSS width at the maximum 120% zoom. + for (const width of [465, 500]) { + await page.viewport(width, 400); + + const selector = page.getByRole('tablist', { name: 'Choose a forge' }).element(); + const bounds = selector.getBoundingClientRect(); + for (const tab of selector.querySelectorAll('[role="tab"]')) { + const rect = tab.getBoundingClientRect(); + expect(rect.left).toBeGreaterThanOrEqual(bounds.left); + expect(rect.right).toBeLessThanOrEqual(bounds.right); + } + } + } finally { + await page.viewport(500, 400); + } + }); + describe.each(THEME_VARIANTS)('$label', ({ designLanguage, theme }) => { it('captures a single-method forge', async () => { renderLogin(theme, designLanguage); diff --git a/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-dark-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-dark-classic-chromium-linux.png index 311c8a6b9..4625eed20 100644 Binary files a/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-dark-classic-chromium-linux.png and b/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-dark-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-dark-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-dark-glass-chromium-linux.png index 63c36c4e5..ebe49f87f 100644 Binary files a/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-dark-glass-chromium-linux.png and b/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-dark-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-light-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-light-classic-chromium-linux.png index 76ae00e17..79b6ccb44 100644 Binary files a/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-light-classic-chromium-linux.png and b/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-light-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-light-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-light-glass-chromium-linux.png index c9177ed06..c36b6e3e0 100644 Binary files a/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-light-glass-chromium-linux.png and b/src/renderer/routes/__screenshots__/Accounts.visual.test.tsx/accounts-add-menu-light-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-dark-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-dark-classic-chromium-linux.png index 21a99ba0f..43a184f4f 100644 Binary files a/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-dark-classic-chromium-linux.png and b/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-dark-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-dark-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-dark-glass-chromium-linux.png index 30223c008..83cef1486 100644 Binary files a/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-dark-glass-chromium-linux.png and b/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-dark-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-light-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-light-classic-chromium-linux.png index 13460c466..5e2a4c81a 100644 Binary files a/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-light-classic-chromium-linux.png and b/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-light-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-light-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-light-glass-chromium-linux.png index 1572619a6..605878613 100644 Binary files a/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-light-glass-chromium-linux.png and b/src/renderer/routes/__screenshots__/LoginComposition.visual.test.tsx/login-gitea-selected-light-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-dark-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-dark-classic-chromium-linux.png index 4342ffa45..bd678e94b 100644 Binary files a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-dark-classic-chromium-linux.png and b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-dark-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-dark-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-dark-glass-chromium-linux.png index 1c526d4f2..ea1d27150 100644 Binary files a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-dark-glass-chromium-linux.png and b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-dark-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-light-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-light-classic-chromium-linux.png index be4cd471a..c0995cc8a 100644 Binary files a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-light-classic-chromium-linux.png and b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-light-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-light-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-light-glass-chromium-linux.png index cf46d32ba..9349875f4 100644 Binary files a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-light-glass-chromium-linux.png and b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-light-glass-chromium-linux.png differ diff --git a/src/renderer/routes/bitbucket/LoginWithPersonalAccessToken.tsx b/src/renderer/routes/bitbucket/LoginWithPersonalAccessToken.tsx index 2b91d509b..149039193 100644 --- a/src/renderer/routes/bitbucket/LoginWithPersonalAccessToken.tsx +++ b/src/renderer/routes/bitbucket/LoginWithPersonalAccessToken.tsx @@ -23,6 +23,8 @@ export function BitbucketLoginWithPersonalAccessTokenRoute() { 'Your Atlassian account email address', )} usernamePlaceholder="you@example.com" + usernameInputType="email" + usernameLabel={t('login.pat.atlassian_email', 'Atlassian Email')} /> ); } diff --git a/src/renderer/routes/gerrit/LoginWithPersonalAccessToken.test.tsx b/src/renderer/routes/gerrit/LoginWithPersonalAccessToken.test.tsx new file mode 100644 index 000000000..e838ef808 --- /dev/null +++ b/src/renderer/routes/gerrit/LoginWithPersonalAccessToken.test.tsx @@ -0,0 +1,145 @@ +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { navigateMock, renderWithProviders } from '../../__helpers__/test-utils'; +import { mockGerritAccount } from '../../__mocks__/account-mocks'; + +import type { Hostname, Token } from '../../types'; + +import { + type PersonalAccessTokenFormData, + validatePersonalAccessTokenForm, +} from '../../utils/auth/loginValidation'; +import * as comms from '../../utils/system/comms'; +import { GerritLoginWithPersonalAccessTokenRoute } from './LoginWithPersonalAccessToken'; + +describe('renderer/routes/gerrit/LoginWithPersonalAccessToken.tsx', () => { + const loginWithPersonalAccessTokenMock = vi.fn(); + const openExternalLinkSpy = vi.spyOn(comms, 'openExternalLink').mockImplementation(vi.fn()); + + it('renders the HTTP credentials form', () => { + renderWithProviders(); + + expect( + screen.getByRole('heading', { name: 'Login to Gerrit with HTTP Credentials' }), + ).toBeInTheDocument(); + expect(screen.getByLabelText(/^Token/)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Login' })).toBeInTheDocument(); + }); + + describe('form validation', () => { + it('requires a username', () => { + const values: PersonalAccessTokenFormData = { + hostname: 'gerrit.example.com' as Hostname, + token: 'my-http-password' as Token, + username: '', + }; + + expect(validatePersonalAccessTokenForm(values, 'gerrit').username).toBe( + 'Username is required', + ); + }); + + it('passes validation with hostname, username, and token', () => { + const values: PersonalAccessTokenFormData = { + hostname: 'gerrit.example.com' as Hostname, + token: 'my-http-password' as Token, + username: 'jdoe', + }; + + expect(validatePersonalAccessTokenForm(values, 'gerrit')).toEqual({}); + }); + }); + + it('renders hostname and username fields', () => { + renderWithProviders(); + expect(screen.getByTestId('login-hostname')).toBeInTheDocument(); + expect(screen.getByRole('textbox', { name: /^Username/ })).toBeInTheDocument(); + }); + + it('should open the HTTP credentials settings page', async () => { + renderWithProviders(, { + loginWithPersonalAccessToken: loginWithPersonalAccessTokenMock, + }); + + await userEvent.type(screen.getByTestId('login-hostname'), 'gerrit.example.com'); + await userEvent.click(screen.getByTestId('login-create-token')); + + expect(openExternalLinkSpy).toHaveBeenCalledTimes(1); + expect(openExternalLinkSpy).toHaveBeenCalledWith( + 'https://gerrit.example.com/settings/#HTTPCredentials', + ); + }); + + it('should login successfully with hostname, username, and token', async () => { + loginWithPersonalAccessTokenMock.mockResolvedValueOnce(null); + + renderWithProviders(, { + loginWithPersonalAccessToken: loginWithPersonalAccessTokenMock, + }); + + await userEvent.type(screen.getByTestId('login-hostname'), 'gerrit.example.com'); + await userEvent.type(screen.getByRole('textbox', { name: /^Username/ }), 'jdoe'); + await userEvent.type(screen.getByTestId('login-token'), 'my-http-password'); + + await userEvent.click(screen.getByTestId('login-submit')); + + await waitFor(() => { + expect(loginWithPersonalAccessTokenMock).toHaveBeenCalledTimes(1); + expect(loginWithPersonalAccessTokenMock).toHaveBeenCalledWith({ + hostname: 'gerrit.example.com', + token: 'my-http-password', + username: 'jdoe', + forge: 'gerrit', + }); + expect(navigateMock).toHaveBeenCalledWith('/'); + }); + }); + + it('shows an error banner on login failure', async () => { + loginWithPersonalAccessTokenMock.mockRejectedValueOnce(new Error('invalid credentials')); + + renderWithProviders(, { + loginWithPersonalAccessToken: loginWithPersonalAccessTokenMock, + }); + + await userEvent.type(screen.getByTestId('login-hostname'), 'gerrit.example.com'); + await userEvent.type(screen.getByRole('textbox', { name: /^Username/ }), 'jdoe'); + await userEvent.type(screen.getByTestId('login-token'), 'my-http-password'); + await userEvent.click(screen.getByTestId('login-submit')); + + await waitFor(() => { + expect(screen.getByTestId('login-errors')).toHaveTextContent( + 'Failed to validate provided token against gerrit.example.com', + ); + expect(navigateMock).not.toHaveBeenCalled(); + }); + }); + + it('should open help docs in the browser', async () => { + renderWithProviders(); + + await userEvent.click(screen.getByRole('button', { name: 'Docs' })); + + expect(openExternalLinkSpy).toHaveBeenCalledTimes(1); + expect(openExternalLinkSpy).toHaveBeenCalledWith( + 'https://gerrit-review.googlesource.com/Documentation/rest-api.html', + ); + }); + + it('prefills hostname and username from the re-auth account in location state', () => { + renderWithProviders(, { + initialEntries: [ + { + pathname: '/login/gerrit/personal-access-token', + state: { + account: mockGerritAccount, + }, + }, + ], + }); + + expect(screen.getByTestId('login-hostname')).toHaveValue('gerrit.example.com'); + expect(screen.getByRole('textbox', { name: /^Username/ })).toHaveValue('jdoe'); + }); +}); diff --git a/src/renderer/routes/gerrit/LoginWithPersonalAccessToken.tsx b/src/renderer/routes/gerrit/LoginWithPersonalAccessToken.tsx new file mode 100644 index 000000000..b9bc794fd --- /dev/null +++ b/src/renderer/routes/gerrit/LoginWithPersonalAccessToken.tsx @@ -0,0 +1,35 @@ +import { useTranslation } from 'react-i18next'; + +import { LoginWithPersonalAccessTokenForm } from '../../components/login/LoginWithPersonalAccessTokenForm'; + +export function GerritLoginWithPersonalAccessTokenRoute() { + const { t } = useTranslation(); + + return ( + + ); +} diff --git a/src/renderer/types.ts b/src/renderer/types.ts index 2fb4c5d4e..a3e2ee8a3 100644 --- a/src/renderer/types.ts +++ b/src/renderer/types.ts @@ -61,7 +61,7 @@ export type AccountUUID = Branded; export type KeyboardAcceleratorShortcut = Branded; /** Code hosting provider for an account. New forges register themselves here. */ -export type Forge = 'github' | 'gitea' | 'bitbucket' | 'gitlab'; +export type Forge = 'github' | 'gitea' | 'bitbucket' | 'gitlab' | 'gerrit'; export interface Account { forge: Forge; @@ -75,7 +75,7 @@ export interface Account { * custom OAuth app; absent for Gitify's own preconfigured app. */ clientId?: ClientID; - /** Atlassian account email — required for Bitbucket Basic Auth (email:token). */ + /** Basic Auth username: Atlassian email for Bitbucket, username for Gerrit. */ username?: string; user: GitifyUser | null; scopes?: string[]; diff --git a/src/renderer/utils/api/errors.ts b/src/renderer/utils/api/errors.ts index 1e3eacb44..8896172cf 100644 --- a/src/renderer/utils/api/errors.ts +++ b/src/renderer/utils/api/errors.ts @@ -10,7 +10,8 @@ import { rendererLogError } from '../core/logger'; /** * Determine the failure type based on an error. - * Handles Octokit RequestError (REST), GraphqlResponseError (GraphQL), and generic Error. + * Handles Octokit RequestError (REST), GraphqlResponseError (GraphQL), and generic Error + * (with an optional numeric `status`). * * @param err The error (RequestError, GraphqlResponseError, or generic Error) * @returns The Gitify error type @@ -25,10 +26,10 @@ export function determineFailureType( return getErrorDetails('BAD_CREDENTIALS'); } - // Handle Octokit REST RequestError - if (err instanceof RequestError) { - const status = err.status; - + // HTTP status from Octokit's RequestError, or from forge clients that attach + // a numeric `status` to a plain Error (e.g. Gerrit). + const status = err instanceof RequestError ? err.status : (err as { status?: unknown }).status; + if (typeof status === 'number') { switch (status) { case 401: return getErrorDetails('BAD_CREDENTIALS'); diff --git a/src/renderer/utils/auth/loginValidation.ts b/src/renderer/utils/auth/loginValidation.ts index 220e2719e..a72f80ca2 100644 --- a/src/renderer/utils/auth/loginValidation.ts +++ b/src/renderer/utils/auth/loginValidation.ts @@ -66,6 +66,9 @@ export const validatePersonalAccessTokenForm = ( if (forge === 'bitbucket' && !values.username) { errors.username = i18n.t('login.pat.atlassian_email_required', 'Atlassian email is required'); } + if (forge === 'gerrit' && !values.username) { + errors.username = i18n.t('login.pat.username_required', 'Username is required'); + } if (!values.token) { errors.token = i18n.t('login.pat.token_required', 'Token is required'); diff --git a/src/renderer/utils/auth/types.ts b/src/renderer/utils/auth/types.ts index d64e6fd1d..2a2954738 100644 --- a/src/renderer/utils/auth/types.ts +++ b/src/renderer/utils/auth/types.ts @@ -8,6 +8,7 @@ export type AuthMethod = export type PlatformType = | 'Bitbucket Cloud' + | 'Gerrit' | 'GitHub Cloud' | 'GitHub Enterprise Server' | 'GitHub Enterprise Cloud with Data Residency' diff --git a/src/renderer/utils/forges/gerrit/adapter.test.ts b/src/renderer/utils/forges/gerrit/adapter.test.ts new file mode 100644 index 000000000..2cbf32fce --- /dev/null +++ b/src/renderer/utils/forges/gerrit/adapter.test.ts @@ -0,0 +1,240 @@ +import { KeyIcon } from '@primer/octicons-react'; + +import { mockGerritAccount } from '../../../__mocks__/account-mocks'; +import { mockPartialGitifyNotification } from '../../../__mocks__/notifications-mocks'; + +import type { Hostname, Link, Token } from '../../../types'; + +import * as logger from '../../core/logger'; +import { gerritAdapter } from './adapter'; +import * as client from './client'; + +describe('renderer/utils/forges/gerrit/adapter.ts', () => { + describe('static fields', () => { + it('identifies as gerrit', () => { + expect(gerritAdapter.id).toBe('gerrit'); + expect(gerritAdapter.displayName).toBe('Gerrit'); + }); + + it('reports unsupported capabilities', () => { + expect(gerritAdapter.accountOps.capabilities.markAsDone(mockGerritAccount)).toBe(false); + expect(gerritAdapter.accountOps.capabilities.unsubscribeThread(mockGerritAccount)).toBe( + false, + ); + }); + + it('does not implement detailed enrichment', () => { + expect(gerritAdapter.enrichNotifications).toBeUndefined(); + }); + + it('exposes a single PAT login method', () => { + expect(gerritAdapter.loginMethods).toHaveLength(1); + expect(gerritAdapter.loginMethods[0]).toMatchObject({ + testId: 'login-gerrit-pat', + route: '/login/gerrit/personal-access-token', + authMethod: 'Personal Access Token', + }); + }); + + it('builds PAT settings and account settings URLs from the hostname', () => { + expect( + gerritAdapter.getPersonalAccessTokenSettingsUrl('gerrit.example.com' as Hostname), + ).toBe('https://gerrit.example.com/settings/#HTTPCredentials'); + + expect(gerritAdapter.accountOps.getAccountSettingsUrl(mockGerritAccount)).toBe( + 'https://gerrit.example.com/settings/#HTTPCredentials', + ); + }); + + it('returns the key icon for every auth method (PAT-only forge today)', () => { + expect(gerritAdapter.getAuthMethodIcon('Personal Access Token')).toBe(KeyIcon); + expect(gerritAdapter.getAuthMethodIcon('Gitify OAuth App')).toBe(KeyIcon); + expect(gerritAdapter.getAuthMethodIcon('Custom OAuth App')).toBe(KeyIcon); + }); + + it('formats the user login without an "@" prefix', () => { + expect(gerritAdapter.formatUserLogin('jdoe')).toBe('jdoe'); + }); + + it('omits the OAuth scopes capability bundle', () => { + expect(gerritAdapter.accountOps.oauthScopes).toBeUndefined(); + }); + + it('omits device-flow and OAuth-app bundles', () => { + expect(gerritAdapter.deviceFlow).toBeUndefined(); + expect(gerritAdapter.customOAuthApp).toBeUndefined(); + }); + }); + + describe('validateToken', () => { + it('rejects an empty token', () => { + expect(gerritAdapter.validateToken('' as Token)).toBe(false); + }); + + it('accepts any non-empty token (no fixed Gerrit token format)', () => { + expect(gerritAdapter.validateToken('any-non-empty-value' as Token)).toBe(true); + }); + }); + + describe('fetchAuthenticatedUser', () => { + it('maps the Gerrit account payload onto the shared shape', async () => { + vi.spyOn(client, 'fetchGerritAuthenticatedUser').mockResolvedValue({ + account: { + _account_id: 7, + username: 'jdoe', + name: 'John Doe', + avatars: [{ url: 'https://example.com/a.png', height: 64 }], + }, + version: '3.13.2', + }); + + const result = await gerritAdapter.accountOps.fetchAuthenticatedUser(mockGerritAccount); + + expect(result).toEqual({ + user: { + id: '7', + login: 'jdoe', + name: 'John Doe', + avatar: 'https://example.com/a.png', + }, + version: '3.13.2', + }); + }); + + it('falls back to null name, empty avatar, and numeric-id login when missing', async () => { + vi.spyOn(client, 'fetchGerritAuthenticatedUser').mockResolvedValue({ + account: { _account_id: 1 }, + version: undefined, + }); + + const result = await gerritAdapter.accountOps.fetchAuthenticatedUser(mockGerritAccount); + + expect(result.user.login).toBe('1'); + expect(result.user.name).toBeNull(); + expect(result.user.avatar).toBe(''); + expect(result.version).toBeUndefined(); + }); + + it.each(['3.9.0', '3.11.0'])('warns but allows login on Gerrit %s', async (version) => { + const warnSpy = vi.spyOn(logger, 'rendererLogWarn').mockImplementation(vi.fn()); + vi.spyOn(client, 'fetchGerritAuthenticatedUser').mockResolvedValue({ + account: { _account_id: 1, username: 'jdoe' }, + version, + }); + + await expect( + gerritAdapter.accountOps.fetchAuthenticatedUser(mockGerritAccount), + ).resolves.toMatchObject({ user: { id: '1', login: 'jdoe' }, version }); + expect(warnSpy).toHaveBeenCalledExactlyOnceWith( + 'gerrit:fetchAuthenticatedUser', + `Gerrit server version ${version} is older than the recommended 3.12.0. Login is allowed, but compatibility is not guaranteed.`, + ); + }); + + it.each([undefined, 'unknown', '3.12.0', '3.13.2'])( + 'allows login without a version warning for %s', + async (version) => { + const warnSpy = vi.spyOn(logger, 'rendererLogWarn').mockImplementation(vi.fn()); + vi.spyOn(client, 'fetchGerritAuthenticatedUser').mockResolvedValue({ + account: { _account_id: 1, username: 'jdoe' }, + version, + }); + + await expect( + gerritAdapter.accountOps.fetchAuthenticatedUser(mockGerritAccount), + ).resolves.toBeDefined(); + expect(warnSpy).not.toHaveBeenCalled(); + }, + ); + }); + + describe('listNotifications', () => { + it('returns transformed notifications', async () => { + vi.spyOn(client, 'listGerritChanges').mockResolvedValue([ + { + id: 'proj~99', + project: 'proj', + branch: 'main', + change_id: 'Iabc', + subject: 'A change', + status: 'NEW', + created: '2024-01-15 10:00:00.000000000', + updated: '2024-01-15 12:00:00.000000000', + _number: 99, + owner: { _account_id: 1, username: 'jdoe' }, + }, + ]); + + const result = await gerritAdapter.accountOps.listNotifications(mockGerritAccount); + + expect(result).toHaveLength(1); + expect(result[0].id).toBe('proj~99'); + expect(result[0].account).toBe(mockGerritAccount); + }); + }); + + describe('thread mutation methods', () => { + it('markThreadAsRead removes the caller from the attention set', async () => { + const removeSpy = vi.spyOn(client, 'removeSelfFromAttentionSet').mockResolvedValue(undefined); + + await gerritAdapter.accountOps.markThreadAsRead(mockGerritAccount, 'proj~12'); + + expect(removeSpy).toHaveBeenCalledWith( + mockGerritAccount, + 'proj~12', + 'Marked as read via Gitify', + ); + }); + + it('markThreadAsDone throws — capability gate is the contract', () => { + expect(() => gerritAdapter.accountOps.markThreadAsDone(mockGerritAccount, 'proj~13')).toThrow( + /check capabilities.markAsDone/, + ); + }); + + it('unsubscribeThread throws because Gerrit has no equivalent', () => { + expect(() => + gerritAdapter.accountOps.unsubscribeThread(mockGerritAccount, 'proj~14'), + ).toThrow(/not supported for Gerrit/); + }); + }); + + describe('followUrl', () => { + it('delegates to gerritGetJson', async () => { + const getJsonSpy = vi.spyOn(client, 'gerritGetJson').mockResolvedValue({ subject: 'x' }); + + const result = await gerritAdapter.accountOps.followUrl<{ subject: string }>( + mockGerritAccount, + 'https://gerrit.example.com/a/changes/proj~1' as Link, + ); + + expect(result).toEqual({ subject: 'x' }); + expect(getJsonSpy).toHaveBeenCalledWith( + mockGerritAccount, + 'https://gerrit.example.com/a/changes/proj~1', + ); + }); + }); + + describe('getDisplayHelpers', () => { + it('returns icon/color/url helpers via the shared subject-type handlers', () => { + const notification = mockPartialGitifyNotification( + { + title: 'Gerrit change', + type: 'PullRequest', + state: 'OPEN', + }, + { + htmlUrl: 'https://gerrit.example.com/admin/repos/proj' as Link, + }, + ); + notification.account = mockGerritAccount; + + const helpers = gerritAdapter.getDisplayHelpers(notification); + + expect(helpers.iconType).toBeDefined(); + expect(helpers.iconColor).toBeDefined(); + expect(helpers.defaultUserType).toBe('User'); + }); + }); +}); diff --git a/src/renderer/utils/forges/gerrit/adapter.ts b/src/renderer/utils/forges/gerrit/adapter.ts new file mode 100644 index 000000000..948db3b57 --- /dev/null +++ b/src/renderer/utils/forges/gerrit/adapter.ts @@ -0,0 +1,187 @@ +import { KeyIcon } from '@primer/octicons-react'; + +import semver from 'semver'; + +import type { Account, Hostname, Link, RawGitifyNotification, Token } from '../../../types'; +import type { + ForgeAdapter, + ForgeCapabilities, + NotificationDisplayHelpers, + RefreshAccountData, +} from '../types'; + +import { GerritIcon } from '../../../icons/GerritIcon'; +import { isValidHostname } from '../../auth/identity'; +import { rendererLogWarn } from '../../core/logger'; +import { createNotificationHandler } from '../github/handlers'; +import { + fetchGerritAuthenticatedUser, + gerritGetJson, + listGerritChanges, + removeSelfFromAttentionSet, +} from './client'; +import { transformGerritChanges } from './transform'; + +const GERRIT_DOCS_URL = + 'https://gerrit-review.googlesource.com/Documentation/rest-api.html' as Link; + +// Support-policy recommendation, not a technical requirement for Attention Set. +const GERRIT_RECOMMENDED_VERSION = '3.12.0'; + +const capabilities: ForgeCapabilities = { + // Gerrit has no "done"/archive concept distinct from "mark as read" + // (removing the calling user from a change's attention set already covers + // that). Throwing rather than silently aliasing to markThreadAsRead + // surfaces any caller that bypasses the capability check. + markAsDone: () => false, + // Gerrit has no per-change unsubscribe; only project-level watch filters, + // which are a different (broader) scope than a single thread. + unsubscribeThread: () => false, +}; + +function warnOnOlderVersion(rawVersion: string | undefined): void { + if (!rawVersion) { + return; + } + + const coerced = semver.coerce(rawVersion); + if (coerced && semver.lt(coerced, GERRIT_RECOMMENDED_VERSION)) { + rendererLogWarn( + 'gerrit:fetchAuthenticatedUser', + `Gerrit server version ${rawVersion} is older than the recommended ${GERRIT_RECOMMENDED_VERSION}. Login is allowed, but compatibility is not guaranteed.`, + ); + } +} + +async function fetchAuthenticatedUser(account: Account): Promise { + const { account: gerritUser, version } = await fetchGerritAuthenticatedUser(account); + + warnOnOlderVersion(version); + + return { + user: { + id: String(gerritUser._account_id), + login: gerritUser.username ?? gerritUser.name ?? String(gerritUser._account_id), + name: gerritUser.name ?? gerritUser.display_name ?? null, + avatar: gerritUser.avatars?.[0]?.url ?? '', + }, + version: version ? (semver.coerce(version)?.version ?? version) : undefined, + }; +} + +async function listNotifications(account: Account): Promise { + const raw = await listGerritChanges(account); + return transformGerritChanges(raw, account); +} + +// Gerrit changes are mapped onto the shared 'PullRequest' subject type (see +// transform.ts), so this reuses GitHub's notification-type handler dispatch +// for display helpers — same precedent as `gitea/adapter.ts`. The dispatch +// only reads `subject.state`/`subject.htmlUrl` here; it never triggers +// GitHub-specific network calls. +function getDisplayHelpers(notification: RawGitifyNotification): NotificationDisplayHelpers { + const handler = createNotificationHandler(notification); + return { + iconType: handler.iconType(notification), + iconColor: handler.iconColor(notification), + defaultUrl: handler.defaultUrl(notification), + defaultUserType: handler.defaultUserType(), + }; +} + +/** + * Build a Gerrit `/q/` search-results URL for the given query predicates. + * Predicates are joined with a literal `+`, matching Gerrit's own + * self-referential dashboard links (e.g. `#/q/status:open+is:watched`). + */ +function buildGerritQueryUrl(account: Account, ...predicates: string[]): Link { + const url = new URL(`https://${account.hostname}/q/${predicates.join('+')}`); + return url.toString() as Link; +} + +export const gerritAdapter: ForgeAdapter = { + id: 'gerrit', + displayName: 'Gerrit', + tagline: 'Gerrit Code Review', + icon: GerritIcon, + getPlatform: () => 'Gerrit', + validateHostname: isValidHostname, + + // Gerrit's own UI does not prefix usernames with "@". + formatUserLogin: (login) => login, + + accountOps: { + capabilities, + formatNotificationUser: (_account, user) => user.login, + fetchAuthenticatedUser, + listNotifications, + + markThreadAsRead: (account, threadId) => + removeSelfFromAttentionSet(account, threadId, 'Marked as read via Gitify'), + markThreadAsDone: () => { + throw new Error( + 'Mark-as-done is not supported for Gerrit accounts; check capabilities.markAsDone before calling.', + ); + }, + unsubscribeThread: () => { + throw new Error( + 'Unsubscribing from a single change is not supported for Gerrit accounts; check capabilities.unsubscribeThread before calling.', + ); + }, + + followUrl(account: Account, url: Link): Promise { + return gerritGetJson(account, url); + }, + + // "My changes" (Gerrit has no "pull request" terminology, but this is the + // closest — and only — equivalent cross-project dashboard). Explicit + // username rather than the `self` keyword so the link resolves correctly + // even if the browser isn't already authenticated as this exact account. + getPullRequestsUrl: (account) => + buildGerritQueryUrl( + account, + 'status:open', + `owner:${encodeURIComponent(account.user?.login ?? 'self')}`, + ), + // Mirrors this adapter's own notification model (see transform.ts): + // presence in the attention set is what Gitify surfaces as "unread". + getNotificationsUrl: (account) => + buildGerritQueryUrl( + account, + `attention:${encodeURIComponent(account.user?.login ?? 'self')}`, + ), + getIssuesUrl: () => undefined, + // Gerrit has no personal profile page; the closest equivalent is the list + // of changes this account owns (same convention already used for + // individual notification authors — see `transform.ts`'s `mapAccount`). + getAccountProfileUrl: (account) => + buildGerritQueryUrl(account, `owner:${encodeURIComponent(account.user?.login ?? 'self')}`), + getAccountSettingsUrl: (account: Account) => + `https://${account.hostname}/settings/#HTTPCredentials` as Link, + }, + getDisplayHelpers, + + // Gerrit HTTP passwords / authentication tokens have no fixed, documented + // format (unlike GitHub's 40-char hex or Gitea's 40-char lowercase hex) — + // same permissive approach as Bitbucket's Atlassian API tokens. + validateToken: (token: Token) => token.length > 0, + getPersonalAccessTokenSettingsUrl: (hostname: Hostname) => + `https://${hostname}/settings/#HTTPCredentials` as Link, + documentationUrl: GERRIT_DOCS_URL, + // Gerrit only supports HTTP password / authentication token login today, so + // every method falls through to the key icon. + getAuthMethodIcon: () => KeyIcon, + + loginMethods: [ + { + testId: 'login-gerrit-pat', + icon: KeyIcon, + label: 'HTTP Password / Token', + route: '/login/gerrit/personal-access-token', + authMethod: 'Personal Access Token', + }, + ], + + // Gerrit has no GitHub-style OAuth scope concept, so `oauthScopes` is + // omitted. Callers skip scopes UI when this is undefined. +}; diff --git a/src/renderer/utils/forges/gerrit/client.test.ts b/src/renderer/utils/forges/gerrit/client.test.ts new file mode 100644 index 000000000..2af37fd4d --- /dev/null +++ b/src/renderer/utils/forges/gerrit/client.test.ts @@ -0,0 +1,229 @@ +import { mockGerritAccount } from '../../../__mocks__/account-mocks'; + +import type { IGerritResponse } from '../../../../shared/events'; + +import { useSettingsStore } from '../../../stores'; + +import type { Hostname } from '../../../types'; + +import { determineFailureType } from '../../api/errors'; +import { getErrorDetails } from '../../core/errors'; +import * as comms from '../../system/comms'; +import { + fetchGerritAuthenticatedUser, + gerritGetJson, + getGerritApiBaseUrl, + listGerritChanges, + removeSelfFromAttentionSet, + stripGerritXssiPrefix, +} from './client'; + +describe('renderer/utils/forges/gerrit/client.ts', () => { + const fetchMock = () => vi.mocked(window.gitify.gerritRequest); + + function xssiResponse(body: T): IGerritResponse { + return { status: 200, statusText: 'OK', body: `)]}'\n${JSON.stringify(body)}` }; + } + + const noContent: IGerritResponse = { status: 204, statusText: 'No Content', body: '' }; + + beforeEach(() => { + fetchMock().mockReset(); + vi.spyOn(comms, 'decryptValue').mockResolvedValue({ token: 'decrypted' }); + }); + + describe('stripGerritXssiPrefix', () => { + it("strips the leading )]}' magic prefix", () => { + expect(stripGerritXssiPrefix(")]}'\n[1,2,3]")).toBe('\n[1,2,3]'); + }); + + it('leaves text without the prefix untouched', () => { + expect(stripGerritXssiPrefix('[1,2,3]')).toBe('[1,2,3]'); + }); + }); + + describe('getGerritApiBaseUrl', () => { + it('builds an authenticated https /a/ base', () => { + const url = getGerritApiBaseUrl('gerrit.example.com' as Hostname); + expect(url.toString()).toBe('https://gerrit.example.com/a/'); + }); + + it('throws for an invalid hostname', () => { + expect(() => getGerritApiBaseUrl('not a host' as Hostname)).toThrow(/invalid hostname/); + }); + }); + + describe('listGerritChanges', () => { + it('sends the attention:self query with DETAILED_ACCOUNTS when fetchAllNotifications is false', async () => { + fetchMock().mockResolvedValueOnce(xssiResponse([{ id: 'proj~1' }])); + + useSettingsStore.setState({ fetchAllNotifications: false }); + + const result = await listGerritChanges(mockGerritAccount); + + expect(result).toEqual([{ id: 'proj~1' }]); + expect(fetchMock()).toHaveBeenCalledTimes(1); + const calledUrl = fetchMock().mock.calls[0][0].url; + expect(calledUrl).toContain('https://gerrit.example.com/a/changes/?'); + expect(calledUrl).toContain('q=attention%3Aself'); + expect(calledUrl).toContain('o=DETAILED_ACCOUNTS'); + expect(calledUrl).not.toContain('S='); + }); + + it('paginates using S/_more_changes until a page reports no more results', async () => { + const fullPage = Array.from({ length: 1 }, (_, i) => ({ + id: `proj~${i}`, + _more_changes: true, + })); + + fetchMock() + .mockResolvedValueOnce(xssiResponse(fullPage)) + .mockResolvedValueOnce(xssiResponse([{ id: 'proj~last' }])); + + useSettingsStore.setState({ fetchAllNotifications: true }); + + const result = await listGerritChanges(mockGerritAccount); + + expect(result).toHaveLength(2); + expect(fetchMock()).toHaveBeenCalledTimes(2); + const secondUrl = fetchMock().mock.calls[1][0].url; + expect(secondUrl).toContain('S=1'); + }); + + it('stops pagination immediately on an empty page', async () => { + fetchMock().mockResolvedValueOnce(xssiResponse([])); + + useSettingsStore.setState({ fetchAllNotifications: true }); + + const result = await listGerritChanges(mockGerritAccount); + + expect(result).toEqual([]); + expect(fetchMock()).toHaveBeenCalledTimes(1); + }); + + it('throws on a non-ok status without echoing the response body', async () => { + fetchMock().mockResolvedValue({ + status: 403, + statusText: 'Forbidden', + body: 'Authorization: Basic leaked-credentials', + }); + + useSettingsStore.setState({ fetchAllNotifications: false }); + + await expect(listGerritChanges(mockGerritAccount)).rejects.toThrow( + /^Gerrit API 403 Forbidden$/, + ); + }); + + it('reports a 401 as bad credentials so the UI offers re-authentication', async () => { + fetchMock().mockResolvedValue({ status: 401, statusText: 'Unauthorized', body: '' }); + + useSettingsStore.setState({ fetchAllNotifications: false }); + + const err = await listGerritChanges(mockGerritAccount).catch((e: Error) => e); + expect(determineFailureType(err as Error)).toEqual(getErrorDetails('BAD_CREDENTIALS')); + }); + }); + + describe('fetchGerritAuthenticatedUser', () => { + it('fetches the account and server version in parallel', async () => { + fetchMock() + .mockResolvedValueOnce(xssiResponse({ _account_id: 7, username: 'jdoe' })) + .mockResolvedValueOnce(xssiResponse({ gerrit_version: '3.13.2' })); + + const result = await fetchGerritAuthenticatedUser(mockGerritAccount); + + expect(result.account).toEqual({ _account_id: 7, username: 'jdoe' }); + expect(result.version).toBe('3.13.2'); + }); + + it('accepts a plain string version response (non-verbose)', async () => { + fetchMock() + .mockResolvedValueOnce(xssiResponse({ _account_id: 7 })) + .mockResolvedValueOnce(xssiResponse('3.9.0')); + + const result = await fetchGerritAuthenticatedUser(mockGerritAccount); + + expect(result.version).toBe('3.9.0'); + }); + + it('resolves version as undefined rather than throwing when the endpoint is unreachable', async () => { + fetchMock() + .mockResolvedValueOnce(xssiResponse({ _account_id: 7 })) + .mockResolvedValueOnce({ status: 403, statusText: 'Forbidden', body: 'nope' }); + + const result = await fetchGerritAuthenticatedUser(mockGerritAccount); + + expect(result.version).toBeUndefined(); + }); + }); + + describe('removeSelfFromAttentionSet', () => { + it('POSTs to the attention/self/delete alias with a reason body', async () => { + fetchMock().mockResolvedValueOnce(noContent); + + await removeSelfFromAttentionSet(mockGerritAccount, 'proj~42', 'Marked as read via Gitify'); + + const [{ url, method, body }] = fetchMock().mock.calls[0]; + expect(url).toContain('/a/changes/proj~42/attention/self/delete'); + expect(method).toBe('POST'); + expect(body).toBe(JSON.stringify({ reason: 'Marked as read via Gitify' })); + }); + + it('does not re-encode a changeId whose project segment is already URL-encoded by Gerrit (regression: double-encoding 404)', async () => { + fetchMock().mockResolvedValueOnce(noContent); + + // Gerrit's own ChangeInfo.id for a nested project (e.g. "modules/cache-infinispan") + // already comes back with the project segment percent-encoded. + const nestedProjectChangeId = 'modules%2Fcache-infinispan~593701'; + + await removeSelfFromAttentionSet(mockGerritAccount, nestedProjectChangeId, 'reason'); + + const [{ url }] = fetchMock().mock.calls[0]; + // Must appear verbatim — re-encoding would turn the existing `%2F` + // into `%252F`, which Gerrit cannot resolve back to a project name. + expect(url).toContain('/a/changes/modules%2Fcache-infinispan~593701/attention/self/delete'); + expect(url).not.toContain('%252F'); + }); + }); + + describe('gerritGetJson', () => { + it('GETs the supplied URL with Basic auth headers and strips the XSSI prefix', async () => { + fetchMock().mockResolvedValueOnce(xssiResponse({ subject: 'x' })); + + const result = await gerritGetJson<{ subject: string }>( + mockGerritAccount, + 'https://gerrit.example.com/a/changes/proj~1', + ); + + expect(result).toEqual({ subject: 'x' }); + expect(fetchMock().mock.calls[0][0].authorization).toBe(`Basic ${btoa('jdoe:decrypted')}`); + }); + + it('refuses cross-origin URLs without sending a request', async () => { + await expect( + gerritGetJson(mockGerritAccount, 'https://attacker.com/a/changes/proj~1'), + ).rejects.toThrow(/cross-origin Gerrit URL/); + expect(fetchMock()).not.toHaveBeenCalled(); + }); + + it('refuses malformed URLs without sending a request', async () => { + await expect(gerritGetJson(mockGerritAccount, 'not-a-url')).rejects.toThrow( + /malformed Gerrit URL/, + ); + expect(fetchMock()).not.toHaveBeenCalled(); + }); + + it('throws on a non-ok response without echoing the body', async () => { + fetchMock().mockResolvedValueOnce({ + status: 500, + statusText: 'Server Error', + body: 'echoed Authorization header', + }); + + await expect( + gerritGetJson(mockGerritAccount, 'https://gerrit.example.com/a/changes/proj~1'), + ).rejects.toThrow(/^Gerrit API 500 Server Error$/); + }); + }); +}); diff --git a/src/renderer/utils/forges/gerrit/client.ts b/src/renderer/utils/forges/gerrit/client.ts new file mode 100644 index 000000000..a040c976d --- /dev/null +++ b/src/renderer/utils/forges/gerrit/client.ts @@ -0,0 +1,208 @@ +import useSettingsStore from '../../../stores/useSettingsStore'; + +import type { Account, Hostname } from '../../../types'; +import type { GerritAccountInfo, GerritChangeInfo, GerritServerVersionInfo } from './types'; + +import { isValidHostname } from '../../auth/identity'; +import { decryptValue, sendGerritRequest } from '../../system/comms'; + +const PAGE_SIZE = 100; + +/** Gerrit's JSON responses are prefixed with this XSSI-protection magic line, which must be stripped before parsing. */ +const XSSI_PREFIX = ")]}'"; + +export function getGerritApiBaseUrl(hostname: Hostname): URL { + if (!isValidHostname(hostname)) { + throw new Error('Refusing to build a Gerrit API URL for invalid hostname.'); + } + // The `/a/` prefix authenticates via HTTP Basic and also bypasses the need + // for XSRF tokens on writes (see Gerrit REST API docs, "Authentication"). + return new URL(`https://${hostname}/a/`); +} + +async function basicAuthorization(account: Account): Promise { + if (!account.username) { + throw new Error('Gerrit account is missing username. Cannot build auth headers.'); + } + const { token } = await decryptValue(account.token); + return `Basic ${btoa(`${account.username}:${token}`)}`; +} + +/** + * Drop the response body from error messages — a misbehaving server can echo + * the request (including the Authorization header) back, and that error + * propagates to logs. `status` lets the shared classifier spot bad credentials. + */ +function apiError(status: number, statusText: string): Error & { status: number } { + return Object.assign(new Error(`Gerrit API ${status} ${statusText}`), { status }); +} + +/** Strip the `)]}'` XSSI-protection prefix Gerrit prepends to every JSON response body. */ +export function stripGerritXssiPrefix(text: string): string { + return text.startsWith(XSSI_PREFIX) ? text.slice(XSSI_PREFIX.length) : text; +} + +/** + * Sent through the main process: Gerrit servers rarely allow the app's origin + * via CORS, which packaged builds enforce. A JSON `body` makes it a POST. + */ +async function gerritRequest(account: Account, pathname: string, body?: unknown): Promise { + const base = getGerritApiBaseUrl(account.hostname); + const url = new URL(pathname.replace(/^\//, ''), base); + + const response = await sendGerritRequest({ + url: url.toString(), + method: body === undefined ? 'GET' : 'POST', + authorization: await basicAuthorization(account), + body: body === undefined ? undefined : JSON.stringify(body), + }); + + if (response.status < 200 || response.status >= 300) { + throw apiError(response.status, response.statusText); + } + if (!response.body) { + return undefined as T; + } + + return JSON.parse(stripGerritXssiPrefix(response.body)) as T; +} + +function buildChangesQuery(start: number): string { + const params = new URLSearchParams(); + // Attention Set is the only Gerrit mechanism with genuine per-user, + // per-change server-side "needs action" state — the closest analogue to + // an unread notification. See ForgeAdapter contract docs on `gerrit/adapter.ts`. + // + // Known scope limitation (accepted trade-off, not a bug): per Gerrit's own + // rules ("If an active change is submitted, abandoned or reset to + // 'work in progress', then all users are removed from the attention set" — + // https://gerrit-review.googlesource.com/Documentation/user-attention-set.html#_rules), + // reviewing a change already removes you from its attention set, and a + // subsequent submit/merge by someone else clears it for everyone. So a + // change you reviewed that later gets merged by another user will *not* + // reappear here, even though Gerrit still emails you about the merge + // (Gerrit's email notifications follow participation/watch settings, not + // attention-set membership). Broadening the query to also catch this would + // require synthesizing an expiring, non-server-backed "unread" state for + // those entries — a deliberate design choice against for now, to keep + // "mark as read" a real, honest server call for every notification this + // adapter returns. + params.set('q', 'attention:self'); + // Cheap (no extra round-trip): needed so `owner`/`attention_set` accounts + // include name/username/email rather than just a numeric id. + params.append('o', 'DETAILED_ACCOUNTS'); + params.set('n', String(PAGE_SIZE)); + if (start > 0) { + params.set('S', String(start)); + } + return params.toString(); +} + +export async function listGerritChanges(account: Account): Promise { + const query = buildChangesQuery(0); + + if (!useSettingsStore.getState().fetchAllNotifications) { + return gerritRequest(account, `changes/?${query}`); + } + + const all: GerritChangeInfo[] = []; + let start = 0; + + while (true) { + const batch = await gerritRequest( + account, + `changes/?${buildChangesQuery(start)}`, + ); + if (!batch.length) { + break; + } + all.push(...batch); + const last = batch[batch.length - 1]; + if (!last._more_changes) { + break; + } + start += batch.length; + } + + return all; +} + +export interface GerritAuthenticatedUserResult { + account: GerritAccountInfo; + /** `undefined` when the version endpoint could not be read (e.g. blocked by server config). */ + version: string | undefined; +} + +export async function fetchGerritAuthenticatedUser( + account: Account, +): Promise { + const [accountInfo, version] = await Promise.all([ + gerritRequest(account, 'accounts/self'), + fetchGerritServerVersion(account), + ]); + + return { account: accountInfo, version }; +} + +/** + * Fetch the Gerrit server version string (e.g. "3.13.2"). + * + * Resolves to `undefined` rather than rejecting when the endpoint is + * unreachable — some servers restrict it, and an account whose version can't + * be determined should not be hard-blocked from logging in. + */ +async function fetchGerritServerVersion(account: Account): Promise { + try { + const info = await gerritRequest( + account, + 'config/server/version?verbose', + ); + return typeof info === 'string' ? info : info?.gerrit_version; + } catch { + return undefined; + } +} + +/** + * Remove the calling user from a change's attention set — Gerrit's closest + * equivalent to "mark as read" (the change stops matching `attention:self` + * on the next poll). Uses the `POST .../delete` alias rather than `DELETE` + * with a body, which is more broadly compatible with HTTP clients/proxies. + * + * `changeId` must be a Gerrit `{change-id}` as returned by the API (e.g. + * `ChangeInfo.id`, which is `RawGitifyNotification.id` for this adapter — + * see `transform.ts`), i.e. `~<_number>` with `project` *already* + * URL-encoded by Gerrit itself. Do NOT `encodeURIComponent` it again here: + * that would double-encode the `%` from an already-encoded `%2F` (nested + * project name) into `%252F`, which Gerrit cannot resolve back to a real + * project and 404s on. + */ +export async function removeSelfFromAttentionSet( + account: Account, + changeId: string, + reason: string, +): Promise { + await gerritRequest(account, `changes/${changeId}/attention/self/delete`, { reason }); +} + +/** + * GET an arbitrary Gerrit URL returned by the API. The URL must point at the + * same origin as the authenticated account — we never send credentials to a + * different host. + */ +export async function gerritGetJson(account: Account, url: string): Promise { + const expected = getGerritApiBaseUrl(account.hostname); + let parsed: URL; + try { + parsed = new URL(url); + } catch { + throw new Error('Refusing to follow malformed Gerrit URL.'); + } + if (parsed.protocol !== 'https:' || parsed.host !== expected.host) { + throw new Error( + `Refusing to follow cross-origin Gerrit URL for account on ${account.hostname}.`, + ); + } + + return gerritRequest(account, parsed.toString()); +} diff --git a/src/renderer/utils/forges/gerrit/transform.test.ts b/src/renderer/utils/forges/gerrit/transform.test.ts new file mode 100644 index 000000000..2e4125497 --- /dev/null +++ b/src/renderer/utils/forges/gerrit/transform.test.ts @@ -0,0 +1,117 @@ +import { mockGitHubCloudAccount } from '../../../__mocks__/account-mocks'; + +import type { Account, Hostname } from '../../../types'; +import type { GerritChangeInfo } from './types'; + +import { toIsoTimestamp, transformGerritChanges } from './transform'; + +describe('renderer/utils/forges/gerrit/transform.ts', () => { + const gerritAccount: Account = { + ...mockGitHubCloudAccount, + forge: 'gerrit', + platform: 'Gerrit', + hostname: 'gerrit.example.com' as Hostname, + }; + + function buildChange(overrides: Partial = {}): GerritChangeInfo { + return { + id: 'platform%2Fframeworks%2Fbase~1234', + project: 'platform/frameworks/base', + branch: 'main', + change_id: 'Iabc123', + subject: 'Fix a bug', + status: 'NEW', + created: '2024-01-15 10:00:00.000000000', + updated: '2024-01-15 12:00:00.123456789', + _number: 1234, + owner: { _account_id: 7, username: 'jdoe', name: 'John Doe' }, + ...overrides, + }; + } + + it('maps a change to a GitifyNotification, always unread', () => { + const [n] = transformGerritChanges([buildChange()], gerritAccount); + + expect(n.id).toBe('platform%2Fframeworks%2Fbase~1234'); + expect(n.unread).toBe(true); + expect(n.reason.code).toBe('review_requested'); + expect(n.subject.type).toBe('PullRequest'); + expect(n.subject.title).toBe('Fix a bug'); + expect(n.subject.number).toBe(1234); + expect(n.subject.state).toBe('OPEN'); + expect(n.subject.htmlUrl).toBe( + 'https://gerrit.example.com/c/platform%2Fframeworks%2Fbase/+/1234', + ); + expect(n.subject.url).toBe( + 'https://gerrit.example.com/a/changes/platform%2Fframeworks%2Fbase~1234', + ); + }); + + it('uses the author reason when the caller owns the change', () => { + const ownAccount: Account = { ...gerritAccount, user: { ...gerritAccount.user!, id: '7' } }; + const [n] = transformGerritChanges([buildChange()], ownAccount); + + expect(n.reason.code).toBe('author'); + }); + + it('maps repository from a nested project namespace', () => { + const [n] = transformGerritChanges([buildChange()], gerritAccount); + + expect(n.repository.fullName).toBe('platform/frameworks/base'); + expect(n.repository.name).toBe('base'); + expect(n.repository.owner.login).toBe('platform/frameworks'); + expect(n.repository.htmlUrl).toBe( + 'https://gerrit.example.com/admin/repos/platform%2Fframeworks%2Fbase', + ); + }); + + it('falls back to the project name as owner login when there is no nesting', () => { + const [n] = transformGerritChanges([buildChange({ project: 'standalone' })], gerritAccount); + + expect(n.repository.name).toBe('standalone'); + expect(n.repository.owner.login).toBe('standalone'); + }); + + it.each([ + ['NEW', undefined, 'OPEN'], + ['NEW', true, 'DRAFT'], + ['MERGED', undefined, 'MERGED'], + ['ABANDONED', undefined, 'CLOSED'], + ] as const)('maps status=%s, work_in_progress=%s to state %s', (status, wip, expected) => { + const [n] = transformGerritChanges( + [buildChange({ status, work_in_progress: wip })], + gerritAccount, + ); + + expect(n.subject.state).toBe(expected); + }); + + it('maps the owner onto subject.author/user, falling back to email/id when name/username are absent', () => { + const [n] = transformGerritChanges( + [buildChange({ owner: { _account_id: 9, email: 'anon@example.com' } })], + gerritAccount, + ); + + expect(n.subject.author?.login).toBe('anon@example.com'); + expect(n.subject.user?.login).toBe('anon@example.com'); + + const [withOnlyId] = transformGerritChanges( + [buildChange({ owner: { _account_id: 9 } })], + gerritAccount, + ); + expect(withOnlyId.subject.author?.login).toBe('9'); + }); +}); + +describe('renderer/utils/forges/gerrit/transform.ts toIsoTimestamp', () => { + it('converts a Gerrit timestamp into a parseable ISO-8601 string', () => { + expect(toIsoTimestamp('2024-01-15 12:00:00.123456789')).toBe('2024-01-15T12:00:00.123Z'); + expect(new Date(toIsoTimestamp('2024-01-15 12:00:00.123456789')).toISOString()).toBe( + '2024-01-15T12:00:00.123Z', + ); + }); + + it('pads short fractional seconds', () => { + expect(toIsoTimestamp('2024-01-15 12:00:00.5')).toBe('2024-01-15T12:00:00.500Z'); + }); +}); diff --git a/src/renderer/utils/forges/gerrit/transform.ts b/src/renderer/utils/forges/gerrit/transform.ts new file mode 100644 index 000000000..c484b5067 --- /dev/null +++ b/src/renderer/utils/forges/gerrit/transform.ts @@ -0,0 +1,139 @@ +import { + type Account, + type GitifyNotificationUser, + type GitifyPullRequestState, + type GitifyRepository, + type GitifySubject, + type RawGitifyNotification, + type Reason, + toLink, +} from '../../../types'; +import type { GerritAccountInfo, GerritChangeInfo } from './types'; + +import { getReasonDetails } from '../../notifications/reason'; + +// A Gerrit change is only ever returned by the `attention:self` query while +// the caller is expected to act on it: on someone else's change that means +// "review requested"; on the caller's own change, a reviewer is waiting on them. +function getReason(raw: GerritChangeInfo, account: Account): Reason { + return String(raw.owner?._account_id) === account.user?.id ? 'author' : 'review_requested'; +} + +export function transformGerritChanges( + raw: GerritChangeInfo[], + account: Account, +): RawGitifyNotification[] { + return raw.map((change) => transformGerritChange(change, account)); +} + +function transformGerritChange(raw: GerritChangeInfo, account: Account): RawGitifyNotification { + const reason = getReason(raw, account); + const reasonDetails = getReasonDetails(reason); + + return { + id: raw.id, + // Every result of the `attention:self` query is, by definition, a change + // still awaiting the caller's attention — there is no "read but still + // listed" state in this model. Removing the account from the attention + // set (`markThreadAsRead`) is what makes an entry disappear. + unread: true, + updatedAt: toIsoTimestamp(raw.updated), + reason: { + code: reason, + title: reasonDetails.title, + description: reasonDetails.description ?? '', + }, + subject: transformSubject(raw, account), + repository: transformRepository(raw, account), + account, + order: 0, + }; +} + +function transformSubject(raw: GerritChangeInfo, account: Account): GitifySubject { + return { + title: raw.subject, + // Reuses GitHub's vocabulary (same precedent as Gitea mapping "Pull" -> + // 'PullRequest') so the shared icon/state-filter/type-filter code applies + // without any Gerrit-specific branching outside this adapter. + type: 'PullRequest', + url: toLink(buildChangeApiUrl(account, raw)), + latestCommentUrl: null, + number: raw._number, + state: mapState(raw), + htmlUrl: toLink(buildChangeWebUrl(account, raw)), + author: mapAccount(raw.owner, account), + user: mapAccount(raw.owner, account), + }; +} + +function mapState(raw: GerritChangeInfo): GitifyPullRequestState { + if (raw.status === 'MERGED') { + return 'MERGED'; + } + if (raw.status === 'ABANDONED') { + return 'CLOSED'; + } + return raw.work_in_progress ? 'DRAFT' : 'OPEN'; +} + +function transformRepository(raw: GerritChangeInfo, account: Account): GitifyRepository { + // Gerrit projects can be nested (e.g. "platform/frameworks/base"). There is + // no user/org "owner" concept the way GitHub has one, so the namespace + // prefix (if any) is used as a best-effort grouping for the UI. + const segments = raw.project.split('/'); + const name = segments.at(-1) || raw.project; + const ownerLogin = segments.length > 1 ? segments.slice(0, -1).join('/') : raw.project; + + return { + name, + fullName: raw.project, + htmlUrl: toLink(`https://${account.hostname}/admin/repos/${encodeURIComponent(raw.project)}`), + owner: { + login: ownerLogin, + avatarUrl: toLink(''), + type: 'Organization', + }, + }; +} + +function mapAccount( + owner: GerritAccountInfo | undefined, + account: Account, +): GitifyNotificationUser | undefined { + if (!owner) { + return undefined; + } + + const login = owner.username ?? owner.name ?? owner.email ?? String(owner._account_id); + const profileUrl = owner.username + ? `https://${account.hostname}/q/owner:${encodeURIComponent(owner.username)}` + : `https://${account.hostname}`; + + return { + login, + avatarUrl: toLink(owner.avatars?.[0]?.url ?? ''), + htmlUrl: toLink(profileUrl), + type: 'User', + }; +} + +function buildChangeWebUrl(account: Account, raw: GerritChangeInfo): string { + return `https://${account.hostname}/c/${encodeURIComponent(raw.project)}/+/${raw._number}`; +} + +function buildChangeApiUrl(account: Account, raw: GerritChangeInfo): string { + return `https://${account.hostname}/a/changes/${encodeURIComponent(raw.project)}~${raw._number}`; +} + +/** + * Convert a Gerrit timestamp (`"yyyy-MM-dd HH:mm:ss.fffffffff"`, always UTC) + * into an ISO-8601 string so shared code (sorting, relative-time display) + * can parse it with `new Date(...)`. + */ +export function toIsoTimestamp(gerritTimestamp: string): string { + const [datePart, timePart = ''] = gerritTimestamp.split(' '); + const [seconds, fractional = ''] = timePart.split('.'); + const milliseconds = fractional.slice(0, 3).padEnd(3, '0'); + return `${datePart}T${seconds}.${milliseconds}Z`; +} diff --git a/src/renderer/utils/forges/gerrit/types.ts b/src/renderer/utils/forges/gerrit/types.ts new file mode 100644 index 000000000..ff6151f1d --- /dev/null +++ b/src/renderer/utils/forges/gerrit/types.ts @@ -0,0 +1,70 @@ +/** + * Subset of the Gerrit Code Review REST API JSON entities used by this + * adapter. Field names follow the JSON shape returned by the Gerrit REST API + * (snake_case, as documented). + * + * @see https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html + * @see https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html + * @see https://gerrit-review.googlesource.com/Documentation/rest-api-config.html + */ + +/** `ChangeInfo.status` — Gerrit has no "draft"/"WIP" status; that's the separate `work_in_progress` flag. */ +export type GerritChangeStatus = 'NEW' | 'MERGED' | 'ABANDONED'; + +/** + * Subset of `AccountInfo`. + * + * `name`/`email`/`username`/`display_name` are only populated when the + * request includes `DETAILED_ACCOUNTS` (or for the calling user's own + * `self` account, which Gerrit always returns in full). + */ +export interface GerritAccountInfo { + _account_id: number; + name?: string; + display_name?: string; + email?: string; + username?: string; + avatars?: GerritAvatarInfo[]; +} + +export interface GerritAvatarInfo { + url: string; + height: number; +} + +/** Entry in `ChangeInfo.attention_set`, keyed by account id. */ +export interface GerritAttentionSetInfo { + account: GerritAccountInfo; + last_update: string; + reason: string; +} + +/** + * Subset of `ChangeInfo` — only the fields this adapter maps onto a + * `RawGitifyNotification`. + */ +export interface GerritChangeInfo { + /** `~<_number>`, URL-encoded. Stable id, safe to use as the {change-id} path segment on subsequent requests. */ + id: string; + project: string; + branch: string; + change_id: string; + subject: string; + status: GerritChangeStatus; + /** Gerrit timestamp format: `"yyyy-MM-dd HH:mm:ss.fffffffff"`, always UTC. */ + created: string; + updated: string; + _number: number; + owner: GerritAccountInfo; + work_in_progress?: boolean; + is_private?: boolean; + /** Present when this change matched an `attention:self`-style query — maps account id (as string key) to attention-set metadata. */ + attention_set?: Record; + /** Set on the last change of a page when more results are available. */ + _more_changes?: boolean; +} + +/** Verbose response shape for `GET /config/server/version?verbose`. */ +export interface GerritServerVersionInfo { + gerrit_version: string; +} diff --git a/src/renderer/utils/forges/registry.test.ts b/src/renderer/utils/forges/registry.test.ts index 5df4e1ec6..9a6184a5d 100644 --- a/src/renderer/utils/forges/registry.test.ts +++ b/src/renderer/utils/forges/registry.test.ts @@ -2,6 +2,7 @@ import { expectTypeOf } from 'vite-plus/test'; import { mockBitbucketAccount, + mockGerritAccount, mockGiteaAccount, mockGitHubCloudAccount, mockGitHubEnterpriseServerAccount, @@ -21,6 +22,19 @@ import { } from './registry'; describe('renderer/utils/forges/registry.ts', () => { + it('binds Gerrit account operations and dashboard links', () => { + expect(getAdapter(mockGerritAccount).getPlatform(mockGerritAccount.hostname)).toBe('Gerrit'); + const adapter = getAccountAdapter(mockGerritAccount); + expect(adapter.getIssuesUrl()).toBeUndefined(); + expect(adapter.getPullRequestsUrl()).toBe( + 'https://gerrit.example.com/q/status:open+owner:jdoe', + ); + expect(adapter.getNotificationsUrl()).toBe('https://gerrit.example.com/q/attention:jdoe'); + expect(adapter.getAccountProfileUrl?.()).toBe('https://gerrit.example.com/q/owner:jdoe'); + expect(adapter.capabilities.markAsDone()).toBe(false); + expect(adapter.capabilities.unsubscribeThread()).toBe(false); + expect(isKnownForge('gerrit')).toBe(true); + }); describe('getAdapter', () => { it('returns the GitHub adapter for github accounts', () => { expect(getAdapter(mockGitHubCloudAccount).id).toBe('github'); @@ -184,11 +198,13 @@ describe('renderer/utils/forges/registry.ts', () => { describe('listAdapters / KNOWN_FORGES', () => { it('returns every registered adapter', () => { const ids = listAdapters().map((a) => a.id); - expect(ids).toEqual(expect.arrayContaining(['github', 'gitea', 'bitbucket', 'gitlab'])); + expect(ids).toEqual( + expect.arrayContaining(['github', 'gitea', 'bitbucket', 'gitlab', 'gerrit']), + ); }); it('every Forge value has a registered adapter (exhaustive)', () => { - const forges: Forge[] = ['github', 'gitea', 'bitbucket', 'gitlab']; + const forges: Forge[] = ['github', 'gitea', 'bitbucket', 'gitlab', 'gerrit']; for (const id of forges) { expect(KNOWN_FORGES.has(id)).toBe(true); expect(() => getAdapter(id)).not.toThrow(); diff --git a/src/renderer/utils/forges/registry.ts b/src/renderer/utils/forges/registry.ts index 87796631f..13a0f03c8 100644 --- a/src/renderer/utils/forges/registry.ts +++ b/src/renderer/utils/forges/registry.ts @@ -2,6 +2,7 @@ import type { Account, Forge, Link } from '../../types'; import type { ForgeAccountAdapter, ForgeAdapter } from './types'; import { bitbucketAdapter } from './bitbucket/adapter'; +import { gerritAdapter } from './gerrit/adapter'; import { giteaAdapter } from './gitea/adapter'; import { githubAdapter } from './github/adapter'; import { gitlabAdapter } from './gitlab/adapter'; @@ -19,6 +20,7 @@ const ADAPTERS: Record = { gitea: giteaAdapter, bitbucket: bitbucketAdapter, gitlab: gitlabAdapter, + gerrit: gerritAdapter, }; /** Single source of truth for the runtime set of registered forges. */ @@ -52,6 +54,7 @@ export function getAccountAdapter(account: Account): ForgeAccountAdapter { // Optional method, so bind it to keep a single reference and avoid an unbound // method reference (the adapter ops are otherwise called as `accountOps.x(...)`). const onAccountTokenChange = accountOps.onAccountTokenChange?.bind(accountOps); + const getAccountProfileUrl = accountOps.getAccountProfileUrl?.bind(accountOps); return { capabilities: { @@ -70,6 +73,7 @@ export function getAccountAdapter(account: Account): ForgeAccountAdapter { getIssuesUrl: () => accountOps.getIssuesUrl(account), getPullRequestsUrl: () => accountOps.getPullRequestsUrl(account), getNotificationsUrl: () => accountOps.getNotificationsUrl(account), + getAccountProfileUrl: getAccountProfileUrl ? () => getAccountProfileUrl(account) : undefined, oauthScopes: oauthScopes ? { hasRequired: () => oauthScopes.hasRequired(account), diff --git a/src/renderer/utils/forges/types.ts b/src/renderer/utils/forges/types.ts index bd7fc5362..d01ef80b6 100644 --- a/src/renderer/utils/forges/types.ts +++ b/src/renderer/utils/forges/types.ts @@ -241,11 +241,13 @@ export interface ForgeAccountAdapter { */ getAccountSettingsUrl(): Link; /** URL to the forge's "my issues" list for the account's host. */ - getIssuesUrl(): Link; + getIssuesUrl(): Link | undefined; /** URL to the forge's "my pull requests" list for the account's host. */ getPullRequestsUrl(): Link; /** URL to the forge's notification centre for the account's host. */ getNotificationsUrl(): Link; + /** Forge-specific account profile; absent for forges using the standard user path. */ + getAccountProfileUrl?(): Link; /** * OAuth scope checks. Forges with no scope concept (e.g. Gitea) omit this @@ -288,9 +290,10 @@ export interface ForgeAccountOperations { unsubscribeThread(account: Account, threadId: string): Promise; followUrl(account: Account, url: Link): Promise; getAccountSettingsUrl(account: Account): Link; - getIssuesUrl(account: Account): Link; + getIssuesUrl(account: Account): Link | undefined; getPullRequestsUrl(account: Account): Link; getNotificationsUrl(account: Account): Link; + getAccountProfileUrl?(account: Account): Link; readonly oauthScopes?: { hasRequired(account: Account): boolean; hasRecommended(account: Account): boolean; diff --git a/src/renderer/utils/system/comms.ts b/src/renderer/utils/system/comms.ts index f482031c2..fe23d2b55 100644 --- a/src/renderer/utils/system/comms.ts +++ b/src/renderer/utils/system/comms.ts @@ -1,4 +1,6 @@ import type { + IGerritRequest, + IGerritResponse, IGitHubCliTokenResult, ISafeStorageDecryptResult, TrayIconAppearance, @@ -65,6 +67,16 @@ export async function readGitHubCliToken(hostname: string): Promise { + return await window.gitify.gerritRequest(request); +} + /** * Quit the application. */ diff --git a/src/renderer/utils/system/links.test.ts b/src/renderer/utils/system/links.test.ts index 360381ee1..e938f76e0 100644 --- a/src/renderer/utils/system/links.test.ts +++ b/src/renderer/utils/system/links.test.ts @@ -1,5 +1,6 @@ import { mockBitbucketAccount, + mockGerritAccount, mockGiteaAccount, mockGitHubCloudAccount, mockGitLabAccount, @@ -30,6 +31,20 @@ import { describe('renderer/utils/links.ts', () => { const openExternalLinkSpy = vi.spyOn(comms, 'openExternalLink').mockImplementation(vi.fn()); + it('uses Gerrit queries for account links and does not open an issues page', () => { + openHostIssues(mockGerritAccount); + expect(openExternalLinkSpy).not.toHaveBeenCalled(); + openHostPulls(mockGerritAccount); + expect(openExternalLinkSpy).toHaveBeenLastCalledWith( + 'https://gerrit.example.com/q/status:open+owner:jdoe', + ); + openAccountProfile(mockGerritAccount); + expect(openExternalLinkSpy).toHaveBeenLastCalledWith('https://gerrit.example.com/q/owner:jdoe'); + openHostNotifications(mockGerritAccount); + expect(openExternalLinkSpy).toHaveBeenLastCalledWith( + 'https://gerrit.example.com/q/attention:jdoe', + ); + }); it('openGitifyReleaseNotes', () => { openGitifyReleaseNotes('v1.0.0'); diff --git a/src/renderer/utils/system/links.ts b/src/renderer/utils/system/links.ts index 9e2d594ec..d9ac4965a 100644 --- a/src/renderer/utils/system/links.ts +++ b/src/renderer/utils/system/links.ts @@ -25,7 +25,10 @@ export function openHostNotifications(account: Account) { } export function openHostIssues(account: Account) { - openExternalLink(getAccountAdapter(account).getIssuesUrl()); + const url = getAccountAdapter(account).getIssuesUrl(); + if (url) { + openExternalLink(url); + } } export function openHostPulls(account: Account) { @@ -33,6 +36,11 @@ export function openHostPulls(account: Account) { } export function openAccountProfile(account: Account) { + const profileUrl = getAccountAdapter(account).getAccountProfileUrl?.(); + if (profileUrl) { + openExternalLink(profileUrl); + return; + } const url = new URL(getAccountOrigin(account)); url.pathname = account.user!.login; openExternalLink(url.toString() as Link); diff --git a/src/renderer/utils/ui/icons.ts b/src/renderer/utils/ui/icons.ts index 926886fdf..768cfca2a 100644 --- a/src/renderer/utils/ui/icons.ts +++ b/src/renderer/utils/ui/icons.ts @@ -25,6 +25,7 @@ import type { PlatformType } from '../auth/types'; import i18n from '../../i18n'; import { BitbucketIcon } from '../../icons/BitbucketIcon'; +import { GerritIcon } from '../../icons/GerritIcon'; import { GitLabIcon } from '../../icons/GitLabIcon'; import type { PullRequestReviewState } from '../forges/github/graphql/generated/graphql'; @@ -87,6 +88,8 @@ export function getPlatformIcon(platform: PlatformType): FC | null return BitbucketIcon; case 'Gitea': return ServerIcon; + case 'Gerrit': + return GerritIcon; case 'GitLab Cloud': case 'GitLab Self-Managed': return GitLabIcon; diff --git a/src/shared/events.ts b/src/shared/events.ts index d364798e1..fcef43264 100644 --- a/src/shared/events.ts +++ b/src/shared/events.ts @@ -24,6 +24,7 @@ export const EVENTS = { SAFE_STORAGE_ENCRYPT: `${P}safe-storage-encrypt`, SAFE_STORAGE_DECRYPT: `${P}safe-storage-decrypt`, GITHUB_CLI_TOKEN: `${P}github-cli-token`, + GERRIT_REQUEST: `${P}gerrit-request`, NOTIFICATION_SOUND_PATH: `${P}notification-sound-path`, OPEN_EXTERNAL: `${P}open-external`, RESET_APP: `${P}reset-app`, @@ -127,6 +128,24 @@ export type IGitHubCliTokenResult = | { token: string; error?: never; detail?: never } | { token?: never; error: GitHubCliTokenError; detail?: string }; +/** + * An authenticated Gerrit REST call, run by the main process because Gerrit + * servers rarely allow the renderer's origin via CORS. + */ +export interface IGerritRequest { + url: string; + method: 'GET' | 'POST'; + authorization: string; + body?: string; +} + +/** Raw Gerrit HTTP response; the renderer parses the body. */ +export interface IGerritResponse { + status: number; + statusText: string; + body: string; +} + /** A structured request to publish an operating-system notification. */ export interface INativeNotificationPayload { /** Short, opaque identity for this notification. */ @@ -208,6 +227,7 @@ export type EventContracts = AssertEventCoverage<{ request: string; response: IGitHubCliTokenResult; }; + [EVENTS.GERRIT_REQUEST]: { request: IGerritRequest; response: IGerritResponse }; [EVENTS.NOTIFICATION_SOUND_PATH]: { request: undefined; response: string }; [EVENTS.OPEN_EXTERNAL]: { request: IOpenExternal; response: undefined }; [EVENTS.RESET_APP]: { request: undefined; response: undefined };