UNPKG

@relbns/github-cloner

Version:

Github Cloner is a CLI tool for cloning Github repositories with interactive lists in the terminal. the tool lists your repositories and sorts them by owners (users and organizations) and by name. choosing the repo will clone it to the current directory i

95 lines (86 loc) 2.81 kB
import axios from 'axios'; const githubToken = process.env.GITHUB_TOKEN; // Ensure you set your token as an environment variable. const getMaxPage = (headers) => { try { const link = headers.link; return link.split(',').pop().split(';')[0].match(/page=(\d+)/)[1]; } catch (error) { console.error(error); } } const getQuery = (pageNum) => axios.get(`https://api.github.com/user/repos?page=${pageNum}`, { headers: { Authorization: `token ${githubToken}`, }, }); const extractRelevantAttributes = (data) => ({ id: data.id, name: data.name, fullName: data.full_name, owner: data.owner.login, ownerType: data.owner.type, isPrivate: data.private, isForked: data.fork, description: data.description, updatedAt: data.updated_at, pushedAt: data.pushed_at, sshUrl: data.ssh_url, cloneUrl: data.clone_url }) const tryGettingGitHubRepos = async () => { let reposData = []; let isCompletedSuccessfully = true; let error = null; try { const userRepos = []; let pageNum = 1; const firstPageResponse = await getQuery(pageNum); userRepos.push(...firstPageResponse.data); const maxPage = getMaxPage(firstPageResponse.headers); const promises = []; if (maxPage > 1) { for (pageNum = 2; pageNum <= maxPage; pageNum++) { promises.push(getQuery(pageNum)); } const responses = await Promise.all(promises); responses.forEach(response => userRepos.push(...response.data)); } reposData = userRepos.map(extractRelevantAttributes); } catch (error) { isCompletedSuccessfully = false; error = error; } return { isCompletedSuccessfully, reposData, error }; } export const getMyUserName = async () => { try { const response = await axios.get(`https://api.github.com/user`, { headers: { Authorization: `token ${githubToken}`, }, }); return response.data.login; } catch (error) { return null; } }; export const getGitHubRepos = async () => { let { reposData, isCompletedSuccessfully, error } = await tryGettingGitHubRepos(); const RETRY_LIMIT = 3; let retryCount = 0; while (!isCompletedSuccessfully && retryCount++ <= RETRY_LIMIT) { await new Promise(resolve => setTimeout(resolve, 1500)); ({ reposData, isCompletedSuccessfully, error } = await tryGettingGitHubRepos()); } if (isCompletedSuccessfully) { return reposData; } if (!isCompletedSuccessfully) { console.error('Failed to fetch GitHub repositories:', error?.message, error?.response?.data); process.exit(1); } }