tspublish/ts/classes.giteaassets.ts

104 lines
3.0 KiB
TypeScript
Raw Normal View History

import * as plugins from './plugins.js';
interface IRepoFile {
name: string;
path: string;
type: 'file' | 'dir';
download_url: string | null;
base64Content: string | null;
encoding: string | null;
}
interface IGiteaAssetsOptions {
giteaBaseUrl: string; // Base URL of your Gitea instance
token?: string; // Optional token for private repositories
}
export class GiteaAssets {
private baseUrl: string;
private headers: {[key: string]: string} = {};
constructor(options: IGiteaAssetsOptions) {
this.baseUrl = options.giteaBaseUrl
if (this.baseUrl.endsWith('/')) {
this.baseUrl = this.baseUrl.slice(0, -1);
}
this.baseUrl += '/api/v1';
this.headers = options.token
? { ...this.headers, 'Authorization': `token ${options.token}` }
: this.headers;
}
/**
* Get all files in a directory of a repository
* @param owner - Repository owner
* @param repo - Repository name
* @param directory - Directory path ('' for root)
* @param branch - Branch name (optional)
* @returns A list of files in the directory
*/
async getFiles(
owner: string,
repo: string,
directory: string,
branch?: string
): Promise<IRepoFile[]> {
try {
const response = await plugins.smartrequest.request(
this.baseUrl + `/repos/${owner}/${repo}/contents/${directory}`,
{
headers: this.headers,
method: 'GET',
queryParams: branch ? { ref: branch } : {},
}
)
if (!Array.isArray(response.body) && typeof response.body === 'object') {
response.body = [response.body];
} else if (Array.isArray(response.body)) {
for (const entry of response.body) {
if (entry.type === 'dir') {
continue;
} else if (entry.type === 'file') {
const response2 = await plugins.smartrequest.request(
this.baseUrl + `/repos/${owner}/${repo}/contents/${entry.path}`,
{
headers: this.headers,
method: 'GET',
queryParams: branch ? { ref: branch } : {},
}
);
entry.encoding = response2.body.encoding;
entry.content = response2.body.content;
}
}
}
// lets map to the IRepoFile interface
response.body = response.body.map((entry: any) => {
return {
name: entry.name,
path: entry.path,
type: entry.type,
download_url: entry.download_url,
base64Content: entry.content,
encoding: entry.encoding,
};
});
return response.body;
} catch (error) {
console.error('Error fetching repository files:', error);
throw error;
}
}
/**
* gets the current cli entry file from the code.foss.global/git.zone/cli repository
* @returns
*/
public async getBinCliEntryFile() {
const files = await this.getFiles('git.zone', 'cli', 'assets/templates/cli/cli.js');
return files[0];
}
}