UNPKG

@roadiehq/backstage-plugin-github-insights

Version:
115 lines (112 loc) 3.31 kB
import { useApi } from '@backstage/core-plugin-api'; import { Octokit } from '@octokit/rest'; import { useAsync } from 'react-use'; import { useProjectEntity } from './useProjectEntity.esm.js'; import { useEntityGithubScmIntegration } from './useEntityGithubScmIntegration.esm.js'; import { useStore } from '../components/store.esm.js'; import { scmAuthApiRef } from '@backstage/integration-react'; const NO_LICENSE_MSG = "No license file found"; const useProtectedBranches = (entity) => { const auth = useApi(scmAuthApiRef); const { baseUrl, hostname } = useEntityGithubScmIntegration(entity); const { owner, repo } = useProjectEntity(entity); const { state: branches, setState: setBranches } = useStore( (state) => state.branches ); const { value, loading, error } = useAsync(async () => { let result; try { const { token } = await auth.getCredentials({ url: `https://${hostname}/`, additionalScope: { customScopes: { github: ["repo"] } } }); const octokit = new Octokit({ auth: token }); const response = await octokit.request( "GET /repos/{owner}/{repo}/branches", { headers: { "if-none-match": branches.etag }, baseUrl, owner, repo, protected: true } ); result = { data: response.data, etag: response.headers.etag ?? "" }; } catch (e) { if (e.status === 304) { result = branches; } } return result; }, [baseUrl]); if (value) { setBranches(value); } return { branches: value ? value?.data : void 0, loading, error }; }; const useRepoLicence = (entity) => { const auth = useApi(scmAuthApiRef); const { baseUrl, hostname } = useEntityGithubScmIntegration(entity); const { owner, repo } = useProjectEntity(entity); const { state: license, setState: setLicense } = useStore( (state) => state.license ); const { value, loading, error } = useAsync(async () => { if (license.data === NO_LICENSE_MSG) { return license; } const { token } = await auth.getCredentials({ url: `https://${hostname}/`, additionalScope: { customScopes: { github: ["repo"] } } }); const octokit = new Octokit({ auth: token }); let result; try { const response = await octokit.request( "GET /repos/{owner}/{repo}/contents/{path}", { headers: { "if-none-match": license.etag }, baseUrl, owner, repo, path: "LICENSE" } ); const licenseData = atob(response.data.content).split("\n").map((line) => line.trim()).filter(Boolean)[0]; result = { etag: response.headers.etag ?? "", data: licenseData }; } catch (e) { if (e.status === 304) { return license; } else if (e.status === 404) { result = { etag: "", data: NO_LICENSE_MSG }; } } return result; }, [baseUrl]); if (value) { setLicense(value); } return { license: value ? value?.data : void 0, loading, error }; }; export { NO_LICENSE_MSG, useProtectedBranches, useRepoLicence }; //# sourceMappingURL=useComplianceHooks.esm.js.map