GitHub

buildRepos

Code

const axios = require('axios');
const path = require('path');
const { readPropertiesFile, requireHttpsUrl, resolveSecureUrl } = require('../essential');

/*
    @param org = String
    @param repos = Array
    @param vis = String
    @param token = String
*/
async function buildRepos(org, repos, vis, token) {
    const filePath = path.join(__dirname, 'properties', 'api.properties');
    const config = readPropertiesFile(filePath);

    if (!config.repourl) {
        throw new Error("Repository URL is missing in the configuration.");
    }

    requireHttpsUrl(config.repourl, 'repourl');

    const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
    };

    const retryLimit = 3;
    const createGitHubRepo = async (repo, attempt = 1) => {
        const replacements = { organization: org };
        const data = { name: repo, visibility: vis };

        try {
            const createResponse = await axios.post(resolveSecureUrl(config.repourl, replacements, 'repourl'), data, { headers });

            if (createResponse.status === 201) {
                return { success: true, message: 'GitHub repository created successfully', repositoryName: repo, organizationName: org };
            } else {
                return { success: false, message: 'Failed to create GitHub repository', status: createResponse.status };
            }
        } catch (error) {
            if (attempt < retryLimit) {
                return createGitHubRepo(repo, attempt + 1);
            }
            console.error('Error:', error.message);
            return { success: false, message: 'Internal server error', status: error.response?.status };
        }
    };

    const results = await Promise.all(repos.map(repo => createGitHubRepo(repo)));

    return results;
}

module.exports = buildRepos;

Usage

/*
    @param org = String
    @param repos = Array
    @param vis = String
    @param token = String
*/
const { buildRepos } = require('jwz/github');

const org = 'your-org-name';
const repos = ['your-repoA', 'your-repoB'];
const vis = 'public';
const token = 'your-token';

const res = await buildRepos(org, repos, vis, token);
console.log(res);

Explanation

The buildRepos function is a utility for programmatically creating GitHub repositories. It reads configurations from an external properties file and uses Axios for API requests. Here's a breakdown:

  • Parameters:
    • org: The name of the GitHub organization where the repositories will be created.
    • repos: An array of repository names to be created.
    • vis: The visibility of the repositories (e.g., 'public' or 'private').
    • token: A GitHub personal access token for authentication.
  • Logic:
    • Reads the API endpoint URL from a properties file.
    • Checks the endpoint uses https, and throws before the token is sent if it does not.
    • Constructs headers with the authentication token.
    • Retries up to 3 times for failed requests.
    • Creates repositories by calling the GitHub API.
  • Output:
    • An array of results, where each result contains the success status, message, and repository details.