import * as wmill from "windmill-client";
import { basename } from "node:path"
const util = require('util');
const exec = util.promisify(require('child_process').exec);
export async function main(repo_url_resource_path: string) {
const cwd = process.cwd();
process.env["HOME"] = ".";
console.log(`Cloning repo from resource`);
const repo_name = await git_clone(repo_url_resource_path);
process.chdir(`${cwd}/${repo_name}`);
console.log(`Attempting an empty push to repository ${repo_name}`);
await git_push();
console.log("Finished");
process.chdir(`${cwd}`);
}
async function git_clone(repo_resource_path: string): Promise<string> {
// TODO: handle private SSH keys as well
let repo_url = (await wmill.getResource(repo_resource_path)).url;
const azureMatch = repo_url.match(/AZURE_DEVOPS_TOKEN\((?<url>.+)\)/);
if (azureMatch) {
console.log(
"Requires Azure DevOps service account access token, requesting..."
);
const azureResource = await wmill.getResource(azureMatch.groups.url);
const response = await fetch(
`https://login.microsoftonline.com/${azureResource.azureTenantId}/oauth2/token`,
{
method: "POST",
body: new URLSearchParams({
client_id: azureResource.azureClientId,
client_secret: azureResource.azureClientSecret,
grant_type: "client_credentials",
resource: "499b84ac-1321-427f-aa17-267ca6975798/.default",
}),
}
);
const { access_token } = await response.json();
repo_url = repo_url.replace(azureMatch[0], access_token);
}
const repo_name = basename(repo_url, ".git");
await sh_run(4, "git", "clone", "--quiet", "--depth", "1", repo_url, repo_name);
return repo_name;
}
async function git_push() {
await sh_run(undefined, "git", "config", "user.email", process.env["WM_EMAIL"])
await sh_run(undefined, "git", "config", "user.name", process.env["WM_USERNAME"])
await sh_run(undefined, "git", "push");
}
async function sh_run(
secret_position: number | undefined,
cmd: string,
...args: string[]
) {
const nargs = secret_position != undefined ? args.slice() : args;
if (secret_position && secret_position < 0) {
secret_position = nargs.length - 1 + secret_position;
}
if (secret_position != undefined) {
nargs[secret_position] = "***";
}
console.log(`Running '${cmd} ${nargs.join(" ")} ...'`);
const command = exec(`${cmd} ${args.join(" ")}`)
// new Deno.Command(cmd, {
// args: args,
// });
const { error, stdout, stderr } = await command
if (stdout.length > 0) {
console.log(stdout);
}
if (stderr.length > 0) {
console.log(stderr);
}
if (error) {
const err = `SH command '${cmd} ${nargs.join(
" "
)}' returned with error ${error}`;
throw Error(err);
}
console.log("Command successfully executed");
}
Submitted by rubenfiszel 87 days ago