Files
tspublish/ts/classes.giteaassets.ts

109 lines
3.2 KiB
TypeScript

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 requestBuilder = plugins.smartrequest.SmartRequest.create()
.url(this.baseUrl + `/repos/${owner}/${repo}/contents/${directory}`)
.headers(this.headers);
if (branch) {
requestBuilder.query({ ref: branch });
}
const response = await requestBuilder.get();
let responseBody = await response.json();
if (!Array.isArray(responseBody) && typeof responseBody === 'object') {
responseBody = [responseBody];
} else if (Array.isArray(responseBody)) {
for (const entry of responseBody) {
if (entry.type === 'dir') {
continue;
} else if (entry.type === 'file') {
const requestBuilder2 = plugins.smartrequest.SmartRequest.create()
.url(this.baseUrl + `/repos/${owner}/${repo}/contents/${entry.path}`)
.headers(this.headers);
if (branch) {
requestBuilder2.query({ ref: branch });
}
const response2 = await requestBuilder2.get();
const response2Body = await response2.json();
entry.encoding = response2Body.encoding;
entry.content = response2Body.content;
}
}
}
// lets map to the IRepoFile interface
responseBody = responseBody.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 responseBody;
} 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];
}
}