Skip to content

Commit

Permalink
Merge pull request #6 from cybersokari/simple-git
Browse files Browse the repository at this point in the history
Setting up simple-git
  • Loading branch information
cybersokari authored Feb 8, 2025
2 parents 8eef308 + 9e52711 commit 6a9288b
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 73 deletions.
5 changes: 4 additions & 1 deletion action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,14 @@ inputs:
description: "Target branch for Deploying to GitHub Pages. Default: gh-pages"
default: 'gh-pages'
github_subfolder:
description: "Git sub directory to write test report when hosting with GitHub Pages"
description: "Git sub directory for test report when hosting with GitHub Pages. Default 'github.run_id'"
default: ${{ github.run_id }}
language:
description: "Allure report language"
default: 'en'
github_pages_repo:
description: "GitHub repository to deploy GitHub pages. Example owner/repository-name"
default: ${{ github.repository }}
outputs:
report_url:
description: "URL to your test report"
16 changes: 9 additions & 7 deletions dist/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export function main() {
fsSync.mkdirSync(gitWorkspace, { recursive: true });
const reportDir = path.posix.join(gitWorkspace, core.getInput('github_subfolder'));
const storageRequired = showHistory || retries > 0;
const [owner, repo] = getInputOrUndefined('github_pages_repo', true).split('/');
const args = {
reportLanguage: getInputOrUndefined('language'),
downloadRequired: storageRequired,
Expand All @@ -54,7 +55,8 @@ export function main() {
showHistory,
storageRequired,
target,
gitWorkspace
gitWorkspace,
owner, repo
};
if (target === Target.FIREBASE) {
const credentials = getInputOrUndefined("google_credentials_json");
Expand All @@ -78,7 +80,7 @@ export function main() {
args.host = getGitHubHost({
token,
reportDir,
gitWorkspace
gitWorkspace, repo, owner
});
}
await executeDeployment(args);
Expand Down Expand Up @@ -106,12 +108,12 @@ async function executeDeployment(args) {
function getFirebaseHost({ firebaseProjectId, REPORTS_DIR }) {
return new FirebaseHost(new FirebaseService(firebaseProjectId, REPORTS_DIR));
}
function getGitHubHost({ token, reportDir, gitWorkspace }) {
function getGitHubHost({ token, reportDir, gitWorkspace, owner, repo }) {
const subFolder = getInputOrUndefined('github_subfolder', true);
const branch = getInputOrUndefined('github_pages_branch', true);
const config = {
owner: github.context.repo.owner,
repo: github.context.repo.repo,
owner,
repo,
workspace: gitWorkspace,
token, subFolder, branch,
reportDir
Expand All @@ -122,8 +124,8 @@ async function initializeStorage(args) {
switch (args.target) {
case Target.GITHUB: {
const config = {
owner: github.context.repo.owner,
repo: github.context.repo.repo,
owner: args.owner,
repo: args.repo,
token: args.githubToken
};
return new GithubStorage(new ArtifactService(config), args);
Expand Down
46 changes: 23 additions & 23 deletions dist/services/github-pages.service.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import fs from "fs";
import path from "node:path";
import simpleGit from "simple-git";
import * as console from "node:console";
import simpleGit, { CheckRepoActions } from "simple-git";
import github from "@actions/github";
export class GithubPagesService {
constructor({ branch, workspace, token, repo, owner, subFolder, reportDir }) {
Expand All @@ -14,69 +13,70 @@ export class GithubPagesService {
this.token = token;
}
async deployPages() {
if (!fs.existsSync(this.reportDir)) {
const [reportDirExists, isRepo] = await Promise.all([
fs.existsSync(this.reportDir),
this.git.checkIsRepo(CheckRepoActions.IS_REPO_ROOT)
]);
if (!reportDirExists) {
throw new Error(`Directory does not exist: ${this.reportDir}`);
}
// Add files to the git index
if (!isRepo) {
throw new Error('No repository found. Call setupBranch() to initialize.');
}
const files = this.getFilePathsFromDir(this.reportDir);
if (files.length === 0) {
console.warn(`No files found in the directory: ${this.reportDir}. Deployment aborted.`);
console.warn(`No files found in directory: ${this.reportDir}. Deployment aborted.`);
return;
}
// Stage and commit files
await this.git.add(files);
await this.git.commit(`Allure report for Github run: ${github.context.runId} `);
// Push changes to the branch
await this.git.commit(`Allure report for GitHub run: ${github.context.runId}`);
await this.git.push('origin', this.branch);
console.log("Deployment to GitHub Pages complete");
console.log("Deployment to GitHub Pages completed successfully.");
}
async setupBranch() {
// Initialize repository and fetch branch info
await this.git.init();
const headers = {
Authorization: `basic ${Buffer.from(`x-access-token:${this.token}`).toString('base64')}`
Authorization: `Basic ${Buffer.from(`x-access-token:${this.token}`).toString('base64')}`
};
this.git.addConfig('http.https://github.com/.extraheader', `AUTHORIZATION: ${headers.Authorization}`, true, 'local');
const actor = github.context.actor;
const email = `${github.context.payload.sender?.id}+${actor}@users.noreply.github.com`;
this.git.addConfig('user.email', email, true, 'local')
await this.git
.addConfig('user.email', email, true, 'local')
.addConfig('user.name', actor, true, 'local');
await this.git.addRemote('origin', `https://github.com/${this.owner}/${this.repo}.git`);
await this.git.fetch('origin', this.branch); // Fetch only the target branch
// Check if the remote branch exists
await this.git.fetch('origin', this.branch);
const branchList = await this.git.branch(['-r', '--list', `origin/${this.branch}`]);
if (branchList.all.length === 0) {
console.log(`Remote branch '${this.branch}' does not exist. Creating it from the default branch.`);
// Get the default branch name
const defaultBranch = (await this.git.raw(['symbolic-ref', 'refs/remotes/origin/HEAD']))
.trim()
.split('/').pop();
// Create and switch to a new local branch that tracks the default branch
.split('/')
.pop();
await this.git.checkoutBranch(this.branch, `origin/${defaultBranch}`);
console.log(`Branch '${this.branch}' created from '${defaultBranch}'`);
console.log(`Branch '${this.branch}' created from '${defaultBranch}'.`);
}
else {
// Branch exists, switch to it
await this.git.checkoutBranch(this.branch, `origin/${this.branch}`);
console.log(`Checked out branch '${this.branch}'`);
console.log(`Checked out branch '${this.branch}'.`);
}
return `https://${this.owner}.github.io/${this.repo}/${this.subFolder}`;
}
getFilePathsFromDir(dir) {
const files = [];
const readDir = (currentDir) => {
const readDirectory = (currentDir) => {
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
readDir(fullPath);
readDirectory(fullPath);
}
else {
files.push(fullPath);
}
}
};
readDir(dir);
readDirectory(dir);
return files;
}
}
2 changes: 2 additions & 0 deletions src/interfaces/args.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ export interface GitHubArgInterface extends ArgsInterface{
target: Target;
storageRequired: boolean;
gitWorkspace: string;
repo: string;
owner: string;
}
export enum Target {FIREBASE, GITHUB}
22 changes: 13 additions & 9 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,10 @@ export function main() {
const retries: number = getRetries()
const runtimeDir = await getRuntimeDirectory();
const gitWorkspace = path.posix.join(runtimeDir, 'report')
fsSync.mkdirSync(gitWorkspace, {recursive: true });
fsSync.mkdirSync(gitWorkspace, {recursive: true});
const reportDir = path.posix.join(gitWorkspace, core.getInput('github_subfolder'));
const storageRequired: boolean = showHistory || retries > 0
const [owner, repo] = getInputOrUndefined('github_pages_repo', true)!.split('/')
const args: GitHubArgInterface = {
reportLanguage: getInputOrUndefined('language'),
downloadRequired: storageRequired,
Expand All @@ -79,7 +80,8 @@ export function main() {
showHistory,
storageRequired,
target,
gitWorkspace
gitWorkspace,
owner, repo
};

if (target === Target.FIREBASE) {
Expand All @@ -103,7 +105,7 @@ export function main() {
args.host = getGitHubHost({
token,
reportDir,
gitWorkspace
gitWorkspace, repo, owner
});
}
await executeDeployment(args);
Expand Down Expand Up @@ -139,17 +141,19 @@ function getFirebaseHost({firebaseProjectId, REPORTS_DIR}: {

function getGitHubHost({
token,
reportDir, gitWorkspace
reportDir, gitWorkspace, owner, repo
}: {
token: string;
reportDir: string;
gitWorkspace: string;
owner: string;
repo: string;
}): GithubHost {
const subFolder = getInputOrUndefined('github_subfolder', true)!;
const branch = getInputOrUndefined('github_pages_branch', true)!;
const config: GitHubConfig = {
owner: github.context.repo.owner,
repo: github.context.repo.repo,
owner,
repo,
workspace: gitWorkspace,
token, subFolder, branch,
reportDir
Expand All @@ -161,8 +165,8 @@ async function initializeStorage(args: GitHubArgInterface): Promise<IStorage | u
switch (args.target) {
case Target.GITHUB: {
const config: ArtifactServiceConfig = {
owner: github.context.repo.owner,
repo: github.context.repo.repo,
owner: args.owner,
repo: args.repo,
token: args.githubToken!
}
return new GithubStorage(new ArtifactService(config), args)
Expand Down Expand Up @@ -273,7 +277,7 @@ async function copyReportToOutput(reportDir: string): Promise<void> {
if (reportOutputPath) {
try {
await copyDirectory(reportDir, reportOutputPath);
}catch (e) {
} catch (e) {
console.error(e);
}
}
Expand Down
Loading

0 comments on commit 6a9288b

Please sign in to comment.