diff --git a/changelog.md b/changelog.md index d6229d6..f266b20 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,15 @@ # Changelog +## 2026-03-02 - 1.5.0 - feat(gitea) +add domain model classes, helpers, and refactor GiteaClient internals; expand README with usage and docs + +- Introduce domain classes: GiteaOrganization, GiteaRepository, GiteaActionRun, GiteaActionRunJob (+steps), GiteaBranch, GiteaTag, GiteaSecret +- Add helper utilities: autoPaginate, computeDuration, resolveGiteaStatus, extractRefFromPath, extractWorkflowIdFromPath, toGiteaApiStatus +- Refactor GiteaClient: consolidate low-level request helpers, add internal request* methods for action-run/job endpoints, requestText/requestBinary support, and PATCH support +- Update raw API interfaces (IGiteaActionRun, IGiteaRepository, IGiteaOrganization, IGiteaUser) to match Gitea 1.25 shapes +- Export new domain classes, helpers and commit info from ts/index.ts +- Revise README: Quick Start, class/method documentation, license and company info + ## 2026-03-02 - 1.4.0 - feat(gitea) add Actions API support: list filters, run/job endpoints, dispatch, and richer types diff --git a/readme.md b/readme.md index da1b79c..7b5a3bc 100644 --- a/readme.md +++ b/readme.md @@ -1,6 +1,10 @@ # @apiclient.xyz/gitea -A TypeScript client for the Gitea API, providing typed access to repositories, organizations, secrets management, and Gitea Actions workflow runs. +A fully typed TypeScript client for the Gitea API. Manage repositories, organizations, secrets, branches, tags, and CI/CD action runs with a clean, object-oriented interface and built-in auto-pagination. + +## Issue Reporting and Security + +For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly. ## Install @@ -10,11 +14,32 @@ npm install @apiclient.xyz/gitea pnpm install @apiclient.xyz/gitea ``` +## Quick Start + +```typescript +import { GiteaClient } from '@apiclient.xyz/gitea'; + +// 1. Connect to your Gitea instance +const client = new GiteaClient('https://gitea.example.com', 'your-api-token'); + +// 2. Verify the connection +const { ok } = await client.testConnection(); +console.log(ok ? '✅ Connected!' : '❌ Connection failed'); + +// 3. List all your repos +const repos = await client.getRepos(); +repos.forEach(repo => console.log(`📦 ${repo.fullName}`)); +``` + +That's it — you're up and running. 🚀 + ## Usage -All examples below use ESM imports and top-level `await`. The package ships as a pure ESM module with full TypeScript type declarations. +All examples use ESM imports and top-level `await`. The package ships as a **pure ESM module** with full TypeScript type declarations. -### Creating a Client +--- + +### 🔌 Creating a Client ```typescript import { GiteaClient } from '@apiclient.xyz/gitea'; @@ -22,9 +47,10 @@ import { GiteaClient } from '@apiclient.xyz/gitea'; const client = new GiteaClient('https://gitea.example.com', 'your-api-token'); ``` -The `baseUrl` should point to your Gitea instance root (trailing slashes are stripped automatically). The `token` is an API token generated in Gitea under **Settings > Applications**. +- `baseUrl` — Your Gitea instance root URL (trailing slashes are stripped automatically) +- `token` — An API token generated in Gitea under **Settings > Applications** -### Testing the Connection +### 🩺 Testing the Connection ```typescript const result = await client.testConnection(); @@ -36,133 +62,340 @@ if (result.ok) { } ``` -### Listing Repositories +--- + +### 📦 Repositories + +The client returns rich `GiteaRepository` objects with built-in methods for managing branches, tags, secrets, action runs, and more. + +#### List / Search Repositories ```typescript -// Fetch the first page of repositories (default: 50 per page, sorted by updated) -const repos = await client.getRepos(); +// Get all repositories (auto-paginated — fetches every page automatically) +const allRepos = await client.getRepos(); -// Search with pagination -const results = await client.getRepos({ - search: 'my-project', - page: 1, - perPage: 20, -}); +// Search with a query +const results = await client.getRepos({ search: 'my-project' }); + +// Grab a specific page +const page2 = await client.getRepos({ page: 2, perPage: 20 }); for (const repo of results) { - console.log(`${repo.full_name} - ${repo.description}`); + console.log(`${repo.fullName} — ${repo.description}`); + console.log(` Default branch: ${repo.defaultBranch}`); + console.log(` Private: ${repo.isPrivate}`); + console.log(` Topics: ${repo.topics.join(', ')}`); } ``` -### Listing Organizations +#### Get a Single Repository ```typescript +const repo = await client.getRepo('my-org/my-repo'); +console.log(repo.fullName, repo.htmlUrl); +``` + +#### Create a Repository in an Organization + +```typescript +const newRepo = await client.createOrgRepo('my-org', 'new-service', { + description: 'A brand new microservice', + private: true, +}); +console.log(`Created: ${newRepo.htmlUrl}`); +``` + +#### Update Repository Properties + +```typescript +const repo = await client.getRepo('my-org/my-repo'); + +await repo.update({ + description: 'Updated description', + defaultBranch: 'develop', + private: false, + archived: false, +}); +``` + +#### Manage Topics + +```typescript +await repo.setTopics(['typescript', 'api', 'gitea']); +``` + +#### Avatars + +```typescript +// Upload an avatar (base64-encoded image) +await repo.setAvatar(base64ImageString); + +// Remove the avatar +await repo.deleteAvatar(); +``` + +#### Transfer Ownership + +```typescript +await repo.transfer('new-owner-org'); +``` + +#### Delete a Repository + +```typescript +await repo.delete(); +``` + +--- + +### 🏢 Organizations + +Organizations are returned as rich `GiteaOrganization` objects. + +#### List All Organizations + +```typescript +// Auto-paginated — fetches every org across all pages const orgs = await client.getOrgs(); for (const org of orgs) { - console.log(`${org.name} (${org.repo_count} repos)`); + console.log(`${org.name} (${org.repoCount} repos) — ${org.visibility}`); } - -// With pagination -const page2 = await client.getOrgs({ page: 2, perPage: 10 }); ``` -### Managing Repository Secrets +#### Get a Single Organization ```typescript -const ownerRepo = 'my-org/my-repo'; +const org = await client.getOrg('my-org'); +console.log(org.fullName, org.description); +``` -// List all secrets for a repository -const secrets = await client.getRepoSecrets(ownerRepo); +#### Create an Organization + +```typescript +const newOrg = await client.createOrg('new-team', { + fullName: 'New Team', + description: 'Our shiny new team', + visibility: 'public', +}); +``` + +#### List Repos in an Organization + +```typescript +const org = await client.getOrg('my-org'); +const repos = await org.getRepos({ search: 'api' }); +``` + +#### Update Organization Properties + +```typescript +await org.update({ + description: 'Updated org description', + visibility: 'private', + fullName: 'My Organization (Renamed)', +}); +``` + +#### Organization Avatars + +```typescript +await org.setAvatar(base64ImageString); +await org.deleteAvatar(); +``` + +#### Delete an Organization + +```typescript +await org.delete(); +``` + +--- + +### 🔑 Secrets Management + +Manage Gitea Actions secrets at both the **repository** and **organization** level. Perfect for CI/CD automation. + +#### Repository Secrets + +```typescript +const repo = await client.getRepo('my-org/my-repo'); + +// List all secrets +const secrets = await repo.getSecrets(); for (const secret of secrets) { - console.log(`${secret.name} (created ${secret.created_at})`); + console.log(`🔒 ${secret.name} (created ${secret.createdAt})`); } // Create or update a secret -await client.setRepoSecret(ownerRepo, 'DEPLOY_TOKEN', 's3cret-value'); +await repo.setSecret('DEPLOY_TOKEN', 's3cret-value'); // Delete a secret -await client.deleteRepoSecret(ownerRepo, 'DEPLOY_TOKEN'); +await repo.deleteSecret('DEPLOY_TOKEN'); ``` -### Managing Organization Secrets +#### Organization Secrets ```typescript -const orgName = 'my-org'; +const org = await client.getOrg('my-org'); -// List all secrets for an organization -const orgSecrets = await client.getOrgSecrets(orgName); +// List all org-level secrets +const orgSecrets = await org.getSecrets(); -// Create or update an organization-level secret -await client.setOrgSecret(orgName, 'NPM_TOKEN', 'npm_abc123'); +// Create or update +await org.setSecret('NPM_TOKEN', 'npm_abc123'); -// Delete an organization-level secret -await client.deleteOrgSecret(orgName, 'NPM_TOKEN'); +// Delete +await org.deleteSecret('NPM_TOKEN'); ``` -### Working with Action Runs +--- + +### 🌿 Branches & Tags + +Fetch branches and tags for any repository — auto-paginated by default. ```typescript -const ownerRepo = 'my-org/my-repo'; +const repo = await client.getRepo('my-org/my-repo'); + +// Get all branches +const branches = await repo.getBranches(); +for (const branch of branches) { + console.log(`Branch: ${branch.name} @ ${branch.commitSha}`); +} + +// Get all tags +const tags = await repo.getTags(); +for (const tag of tags) { + console.log(`Tag: ${tag.name} @ ${tag.commitSha}`); +} +``` + +--- + +### ⚡ Gitea Actions (CI/CD Runs) + +Full support for listing, filtering, inspecting, and managing Gitea Actions workflow runs and jobs. + +#### List Action Runs + +```typescript +const repo = await client.getRepo('my-org/my-repo'); + +// Get all recent runs (auto-paginated) +const runs = await repo.getActionRuns(); -// List recent action runs -const runs = await client.getActionRuns(ownerRepo); for (const run of runs) { - console.log(`#${run.id} ${run.name} [${run.status}/${run.conclusion}] on ${run.head_branch}`); + console.log(`#${run.runNumber} ${run.displayTitle}`); + console.log(` Status: ${run.resolvedStatus}`); + console.log(` Branch: ${run.headBranch}`); + console.log(` Event: ${run.event}`); + console.log(` Duration: ${run.duration}s`); + console.log(` Triggered by: ${run.actorLogin}`); } - -// Paginate runs -const olderRuns = await client.getActionRuns(ownerRepo, { page: 2, perPage: 10 }); - -// Get jobs for a specific run -const jobs = await client.getActionRunJobs(ownerRepo, runs[0].id); -for (const job of jobs) { - console.log(` Job "${job.name}" - ${job.status} (${job.run_duration}s)`); -} - -// Fetch raw log output for a job -const log = await client.getJobLog(ownerRepo, jobs[0].id); -console.log(log); - -// Re-run a workflow -await client.rerunAction(ownerRepo, runs[0].id); - -// Cancel a running workflow -await client.cancelAction(ownerRepo, runs[0].id); ``` -## API Reference +#### Filter Runs -### `GiteaClient` +```typescript +// Filter by status, branch, event, or actor +const failedRuns = await repo.getActionRuns({ status: 'failed' }); +const mainRuns = await repo.getActionRuns({ branch: 'main' }); +const pushRuns = await repo.getActionRuns({ event: 'push' }); +const myRuns = await repo.getActionRuns({ actor: 'phil' }); -| Method | Signature | Returns | Description | -|--------|-----------|---------|-------------| -| `constructor` | `(baseUrl: string, token: string)` | `GiteaClient` | Create a new client instance. | -| `testConnection` | `()` | `Promise` | Verify credentials and connectivity. | -| `getRepos` | `(opts?: IListOptions)` | `Promise` | Search/list repositories with pagination. | -| `getOrgs` | `(opts?: IListOptions)` | `Promise` | List organizations with pagination. | -| `getRepoSecrets` | `(ownerRepo: string)` | `Promise` | List all action secrets for a repository. | -| `setRepoSecret` | `(ownerRepo: string, key: string, value: string)` | `Promise` | Create or update a repository secret. | -| `deleteRepoSecret` | `(ownerRepo: string, key: string)` | `Promise` | Delete a repository secret. | -| `getOrgSecrets` | `(orgName: string)` | `Promise` | List all action secrets for an organization. | -| `setOrgSecret` | `(orgName: string, key: string, value: string)` | `Promise` | Create or update an organization secret. | -| `deleteOrgSecret` | `(orgName: string, key: string)` | `Promise` | Delete an organization secret. | -| `getActionRuns` | `(ownerRepo: string, opts?: IListOptions)` | `Promise` | List action workflow runs for a repository. | -| `getActionRunJobs` | `(ownerRepo: string, runId: number)` | `Promise` | List jobs within a specific action run. | -| `getJobLog` | `(ownerRepo: string, jobId: number)` | `Promise` | Fetch the raw log output for a job. | -| `rerunAction` | `(ownerRepo: string, runId: number)` | `Promise` | Re-run a completed action run. | -| `cancelAction` | `(ownerRepo: string, runId: number)` | `Promise` | Cancel an in-progress action run. | +// Combine filters +const filtered = await repo.getActionRuns({ + status: 'running', + branch: 'develop', + event: 'pull_request', +}); +``` -### Parameter Conventions +**Supported status values:** `running`, `failed`, `pending`, `success`, `skipped`, `waiting`, `canceled` — automatically translated to Gitea's native API values. -- **`ownerRepo`** -- Repository identifier in `"owner/repo"` format (e.g., `"my-org/my-repo"`). -- **`orgName`** -- Organization login name (e.g., `"my-org"`). -- **`key`** -- Secret name, typically uppercase with underscores (e.g., `"DEPLOY_TOKEN"`). -- **`runId` / `jobId`** -- Numeric identifiers returned by the list endpoints. +#### Inspect Jobs & Steps -## Interfaces +```typescript +const runs = await repo.getActionRuns(); +const latestRun = runs[0]; -All interfaces are exported from the package entry point and can be imported for type annotations. +// Get all jobs in a run +const jobs = await latestRun.getJobs(); + +for (const job of jobs) { + console.log(`Job: ${job.name} [${job.resolvedStatus}] (${job.duration}s)`); + console.log(` Runner: ${job.runnerName}`); + + // Inspect individual steps + for (const step of job.steps) { + console.log(` Step ${step.number}: ${step.name} — ${step.resolvedStatus} (${step.duration}s)`); + } +} +``` + +#### Fetch Job Logs + +```typescript +const jobs = await latestRun.getJobs(); +const log = await jobs[0].getLog(); +console.log(log); // Raw log output +``` + +#### Re-run a Workflow + +```typescript +// Re-dispatches the workflow on the same ref +await latestRun.rerun(); + +// With custom inputs +await latestRun.rerun({ environment: 'staging' }); +``` + +#### Delete an Action Run + +```typescript +await latestRun.delete(); +``` + +--- + +### 🔄 Auto-Pagination + +By default, all list methods (`getRepos`, `getOrgs`, `getBranches`, `getTags`, `getActionRuns`, etc.) **auto-paginate** and return every item across all pages. + +To disable auto-pagination and fetch a specific page, pass the `page` option: + +```typescript +// Only fetch page 3 +const page3 = await client.getRepos({ page: 3, perPage: 25 }); +``` + +The `autoPaginate` helper is also exported if you need it for custom endpoints: + +```typescript +import { autoPaginate } from '@apiclient.xyz/gitea'; +``` + +--- + +## 🗂️ Exported Classes + +| Class | Description | +|---|---| +| `GiteaClient` | Main entry point — connects to a Gitea instance | +| `GiteaOrganization` | Rich object for an organization with repos, secrets, avatars | +| `GiteaRepository` | Rich object for a repo with branches, tags, secrets, runs | +| `GiteaBranch` | Branch with name and commit SHA | +| `GiteaTag` | Tag with name and commit SHA | +| `GiteaSecret` | Secret metadata (name + creation timestamp) | +| `GiteaActionRun` | CI/CD workflow run with jobs, rerun, and delete | +| `GiteaActionRunJob` | Individual job within a run, with steps and log access | +| `GiteaActionRunJobStep` | Individual step within a job | + +## 🧩 Exported Interfaces + +All interfaces are exported for type annotations: ```typescript import type { @@ -170,120 +403,136 @@ import type { IGiteaRepository, IGiteaOrganization, IGiteaSecret, + IGiteaBranch, + IGiteaTag, IGiteaActionRun, IGiteaActionRunJob, + IGiteaActionRunJobStep, ITestConnectionResult, IListOptions, + IActionRunListOptions, } from '@apiclient.xyz/gitea'; ``` -### `IListOptions` +## 🛠️ Exported Helpers -Pagination and search options accepted by list methods. +Utility functions for working with Gitea API data: -```typescript -interface IListOptions { - search?: string; // Free-text search query (repos only) - page?: number; // Page number (default: 1) - perPage?: number; // Results per page (default: 50 for repos/orgs, 30 for runs) -} -``` +| Helper | Description | +|---|---| +| `autoPaginate(fetchPage, opts?)` | Auto-paginate any list endpoint | +| `computeDuration(startedAt, completedAt)` | Compute duration in seconds from ISO timestamps | +| `resolveGiteaStatus(status, conclusion)` | Resolve Gitea's split status/conclusion into a single string | +| `extractRefFromPath(path)` | Extract a human-readable ref from Gitea's `path` field | +| `extractWorkflowIdFromPath(path)` | Extract the workflow filename from Gitea's `path` field | +| `toGiteaApiStatus(status)` | Translate friendly status names to Gitea API values | -### `ITestConnectionResult` +--- -```typescript -interface ITestConnectionResult { - ok: boolean; // true if the connection succeeded - error?: string; // Error message when ok is false -} -``` +## Full API Reference -### `IGiteaUser` +### `GiteaClient` -```typescript -interface IGiteaUser { - id: number; - login: string; - full_name: string; - email: string; - avatar_url: string; -} -``` +| Method | Signature | Description | +|---|---|---| +| `constructor` | `(baseUrl: string, token: string)` | Create a new client | +| `testConnection` | `() => Promise` | Verify credentials and connectivity | +| `getRepos` | `(opts?: IListOptions) => Promise` | List/search repositories (auto-paginated) | +| `getRepo` | `(ownerRepo: string) => Promise` | Get a single repository | +| `createOrgRepo` | `(orgName, name, opts?) => Promise` | Create a repo in an organization | +| `getOrgs` | `(opts?: IListOptions) => Promise` | List organizations (auto-paginated) | +| `getOrg` | `(orgName: string) => Promise` | Get a single organization | +| `createOrg` | `(name, opts?) => Promise` | Create a new organization | -### `IGiteaRepository` +### `GiteaRepository` -```typescript -interface IGiteaRepository { - id: number; - name: string; - full_name: string; // "owner/repo" - description: string; - default_branch: string; - html_url: string; - private: boolean; - topics: string[]; - updated_at: string; // ISO 8601 timestamp - owner: { - id: number; - login: string; - avatar_url: string; - }; -} -``` +| Method | Description | +|---|---| +| `getBranches(opts?)` | List branches (auto-paginated) | +| `getTags(opts?)` | List tags (auto-paginated) | +| `getSecrets()` | List repository secrets | +| `setSecret(key, value)` | Create or update a secret | +| `deleteSecret(key)` | Delete a secret | +| `getActionRuns(opts?)` | List CI/CD runs with optional filters | +| `update(data)` | Update repo properties (name, description, default branch, etc.) | +| `setTopics(topics)` | Replace all repository topics | +| `setAvatar(base64)` | Upload an avatar image | +| `deleteAvatar()` | Remove the avatar | +| `transfer(newOwner)` | Transfer ownership | +| `delete()` | Delete the repository | -### `IGiteaOrganization` +### `GiteaOrganization` -```typescript -interface IGiteaOrganization { - id: number; - name: string; - full_name: string; - description: string; - visibility: string; // "public", "limited", or "private" - repo_count: number; -} -``` +| Method | Description | +|---|---| +| `getRepos(opts?)` | List org repositories (auto-paginated) | +| `getSecrets()` | List organization secrets | +| `setSecret(key, value)` | Create or update an org secret | +| `deleteSecret(key)` | Delete an org secret | +| `update(data)` | Update org properties (description, visibility, fullName) | +| `setAvatar(base64)` | Upload an avatar image | +| `deleteAvatar()` | Remove the avatar | +| `delete()` | Delete the organization | -### `IGiteaSecret` +### `GiteaActionRun` -```typescript -interface IGiteaSecret { - name: string; // Secret key name - created_at: string; // ISO 8601 timestamp -} -``` +| Property | Type | Description | +|---|---|---| +| `id` | `number` | Run ID | +| `runNumber` | `number` | Sequential run number | +| `name` | `string` | Workflow name | +| `displayTitle` | `string` | Display title of the run | +| `status` | `string` | Raw status (running, waiting, completed) | +| `conclusion` | `string` | Raw conclusion (success, failure, cancelled) | +| `resolvedStatus` | `string` | **Computed** — single human-readable status | +| `duration` | `number` | **Computed** — duration in seconds | +| `headBranch` | `string` | Branch that triggered the run | +| `headSha` | `string` | Commit SHA | +| `event` | `string` | Trigger event (push, pull_request, etc.) | +| `ref` | `string` | **Computed** — human-readable ref | +| `workflowId` | `string` | **Computed** — workflow filename | +| `actorLogin` | `string` | User who triggered the run | -### `IGiteaActionRun` +| Method | Description | +|---|---| +| `getJobs()` | List all jobs in this run | +| `rerun(inputs?)` | Re-dispatch the workflow on the same ref | +| `delete()` | Delete this action run | -```typescript -interface IGiteaActionRun { - id: number; - name: string; // Workflow name - status: string; // "running", "waiting", "success", "failure", etc. - conclusion: string; // Final result: "success", "failure", "cancelled", etc. - head_branch: string; // Branch that triggered the run - head_sha: string; // Commit SHA - html_url: string; // Web URL for the run - event: string; // Trigger event: "push", "pull_request", etc. - run_duration: number; // Duration in seconds - created_at: string; // ISO 8601 timestamp -} -``` +### `GiteaActionRunJob` -### `IGiteaActionRunJob` +| Property | Type | Description | +|---|---|---| +| `id` | `number` | Job ID | +| `name` | `string` | Job name | +| `resolvedStatus` | `string` | **Computed** — resolved status | +| `duration` | `number` | **Computed** — duration in seconds | +| `steps` | `GiteaActionRunJobStep[]` | Individual steps | +| `runnerName` | `string` | Runner that executed the job | -```typescript -interface IGiteaActionRunJob { - id: number; - name: string; // Job name from the workflow - status: string; - conclusion: string; - run_duration: number; // Duration in seconds -} -``` +| Method | Description | +|---|---| +| `getLog()` | Fetch raw log output for this job | -## License +--- -MIT -- see [LICENSE](./license.md) for details. +## License and Legal Information -Published under the [Lossless GmbH](https://lossless.com) umbrella. +This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file. + +**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. + +### Trademarks + +This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein. + +Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar. + +### Company Information + +Task Venture Capital GmbH +Registered at District Court Bremen HRB 35230 HB, Germany + +For any legal inquiries or further information, please contact us via email at hello@task.vc. + +By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works. diff --git a/ts/00_commitinfo_data.ts b/ts/00_commitinfo_data.ts index 81526bb..f2e74ef 100644 --- a/ts/00_commitinfo_data.ts +++ b/ts/00_commitinfo_data.ts @@ -3,6 +3,6 @@ */ export const commitinfo = { name: '@apiclient.xyz/gitea', - version: '1.4.0', + version: '1.5.0', description: 'A TypeScript client for the Gitea API, providing easy access to repositories, organizations, secrets, and action runs.' } diff --git a/ts/gitea.classes.actionrun.ts b/ts/gitea.classes.actionrun.ts new file mode 100644 index 0000000..beac964 --- /dev/null +++ b/ts/gitea.classes.actionrun.ts @@ -0,0 +1,124 @@ +import type { GiteaClient } from './gitea.classes.giteaclient.js'; +import type { IGiteaActionRun } from './gitea.interfaces.js'; +import { GiteaActionRunJob } from './gitea.classes.actionrunjob.js'; +import { + computeDuration, + resolveGiteaStatus, + extractRefFromPath, + extractWorkflowIdFromPath, +} from './gitea.helpers.js'; + +export class GiteaActionRun { + // Raw data + public readonly id: number; + public readonly runNumber: number; + public readonly runAttempt: number; + public readonly name: string; + public readonly displayTitle: string; + public readonly status: string; + public readonly conclusion: string; + public readonly headBranch: string; + public readonly headSha: string; + public readonly htmlUrl: string; + public readonly event: string; + public readonly path: string; + public readonly startedAt: string; + public readonly completedAt: string; + public readonly actorLogin: string; + public readonly triggerActorLogin: string; + + // Computed + public readonly resolvedStatus: string; + public readonly duration: number; + public readonly ref: string; + public readonly workflowId: string; + + /** @internal */ + constructor( + private client: GiteaClient, + private ownerRepo: string, + raw: IGiteaActionRun, + ) { + this.id = raw.id; + this.runNumber = raw.run_number || 0; + this.runAttempt = raw.run_attempt || 1; + this.name = raw.name || ''; + this.displayTitle = raw.display_title || this.name; + this.status = raw.status || ''; + this.conclusion = raw.conclusion || ''; + this.headBranch = raw.head_branch || ''; + this.headSha = raw.head_sha || ''; + this.htmlUrl = raw.html_url || ''; + this.event = raw.event || ''; + this.path = raw.path || ''; + this.startedAt = raw.started_at || ''; + this.completedAt = raw.completed_at || ''; + this.actorLogin = raw.actor?.login || ''; + this.triggerActorLogin = raw.trigger_actor?.login || ''; + + // Computed properties + this.resolvedStatus = resolveGiteaStatus(this.status, this.conclusion); + this.duration = computeDuration(this.startedAt, this.completedAt); + this.ref = this.headBranch || extractRefFromPath(this.path); + this.workflowId = extractWorkflowIdFromPath(this.path); + } + + // --------------------------------------------------------------------------- + // Jobs + // --------------------------------------------------------------------------- + + async getJobs(): Promise { + const jobs = await this.client.requestGetActionRunJobs(this.ownerRepo, this.id); + return jobs.map(j => new GiteaActionRunJob(this.client, this.ownerRepo, j)); + } + + // --------------------------------------------------------------------------- + // Actions + // --------------------------------------------------------------------------- + + /** + * Re-dispatch this workflow on the same ref. + * Gitea 1.25 has no rerun endpoint, so this dispatches the workflow again. + */ + async rerun(inputs?: Record): Promise { + const wfId = this.workflowId; + if (!wfId) { + throw new Error(`Cannot rerun: no workflow ID found in path "${this.path}"`); + } + await this.client.requestDispatchWorkflow(this.ownerRepo, wfId, this.ref, inputs); + } + + /** + * Delete this action run. + */ + async delete(): Promise { + await this.client.requestDeleteActionRun(this.ownerRepo, this.id); + } + + // --------------------------------------------------------------------------- + // Serialization + // --------------------------------------------------------------------------- + + toJSON(): IGiteaActionRun { + return { + id: this.id, + name: this.name, + workflow_id: this.workflowId, + status: this.status, + conclusion: this.conclusion, + head_branch: this.headBranch, + head_sha: this.headSha, + html_url: this.htmlUrl, + event: this.event, + path: this.path, + display_title: this.displayTitle, + run_number: this.runNumber, + run_attempt: this.runAttempt, + started_at: this.startedAt, + completed_at: this.completedAt, + actor: { id: 0, login: this.actorLogin, login_name: '', source_id: 0, full_name: '', email: '', avatar_url: '' }, + trigger_actor: { id: 0, login: this.triggerActorLogin, login_name: '', source_id: 0, full_name: '', email: '', avatar_url: '' }, + repository: { id: 0, name: '', full_name: this.ownerRepo, html_url: '' }, + }; + } +} diff --git a/ts/gitea.classes.actionrunjob.ts b/ts/gitea.classes.actionrunjob.ts new file mode 100644 index 0000000..92e2296 --- /dev/null +++ b/ts/gitea.classes.actionrunjob.ts @@ -0,0 +1,118 @@ +import type { GiteaClient } from './gitea.classes.giteaclient.js'; +import type { IGiteaActionRunJob, IGiteaActionRunJobStep } from './gitea.interfaces.js'; +import { computeDuration, resolveGiteaStatus } from './gitea.helpers.js'; + +export class GiteaActionRunJobStep { + public readonly name: string; + public readonly number: number; + public readonly status: string; + public readonly conclusion: string; + public readonly resolvedStatus: string; + public readonly startedAt: string; + public readonly completedAt: string; + public readonly duration: number; + + constructor(raw: IGiteaActionRunJobStep) { + this.name = raw.name || ''; + this.number = raw.number || 0; + this.status = raw.status || ''; + this.conclusion = raw.conclusion || ''; + this.resolvedStatus = resolveGiteaStatus(this.status, this.conclusion); + this.startedAt = raw.started_at || ''; + this.completedAt = raw.completed_at || ''; + this.duration = computeDuration(this.startedAt, this.completedAt); + } + + toJSON(): IGiteaActionRunJobStep { + return { + name: this.name, + number: this.number, + status: this.status, + conclusion: this.conclusion, + started_at: this.startedAt, + completed_at: this.completedAt, + }; + } +} + +export class GiteaActionRunJob { + // Raw data + public readonly id: number; + public readonly runId: number; + public readonly name: string; + public readonly workflowName: string; + public readonly headBranch: string; + public readonly headSha: string; + public readonly status: string; + public readonly conclusion: string; + public readonly htmlUrl: string; + public readonly startedAt: string; + public readonly completedAt: string; + public readonly labels: string[]; + public readonly runnerId: number; + public readonly runnerName: string; + public readonly steps: GiteaActionRunJobStep[]; + + // Computed + public readonly resolvedStatus: string; + public readonly duration: number; + + /** @internal */ + constructor( + private client: GiteaClient, + private ownerRepo: string, + raw: IGiteaActionRunJob, + ) { + this.id = raw.id; + this.runId = raw.run_id || 0; + this.name = raw.name || ''; + this.workflowName = raw.workflow_name || ''; + this.headBranch = raw.head_branch || ''; + this.headSha = raw.head_sha || ''; + this.status = raw.status || ''; + this.conclusion = raw.conclusion || ''; + this.htmlUrl = raw.html_url || ''; + this.startedAt = raw.started_at || ''; + this.completedAt = raw.completed_at || ''; + this.labels = raw.labels || []; + this.runnerId = raw.runner_id || 0; + this.runnerName = raw.runner_name || ''; + this.steps = (raw.steps || []).map(s => new GiteaActionRunJobStep(s)); + + // Computed + this.resolvedStatus = resolveGiteaStatus(this.status, this.conclusion); + this.duration = computeDuration(this.startedAt, this.completedAt); + } + + // --------------------------------------------------------------------------- + // Log + // --------------------------------------------------------------------------- + + async getLog(): Promise { + return this.client.requestGetJobLog(this.ownerRepo, this.id); + } + + // --------------------------------------------------------------------------- + // Serialization + // --------------------------------------------------------------------------- + + toJSON(): IGiteaActionRunJob { + return { + id: this.id, + run_id: this.runId, + name: this.name, + workflow_name: this.workflowName, + head_branch: this.headBranch, + head_sha: this.headSha, + status: this.status, + conclusion: this.conclusion, + html_url: this.htmlUrl, + started_at: this.startedAt, + completed_at: this.completedAt, + steps: this.steps.map(s => s.toJSON()), + labels: this.labels, + runner_id: this.runnerId, + runner_name: this.runnerName, + }; + } +} diff --git a/ts/gitea.classes.branch.ts b/ts/gitea.classes.branch.ts new file mode 100644 index 0000000..40ba80b --- /dev/null +++ b/ts/gitea.classes.branch.ts @@ -0,0 +1,18 @@ +import type { IGiteaBranch } from './gitea.interfaces.js'; + +export class GiteaBranch { + public readonly name: string; + public readonly commitSha: string; + + constructor(raw: IGiteaBranch) { + this.name = raw.name || ''; + this.commitSha = raw.commit?.id || ''; + } + + toJSON(): IGiteaBranch { + return { + name: this.name, + commit: { id: this.commitSha }, + }; + } +} diff --git a/ts/gitea.classes.giteaclient.ts b/ts/gitea.classes.giteaclient.ts index 0af499f..d90381f 100644 --- a/ts/gitea.classes.giteaclient.ts +++ b/ts/gitea.classes.giteaclient.ts @@ -1,5 +1,4 @@ import * as plugins from './gitea.plugins.js'; -import { logger } from './gitea.logging.js'; import type { IGiteaUser, IGiteaRepository, @@ -13,23 +12,26 @@ import type { IListOptions, IActionRunListOptions, } from './gitea.interfaces.js'; +import { GiteaOrganization } from './gitea.classes.organization.js'; +import { GiteaRepository } from './gitea.classes.repository.js'; +import { autoPaginate, toGiteaApiStatus } from './gitea.helpers.js'; export class GiteaClient { private baseUrl: string; private token: string; constructor(baseUrl: string, token: string) { - // Remove trailing slash if present this.baseUrl = baseUrl.replace(/\/+$/, ''); this.token = token; } - // --------------------------------------------------------------------------- - // HTTP helpers - // --------------------------------------------------------------------------- + // =========================================================================== + // HTTP helpers (internal) + // =========================================================================== - private async request( - method: 'GET' | 'POST' | 'PUT' | 'DELETE', + /** @internal */ + async request( + method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', path: string, data?: any, customHeaders?: Record, @@ -62,6 +64,9 @@ export class GiteaClient { case 'PUT': response = await builder.put(); break; + case 'PATCH': + response = await builder.patch(); + break; case 'DELETE': response = await builder.delete(); break; @@ -79,7 +84,8 @@ export class GiteaClient { } } - private async requestText( + /** @internal */ + async requestText( method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, ): Promise { @@ -114,9 +120,22 @@ export class GiteaClient { return response.text(); } - // --------------------------------------------------------------------------- - // Connection - // --------------------------------------------------------------------------- + /** @internal — fetch binary data (e.g. avatar images) */ + async requestBinary(path: string): Promise { + const url = `${this.baseUrl}${path}`; + const response = await fetch(url, { + headers: { 'Authorization': `token ${this.token}` }, + }); + if (!response.ok) { + throw new Error(`GET ${path}: ${response.status} ${response.statusText}`); + } + const buf = await response.arrayBuffer(); + return new Uint8Array(buf); + } + + // =========================================================================== + // Public API — Connection + // =========================================================================== public async testConnection(): Promise { try { @@ -127,11 +146,81 @@ export class GiteaClient { } } - // --------------------------------------------------------------------------- - // Repositories - // --------------------------------------------------------------------------- + // =========================================================================== + // Public API — Organizations (returns rich objects) + // =========================================================================== - public async getRepos(opts?: IListOptions): Promise { + /** + * Get all organizations (auto-paginated). + */ + public async getOrgs(opts?: IListOptions): Promise { + return autoPaginate( + (page, perPage) => this.requestGetOrgs({ ...opts, page, perPage }), + opts, + ).then(orgs => orgs.map(o => new GiteaOrganization(this, o))); + } + + /** + * Get a single organization by name. + */ + public async getOrg(orgName: string): Promise { + const raw = await this.requestGetOrg(orgName); + return new GiteaOrganization(this, raw); + } + + /** + * Create a new organization. + */ + public async createOrg(name: string, opts?: { + fullName?: string; + description?: string; + visibility?: string; + }): Promise { + const raw = await this.requestCreateOrg(name, opts); + return new GiteaOrganization(this, raw); + } + + // =========================================================================== + // Public API — Repositories (returns rich objects) + // =========================================================================== + + /** + * Search/list all repositories (auto-paginated). + */ + public async getRepos(opts?: IListOptions): Promise { + return autoPaginate( + (page, perPage) => this.requestGetRepos({ ...opts, page, perPage }), + opts, + ).then(repos => repos.map(r => new GiteaRepository(this, r))); + } + + /** + * Get a single repository by owner/repo. + */ + public async getRepo(ownerRepo: string): Promise { + const raw = await this.requestGetRepo(ownerRepo); + return new GiteaRepository(this, raw); + } + + /** + * Create a repository within an organization. + */ + public async createOrgRepo(orgName: string, name: string, opts?: { + description?: string; + private?: boolean; + }): Promise { + const raw = await this.requestCreateOrgRepo(orgName, name, opts); + return new GiteaRepository(this, raw); + } + + // =========================================================================== + // Internal request methods — called by domain classes + // =========================================================================== + + // --- Repos --- + + /** @internal */ + async requestGetRepos(opts?: IListOptions): Promise { const page = opts?.page || 1; const limit = opts?.perPage || 50; let url = `/api/v1/repos/search?page=${page}&limit=${limit}&sort=updated`; @@ -142,40 +231,104 @@ export class GiteaClient { return body.data || body; } - // --------------------------------------------------------------------------- - // Organizations - // --------------------------------------------------------------------------- + /** @internal */ + async requestGetRepo(ownerRepo: string): Promise { + return this.request('GET', `/api/v1/repos/${ownerRepo}`); + } - public async getOrgs(opts?: IListOptions): Promise { + /** @internal */ + async requestCreateOrgRepo(orgName: string, name: string, opts?: { + description?: string; + private?: boolean; + }): Promise { + return this.request('POST', `/api/v1/orgs/${encodeURIComponent(orgName)}/repos`, { + name, + description: opts?.description || '', + private: opts?.private ?? true, + }); + } + + /** @internal */ + async requestPatchRepo(ownerRepo: string, data: Record): Promise { + await this.request('PATCH', `/api/v1/repos/${ownerRepo}`, data); + } + + /** @internal */ + async requestSetRepoTopics(ownerRepo: string, topics: string[]): Promise { + await this.request('PUT', `/api/v1/repos/${ownerRepo}/topics`, { topics }); + } + + /** @internal */ + async requestPostRepoAvatar(ownerRepo: string, imageBase64: string): Promise { + await this.request('POST', `/api/v1/repos/${ownerRepo}/avatar`, { image: imageBase64 }); + } + + /** @internal */ + async requestDeleteRepoAvatar(ownerRepo: string): Promise { + await this.request('DELETE', `/api/v1/repos/${ownerRepo}/avatar`); + } + + /** @internal */ + async requestTransferRepo(ownerRepo: string, newOwner: string, teamIds?: number[]): Promise { + const body: any = { new_owner: newOwner }; + if (teamIds?.length) body.team_ids = teamIds; + await this.request('POST', `/api/v1/repos/${ownerRepo}/transfer`, body); + } + + /** @internal */ + async requestDeleteRepo(owner: string, repo: string): Promise { + await this.request('DELETE', `/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`); + } + + // --- Repo Branches & Tags --- + + /** @internal */ + async requestGetRepoBranches(ownerRepo: string, opts?: IListOptions): Promise { + const page = opts?.page || 1; + const limit = opts?.perPage || 50; + return this.request('GET', `/api/v1/repos/${ownerRepo}/branches?page=${page}&limit=${limit}`); + } + + /** @internal */ + async requestGetRepoTags(ownerRepo: string, opts?: IListOptions): Promise { + const page = opts?.page || 1; + const limit = opts?.perPage || 50; + return this.request('GET', `/api/v1/repos/${ownerRepo}/tags?page=${page}&limit=${limit}`); + } + + // --- Repo Secrets --- + + /** @internal */ + async requestGetRepoSecrets(ownerRepo: string): Promise { + return this.request('GET', `/api/v1/repos/${ownerRepo}/actions/secrets`); + } + + /** @internal */ + async requestSetRepoSecret(ownerRepo: string, key: string, value: string): Promise { + await this.request('PUT', `/api/v1/repos/${ownerRepo}/actions/secrets/${key}`, { data: value }); + } + + /** @internal */ + async requestDeleteRepoSecret(ownerRepo: string, key: string): Promise { + await this.request('DELETE', `/api/v1/repos/${ownerRepo}/actions/secrets/${key}`); + } + + // --- Organizations --- + + /** @internal */ + async requestGetOrgs(opts?: IListOptions): Promise { const page = opts?.page || 1; const limit = opts?.perPage || 50; return this.request('GET', `/api/v1/orgs?page=${page}&limit=${limit}`); } - /** - * Get a single organization by name - */ - public async getOrg(orgName: string): Promise { + /** @internal */ + async requestGetOrg(orgName: string): Promise { return this.request('GET', `/api/v1/orgs/${encodeURIComponent(orgName)}`); } - /** - * List repositories within an organization - */ - public async getOrgRepos(orgName: string, opts?: IListOptions): Promise { - const page = opts?.page || 1; - const limit = opts?.perPage || 50; - let url = `/api/v1/orgs/${encodeURIComponent(orgName)}/repos?page=${page}&limit=${limit}&sort=updated`; - if (opts?.search) { - url += `&q=${encodeURIComponent(opts.search)}`; - } - return this.request('GET', url); - } - - /** - * Create a new organization - */ - public async createOrg(name: string, opts?: { + /** @internal */ + async requestCreateOrg(name: string, opts?: { fullName?: string; description?: string; visibility?: string; @@ -188,87 +341,66 @@ export class GiteaClient { }); } - /** - * Create a repository within an organization - */ - public async createOrgRepo(orgName: string, name: string, opts?: { - description?: string; - private?: boolean; - }): Promise { - return this.request('POST', `/api/v1/orgs/${encodeURIComponent(orgName)}/repos`, { - name, - description: opts?.description || '', - private: opts?.private ?? true, - }); + /** @internal */ + async requestPatchOrg(orgName: string, data: Record): Promise { + await this.request('PATCH', `/api/v1/orgs/${encodeURIComponent(orgName)}`, data); } - // --------------------------------------------------------------------------- - // Repository Branches & Tags - // --------------------------------------------------------------------------- + /** @internal */ + async requestPostOrgAvatar(orgName: string, imageBase64: string): Promise { + await this.request('POST', `/api/v1/orgs/${encodeURIComponent(orgName)}/avatar`, { image: imageBase64 }); + } - public async getRepoBranches(ownerRepo: string, opts?: IListOptions): Promise { + /** @internal */ + async requestDeleteOrgAvatar(orgName: string): Promise { + await this.request('DELETE', `/api/v1/orgs/${encodeURIComponent(orgName)}/avatar`); + } + + /** @internal */ + async requestDeleteOrg(orgName: string): Promise { + await this.request('DELETE', `/api/v1/orgs/${encodeURIComponent(orgName)}`); + } + + // --- Org repos --- + + /** @internal */ + async requestGetOrgRepos(orgName: string, opts?: IListOptions): Promise { const page = opts?.page || 1; const limit = opts?.perPage || 50; - return this.request( - 'GET', - `/api/v1/repos/${ownerRepo}/branches?page=${page}&limit=${limit}`, - ); + let url = `/api/v1/orgs/${encodeURIComponent(orgName)}/repos?page=${page}&limit=${limit}&sort=updated`; + if (opts?.search) { + url += `&q=${encodeURIComponent(opts.search)}`; + } + return this.request('GET', url); } - public async getRepoTags(ownerRepo: string, opts?: IListOptions): Promise { - const page = opts?.page || 1; - const limit = opts?.perPage || 50; - return this.request( - 'GET', - `/api/v1/repos/${ownerRepo}/tags?page=${page}&limit=${limit}`, - ); - } + // --- Org Secrets --- - // --------------------------------------------------------------------------- - // Repository Secrets - // --------------------------------------------------------------------------- - - public async getRepoSecrets(ownerRepo: string): Promise { - return this.request('GET', `/api/v1/repos/${ownerRepo}/actions/secrets`); - } - - public async setRepoSecret(ownerRepo: string, key: string, value: string): Promise { - await this.request('PUT', `/api/v1/repos/${ownerRepo}/actions/secrets/${key}`, { data: value }); - } - - public async deleteRepoSecret(ownerRepo: string, key: string): Promise { - await this.request('DELETE', `/api/v1/repos/${ownerRepo}/actions/secrets/${key}`); - } - - // --------------------------------------------------------------------------- - // Organization Secrets - // --------------------------------------------------------------------------- - - public async getOrgSecrets(orgName: string): Promise { + /** @internal */ + async requestGetOrgSecrets(orgName: string): Promise { return this.request('GET', `/api/v1/orgs/${orgName}/actions/secrets`); } - public async setOrgSecret(orgName: string, key: string, value: string): Promise { + /** @internal */ + async requestSetOrgSecret(orgName: string, key: string, value: string): Promise { await this.request('PUT', `/api/v1/orgs/${orgName}/actions/secrets/${key}`, { data: value }); } - public async deleteOrgSecret(orgName: string, key: string): Promise { + /** @internal */ + async requestDeleteOrgSecret(orgName: string, key: string): Promise { await this.request('DELETE', `/api/v1/orgs/${orgName}/actions/secrets/${key}`); } - // --------------------------------------------------------------------------- - // Action Runs - // --------------------------------------------------------------------------- + // --- Action Runs --- - /** - * List action runs for a repository with optional filters. - * Supports status, branch, event, actor filtering. - */ - public async getActionRuns(ownerRepo: string, opts?: IActionRunListOptions): Promise { + /** @internal */ + async requestGetActionRuns(ownerRepo: string, opts?: IActionRunListOptions): Promise { const page = opts?.page || 1; const limit = opts?.perPage || 30; let url = `/api/v1/repos/${ownerRepo}/actions/runs?page=${page}&limit=${limit}`; - if (opts?.status) url += `&status=${encodeURIComponent(opts.status)}`; + // Translate user-friendly status names to Gitea API values + const apiStatus = toGiteaApiStatus(opts?.status); + if (apiStatus) url += `&status=${encodeURIComponent(apiStatus)}`; if (opts?.branch) url += `&branch=${encodeURIComponent(opts.branch)}`; if (opts?.event) url += `&event=${encodeURIComponent(opts.event)}`; if (opts?.actor) url += `&actor=${encodeURIComponent(opts.actor)}`; @@ -276,49 +408,24 @@ export class GiteaClient { return body.workflow_runs || body; } - /** - * Get a single action run's full details. - */ - public async getActionRun(ownerRepo: string, runId: number): Promise { - return this.request( - 'GET', - `/api/v1/repos/${ownerRepo}/actions/runs/${runId}`, - ); + /** @internal */ + async requestGetActionRun(ownerRepo: string, runId: number): Promise { + return this.request('GET', `/api/v1/repos/${ownerRepo}/actions/runs/${runId}`); } - /** - * List jobs for an action run. - */ - public async getActionRunJobs(ownerRepo: string, runId: number): Promise { + /** @internal */ + async requestGetActionRunJobs(ownerRepo: string, runId: number): Promise { const body = await this.request('GET', `/api/v1/repos/${ownerRepo}/actions/runs/${runId}/jobs`); return body.jobs || body; } - /** - * Get a job's raw log output. - */ - public async getJobLog(ownerRepo: string, jobId: number): Promise { + /** @internal */ + async requestGetJobLog(ownerRepo: string, jobId: number): Promise { return this.requestText('GET', `/api/v1/repos/${ownerRepo}/actions/jobs/${jobId}/logs`); } - /** - * Re-run an action run. - */ - public async rerunAction(ownerRepo: string, runId: number): Promise { - await this.request('POST', `/api/v1/repos/${ownerRepo}/actions/runs/${runId}/rerun`); - } - - /** - * Cancel a running action run. - */ - public async cancelAction(ownerRepo: string, runId: number): Promise { - await this.request('POST', `/api/v1/repos/${ownerRepo}/actions/runs/${runId}/cancel`); - } - - /** - * Dispatch a workflow (trigger manually). - */ - public async dispatchWorkflow( + /** @internal */ + async requestDispatchWorkflow( ownerRepo: string, workflowId: string, ref: string, @@ -331,14 +438,8 @@ export class GiteaClient { ); } - // --------------------------------------------------------------------------- - // Repository Deletion - // --------------------------------------------------------------------------- - - public async deleteRepo(owner: string, repo: string): Promise { - await this.request( - 'DELETE', - `/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`, - ); + /** @internal */ + async requestDeleteActionRun(ownerRepo: string, runId: number): Promise { + await this.request('DELETE', `/api/v1/repos/${ownerRepo}/actions/runs/${runId}`); } } diff --git a/ts/gitea.classes.organization.ts b/ts/gitea.classes.organization.ts new file mode 100644 index 0000000..1843e60 --- /dev/null +++ b/ts/gitea.classes.organization.ts @@ -0,0 +1,115 @@ +import type { GiteaClient } from './gitea.classes.giteaclient.js'; +import type { IGiteaOrganization, IGiteaSecret, IListOptions } from './gitea.interfaces.js'; +import { GiteaRepository } from './gitea.classes.repository.js'; +import { GiteaSecret } from './gitea.classes.secret.js'; +import { autoPaginate } from './gitea.helpers.js'; + +export class GiteaOrganization { + // Raw data + public readonly id: number; + public readonly name: string; + public readonly fullName: string; + public readonly description: string; + public readonly visibility: string; + public readonly repoCount: number; + public readonly avatarUrl: string; + + /** @internal */ + constructor( + private client: GiteaClient, + raw: IGiteaOrganization, + ) { + this.id = raw.id; + this.name = raw.name || ''; + this.fullName = raw.full_name || this.name; + this.description = raw.description || ''; + this.visibility = raw.visibility || 'public'; + this.repoCount = raw.repo_count || 0; + this.avatarUrl = raw.avatar_url || ''; + } + + // --------------------------------------------------------------------------- + // Repos + // --------------------------------------------------------------------------- + + async getRepos(opts?: IListOptions): Promise { + return autoPaginate( + (page, perPage) => this.client.requestGetOrgRepos(this.name, { ...opts, page, perPage }), + opts, + ).then(repos => repos.map(r => new GiteaRepository(this.client, r))); + } + + // --------------------------------------------------------------------------- + // Secrets + // --------------------------------------------------------------------------- + + async getSecrets(): Promise { + const secrets = await this.client.requestGetOrgSecrets(this.name); + return secrets.map(s => new GiteaSecret(s)); + } + + async setSecret(key: string, value: string): Promise { + await this.client.requestSetOrgSecret(this.name, key, value); + } + + async deleteSecret(key: string): Promise { + await this.client.requestDeleteOrgSecret(this.name, key); + } + + // --------------------------------------------------------------------------- + // Mutation + // --------------------------------------------------------------------------- + + /** + * Update organization properties (description, visibility, etc.) + */ + async update(data: { + description?: string; + visibility?: string; + fullName?: string; + }): Promise { + await this.client.requestPatchOrg(this.name, { + description: data.description, + visibility: data.visibility, + full_name: data.fullName, + }); + } + + /** + * Upload an avatar image for this organization. + * @param imageBase64 - Base64-encoded image data + */ + async setAvatar(imageBase64: string): Promise { + await this.client.requestPostOrgAvatar(this.name, imageBase64); + } + + /** + * Remove the organization's avatar. + */ + async deleteAvatar(): Promise { + await this.client.requestDeleteOrgAvatar(this.name); + } + + /** + * Delete this organization. + */ + async delete(): Promise { + await this.client.requestDeleteOrg(this.name); + } + + // --------------------------------------------------------------------------- + // Serialization + // --------------------------------------------------------------------------- + + toJSON(): IGiteaOrganization { + return { + id: this.id, + name: this.name, + full_name: this.fullName, + description: this.description, + visibility: this.visibility, + repo_count: this.repoCount, + avatar_url: this.avatarUrl, + }; + } +} diff --git a/ts/gitea.classes.repository.ts b/ts/gitea.classes.repository.ts new file mode 100644 index 0000000..647ecb3 --- /dev/null +++ b/ts/gitea.classes.repository.ts @@ -0,0 +1,171 @@ +import type { GiteaClient } from './gitea.classes.giteaclient.js'; +import type { IGiteaRepository, IGiteaSecret, IListOptions, IActionRunListOptions } from './gitea.interfaces.js'; +import { GiteaBranch } from './gitea.classes.branch.js'; +import { GiteaTag } from './gitea.classes.tag.js'; +import { GiteaSecret } from './gitea.classes.secret.js'; +import { GiteaActionRun } from './gitea.classes.actionrun.js'; +import { autoPaginate } from './gitea.helpers.js'; + +export class GiteaRepository { + // Raw data + public readonly id: number; + public readonly name: string; + public readonly fullName: string; + public readonly description: string; + public readonly defaultBranch: string; + public readonly htmlUrl: string; + public readonly isPrivate: boolean; + public readonly topics: string[]; + public readonly updatedAt: string; + public readonly ownerId: number; + public readonly ownerLogin: string; + public readonly ownerAvatarUrl: string; + + /** @internal */ + constructor( + private client: GiteaClient, + raw: IGiteaRepository, + ) { + this.id = raw.id; + this.name = raw.name || ''; + this.fullName = raw.full_name || ''; + this.description = raw.description || ''; + this.defaultBranch = raw.default_branch || 'main'; + this.htmlUrl = raw.html_url || ''; + this.isPrivate = raw.private ?? true; + this.topics = raw.topics || []; + this.updatedAt = raw.updated_at || ''; + this.ownerId = raw.owner?.id || 0; + this.ownerLogin = raw.owner?.login || ''; + this.ownerAvatarUrl = raw.owner?.avatar_url || ''; + } + + // --------------------------------------------------------------------------- + // Branches & Tags + // --------------------------------------------------------------------------- + + async getBranches(opts?: IListOptions): Promise { + return autoPaginate( + (page, perPage) => this.client.requestGetRepoBranches(this.fullName, { ...opts, page, perPage }), + opts, + ).then(branches => branches.map(b => new GiteaBranch(b))); + } + + async getTags(opts?: IListOptions): Promise { + return autoPaginate( + (page, perPage) => this.client.requestGetRepoTags(this.fullName, { ...opts, page, perPage }), + opts, + ).then(tags => tags.map(t => new GiteaTag(t))); + } + + // --------------------------------------------------------------------------- + // Secrets + // --------------------------------------------------------------------------- + + async getSecrets(): Promise { + const secrets = await this.client.requestGetRepoSecrets(this.fullName); + return secrets.map(s => new GiteaSecret(s)); + } + + async setSecret(key: string, value: string): Promise { + await this.client.requestSetRepoSecret(this.fullName, key, value); + } + + async deleteSecret(key: string): Promise { + await this.client.requestDeleteRepoSecret(this.fullName, key); + } + + // --------------------------------------------------------------------------- + // Action Runs + // --------------------------------------------------------------------------- + + async getActionRuns(opts?: IActionRunListOptions): Promise { + return autoPaginate( + (page, perPage) => this.client.requestGetActionRuns(this.fullName, { ...opts, page, perPage }), + opts, + ).then(runs => runs.map(r => new GiteaActionRun(this.client, this.fullName, r))); + } + + // --------------------------------------------------------------------------- + // Mutation + // --------------------------------------------------------------------------- + + /** + * Update repository properties. + */ + async update(data: { + name?: string; + description?: string; + defaultBranch?: string; + private?: boolean; + archived?: boolean; + }): Promise { + await this.client.requestPatchRepo(this.fullName, { + name: data.name, + description: data.description, + default_branch: data.defaultBranch, + private: data.private, + archived: data.archived, + }); + } + + /** + * Set topics for this repository (replaces all existing topics). + */ + async setTopics(topics: string[]): Promise { + await this.client.requestSetRepoTopics(this.fullName, topics); + } + + /** + * Upload an avatar image for this repository. + * @param imageBase64 - Base64-encoded image data + */ + async setAvatar(imageBase64: string): Promise { + await this.client.requestPostRepoAvatar(this.fullName, imageBase64); + } + + /** + * Remove the repository's avatar. + */ + async deleteAvatar(): Promise { + await this.client.requestDeleteRepoAvatar(this.fullName); + } + + /** + * Transfer this repository to a different owner (org or user). + */ + async transfer(newOwner: string, teamIds?: number[]): Promise { + await this.client.requestTransferRepo(this.fullName, newOwner, teamIds); + } + + /** + * Delete this repository. + */ + async delete(): Promise { + const [owner, repo] = this.fullName.split('/'); + await this.client.requestDeleteRepo(owner, repo); + } + + // --------------------------------------------------------------------------- + // Serialization + // --------------------------------------------------------------------------- + + toJSON(): IGiteaRepository { + return { + id: this.id, + name: this.name, + full_name: this.fullName, + description: this.description, + default_branch: this.defaultBranch, + html_url: this.htmlUrl, + private: this.isPrivate, + topics: this.topics, + updated_at: this.updatedAt, + owner: { + id: this.ownerId, + login: this.ownerLogin, + avatar_url: this.ownerAvatarUrl, + }, + }; + } +} diff --git a/ts/gitea.classes.secret.ts b/ts/gitea.classes.secret.ts new file mode 100644 index 0000000..cfb0c6b --- /dev/null +++ b/ts/gitea.classes.secret.ts @@ -0,0 +1,18 @@ +import type { IGiteaSecret } from './gitea.interfaces.js'; + +export class GiteaSecret { + public readonly name: string; + public readonly createdAt: string; + + constructor(raw: IGiteaSecret) { + this.name = raw.name || ''; + this.createdAt = raw.created_at || ''; + } + + toJSON(): IGiteaSecret { + return { + name: this.name, + created_at: this.createdAt, + }; + } +} diff --git a/ts/gitea.classes.tag.ts b/ts/gitea.classes.tag.ts new file mode 100644 index 0000000..1d37475 --- /dev/null +++ b/ts/gitea.classes.tag.ts @@ -0,0 +1,19 @@ +import type { IGiteaTag } from './gitea.interfaces.js'; + +export class GiteaTag { + public readonly name: string; + public readonly commitSha: string; + + constructor(raw: IGiteaTag) { + this.name = raw.name || ''; + this.commitSha = raw.commit?.sha || ''; + } + + toJSON(): IGiteaTag { + return { + name: this.name, + id: this.name, + commit: { sha: this.commitSha }, + }; + } +} diff --git a/ts/gitea.helpers.ts b/ts/gitea.helpers.ts new file mode 100644 index 0000000..ab30fa9 --- /dev/null +++ b/ts/gitea.helpers.ts @@ -0,0 +1,87 @@ +/** + * Auto-paginate a list endpoint. + * If opts includes a specific page, returns just that page (no auto-pagination). + */ +export async function autoPaginate( + fetchPage: (page: number, perPage: number) => Promise, + opts?: { page?: number; perPage?: number }, +): Promise { + const perPage = opts?.perPage || 50; + + // If caller requests a specific page, return just that page + if (opts?.page) { + return fetchPage(opts.page, perPage); + } + + // Otherwise auto-paginate through all pages + const all: T[] = []; + let page = 1; + while (true) { + const items = await fetchPage(page, perPage); + all.push(...items); + if (items.length < perPage) break; + page++; + } + return all; +} + +/** + * Compute duration in seconds from two ISO timestamps. + */ +export function computeDuration(startedAt?: string, completedAt?: string): number { + if (!startedAt || !completedAt) return 0; + const ms = new Date(completedAt).getTime() - new Date(startedAt).getTime(); + return ms > 0 ? Math.round(ms / 1000) : 0; +} + +/** + * Gitea uses `status` for run state (running, waiting, completed) + * and `conclusion` for the actual result (success, failure, cancelled, skipped). + * When status is "completed", the conclusion carries the meaningful status. + */ +export function resolveGiteaStatus(status: string, conclusion: string): string { + if (status === 'completed' && conclusion) { + return conclusion; + } + return status || conclusion || ''; +} + +/** + * Extract a human-readable ref from the Gitea `path` field. + * path format: "workflow.yaml@refs/tags/v1.0.0" or "workflow.yaml@refs/heads/main" + */ +export function extractRefFromPath(path?: string): string { + if (!path) return ''; + const atIdx = path.indexOf('@'); + if (atIdx < 0) return ''; + const ref = path.substring(atIdx + 1); + return ref.replace(/^refs\/tags\//, '').replace(/^refs\/heads\//, ''); +} + +/** + * Extract the workflow filename from the Gitea `path` field. + * path format: "workflow.yaml@refs/tags/v1.0.0" → "workflow.yaml" + */ +export function extractWorkflowIdFromPath(path?: string): string { + if (!path) return ''; + const atIdx = path.indexOf('@'); + return atIdx >= 0 ? path.substring(0, atIdx) : path; +} + +/** + * Translate normalized status names to Gitea API-native query parameter values. + * Gitea accepts: pending, queued, in_progress, failure, success, skipped + */ +export function toGiteaApiStatus(status?: string): string | undefined { + if (!status) return undefined; + const map: Record = { + running: 'in_progress', + failed: 'failure', + canceled: 'cancelled', + pending: 'pending', + success: 'success', + skipped: 'skipped', + waiting: 'queued', + }; + return map[status] || status; +} diff --git a/ts/gitea.interfaces.ts b/ts/gitea.interfaces.ts index be021b6..a0e8b4d 100644 --- a/ts/gitea.interfaces.ts +++ b/ts/gitea.interfaces.ts @@ -18,7 +18,7 @@ export interface IListOptions { // --------------------------------------------------------------------------- export interface IActionRunListOptions extends IListOptions { - /** Filter by run status (waiting, running, success, failure, cancelled) */ + /** Filter by run status. Accepts normalized names (running, failed, etc.) — auto-translated to Gitea API values. */ status?: string; /** Filter by head branch */ branch?: string; @@ -35,13 +35,15 @@ export interface IActionRunListOptions extends IListOptions { export interface IGiteaUser { id: number; login: string; + login_name: string; + source_id: number; full_name: string; email: string; avatar_url: string; } // --------------------------------------------------------------------------- -// Repositories +// Repositories (raw API response) // --------------------------------------------------------------------------- export interface IGiteaRepository { @@ -62,7 +64,7 @@ export interface IGiteaRepository { } // --------------------------------------------------------------------------- -// Organizations +// Organizations (raw API response) // --------------------------------------------------------------------------- export interface IGiteaOrganization { @@ -72,6 +74,7 @@ export interface IGiteaOrganization { description: string; visibility: string; repo_count: number; + avatar_url: string; } // --------------------------------------------------------------------------- @@ -84,25 +87,25 @@ export interface IGiteaSecret { } // --------------------------------------------------------------------------- -// Action Runs +// Action Runs (raw API response — aligned with Gitea 1.25 swagger) // --------------------------------------------------------------------------- export interface IGiteaActionRun { id: number; name: string; workflow_id: string; - status: string; - conclusion: string; + status: string; // run state: running, waiting, completed + conclusion: string; // result: success, failure, cancelled, skipped head_branch: string; head_sha: string; html_url: string; event: string; + path: string; // e.g. "workflow.yaml@refs/tags/v1.0" + display_title: string; run_number: number; run_attempt: number; - run_duration: number; - created_at: string; - updated_at: string; started_at: string; + completed_at: string; actor: IGiteaUser; trigger_actor: IGiteaUser; repository: { @@ -111,15 +114,10 @@ export interface IGiteaActionRun { full_name: string; html_url: string; }; - head_commit: { - id: string; - message: string; - timestamp: string; - }; } // --------------------------------------------------------------------------- -// Action Run Jobs +// Action Run Jobs (raw API response) // --------------------------------------------------------------------------- export interface IGiteaActionRunJob { @@ -132,7 +130,6 @@ export interface IGiteaActionRunJob { status: string; conclusion: string; html_url: string; - run_duration: number; started_at: string; completed_at: string; steps: IGiteaActionRunJobStep[]; diff --git a/ts/index.ts b/ts/index.ts index 21881e1..9a86e86 100644 --- a/ts/index.ts +++ b/ts/index.ts @@ -1,4 +1,26 @@ +// Main client export { GiteaClient } from './gitea.classes.giteaclient.js'; + +// Domain classes +export { GiteaOrganization } from './gitea.classes.organization.js'; +export { GiteaRepository } from './gitea.classes.repository.js'; +export { GiteaActionRun } from './gitea.classes.actionrun.js'; +export { GiteaActionRunJob, GiteaActionRunJobStep } from './gitea.classes.actionrunjob.js'; +export { GiteaBranch } from './gitea.classes.branch.js'; +export { GiteaTag } from './gitea.classes.tag.js'; +export { GiteaSecret } from './gitea.classes.secret.js'; + +// Helpers +export { + autoPaginate, + computeDuration, + resolveGiteaStatus, + extractRefFromPath, + extractWorkflowIdFromPath, + toGiteaApiStatus, +} from './gitea.helpers.js'; + +// Interfaces (raw API types) export type { IGiteaUser, IGiteaRepository, @@ -13,4 +35,6 @@ export type { IListOptions, IActionRunListOptions, } from './gitea.interfaces.js'; + +// Commit info export { commitinfo } from './00_commitinfo_data.js';