Best JavaScript code snippet using qawolf
handler.js
Source:handler.js
1const YAML = require('yaml')2const fs = require('fs')3const { Octokit } = require('@octokit/rest')4const { createPullRequest } = require('octokit-plugin-create-pull-request')5const { paginateRest } = require('@octokit/plugin-paginate-rest')6const MyOctokit = Octokit.plugin(createPullRequest).plugin(paginateRest)7const newOctokit = (installationId) => {8 const auth = {9 appId: process.env.APP_ID,10 privateKey: process.env.CERT11 }12 if (installationId) auth.installationId = installationId13 return new MyOctokit({14 authStrategy: require('@octokit/auth-app').createAppAuth,15 auth16 })17}18const cron = async () => {19 const octokit = newOctokit(0)20 const installations = await octokit.paginate(octokit.apps.listInstallations)21 const repos = await Promise.allSettled(22 installations.map(async (inst) => {23 const octokit = newOctokit(inst.id)24 return octokit25 .paginate(octokit.apps.listReposAccessibleToInstallation, inst.id)26 .then((repos) =>27 repos.filter(28 (repo) =>29 repo.fork === false &&30 repo.disabled === false &&31 repo.archived === false32 )33 )34 .then(async (repos) =>35 Promise.allSettled(36 repos.map(async (repo) => {37 return {38 ...repo,39 installationId: inst.id,40 octokit,41 desiredConfig: await getRepoConfig(42 repo.name,43 repo.owner.login,44 octokit45 )46 }47 })48 )49 )50 })51 )52 await Promise.allSettled(repos.flat().map(applyConfig))53}54const applyConfig = async (repo) => {55 const octokit = repo.octokit56 if (repo.desiredConfig.vulnerabilityAlerts === true) {57 await octokit.repos.enableVulnerabilityAlerts({58 owner: repo.owner.login,59 repo: repo.name60 })61 } else if (repo.desiredConfig.vulnerabilityAlerts === false) {62 octokit.repos.disableVulnerabilityAlerts({63 owner: repo.owner.login,64 repo: repo.name65 })66 }67 if (repo.desiredConfig.automatedSecurityFixes === true) {68 await octokit.repos.enableAutomatedSecurityFixes({69 owner: repo.owner.login,70 repo: repo.name71 })72 } else if (repo.desiredConfig.automatedSecurityFixes === false) {73 octokit.repos.disableAutomatedSecurityFixes({74 owner: repo.owner.login,75 repo: repo.name76 })77 }78 if (79 repo.desiredConfig.branchProtection &&80 repo.private === false &&81 repo.default_branch82 ) {83 const branchProtectionConfig = await Promise.allSettled(84 repo.desiredConfig.branchProtection.map(async (a) => {85 return {86 owner: repo.owner.login,87 repo: repo.name,88 ...a,89 branch:90 a.branch === '__DEFALT_BRANCH__' ? repo.default_branch : a.branch,91 required_status_checks:92 a.required_status_checks.contexts === 'ALL'93 ? await (async () => {94 try {95 a.required_status_checks.contexts = Array.from(96 new Set(97 (98 await octokit.checks.listForRef({99 owner: repo.owner.login,100 repo: repo.name,101 ref: `refs/heads/${102 a.branch === '__DEFALT_BRANCH__'103 ? repo.default_branch104 : a.branch105 }`106 })107 ).data.check_runs.map((check) => check.name)108 )109 )110 } catch (error) {111 a.required_status_checks.contexts = []112 }113 return a.required_status_checks114 })(a.required_status_checks)115 : a.required_status_checks116 }117 })118 )119 console.log(branchProtectionConfig[0])120 await Promise.allSettled(121 branchProtectionConfig.map(octokit.repos.updateBranchProtection)122 )123 }124 if (repo.desiredConfig.repo) {125 await octokit.repos.update({126 owner: repo.owner.login,127 repo: repo.name,128 ...repo.desiredConfig.repo129 })130 }131 if (repo.desiredConfig.files !== false) {132 try {133 await octokit.createPullRequest({134 owner: repo.owner.login,135 repo: repo.name,136 title: 'Update templated files',137 body: '',138 createWhenEmpty: false,139 head: 'repomanager_files',140 changes: [141 {142 files: repo.desiredConfig.files,143 emptyCommit: false,144 commit: 'Update templated files'145 }146 ]147 })148 } catch (error) {149 console.error(150 `${repo.full_name}: could not template file PR`,151 error.message152 )153 }154 }155}156const getRepoConfig = async (repo, owner, octokit) => {157 let configFromRepo = {}158 let configFromOwner = {}159 try {160 configFromRepo = YAML.parse(161 Buffer.from(162 (163 await octokit.repos.getContent({164 owner,165 repo,166 path: '.github/repo-config.yml'167 })168 ).data.content,169 'base64'170 ).toString()171 )172 } catch (error) {173 console.info(`${owner}/${repo}: could not get .github/repo-config.yml`)174 }175 try {176 configFromOwner = YAML.parse(177 Buffer.from(178 (179 await octokit.repos.getContent({180 owner,181 repo: '.github',182 path: 'repo-config.yml'183 })184 ).data.content,185 'base64'186 ).toString()187 )188 } catch (error) {189 console.warn(`${owner}/.github: could not get .github/repo-config.yml`)190 }191 const baseConfig = YAML.parse(192 fs.readFileSync('./base-repo-config.yml').toString()193 )194 return { ...baseConfig, ...configFromOwner, ...configFromRepo }195}196module.exports = {197 cron,198 getRepoConfig,199 applyConfig,200 newOctokit,201 MyOctokit...
github-app.js
Source:github-app.js
...56 * @return {Object[]} For each repository a subset of the data provided by github.57 */58 async getRepositories(installation_id){59 const octokit = await this.authenticateAsInstallation(installation_id)60 var response = await octokit.apps.listReposAccessibleToInstallation({per_page: 100}),61 repos = response.data.repositories || []62 //TODO: HANDLE MORE THAN 100 PAGES63 return repos.map( repository => ({64 name: repository.name,65 full_name: repository.full_name,66 owner: repository.owner,67 installation_id: installation_id,68 html_url: repository.html_url69 }))70 }71 /**72 * Create or Update an Issue. If issue.number is provided, update the corresponding issue, otherwise create a new one .73 * 74 * @param {Identifier} target_identifier Identifier pointing at a github repository...
scheduled.ts
Source:scheduled.ts
1import type { Probot, WebhookPayloadWithRepository } from "probot";2import { Context } from "probot";3import { promisify } from "util";4import { match, PullRequestBase } from "../matcher";5import { enqueue } from "../tasks/queue";6import { synchronizeManaged } from "../tasks/synchronize-managed";7const wait = promisify(setTimeout);8let running = true;9export function stop(): void {10 running = false;11}12async function waitUntil(date: number): Promise<void> {13 while (true) {14 if (Date.now() >= date) {15 break;16 }17 await wait(1000);18 }19}20export async function schedule(app: Probot): Promise<void> {21 // default: no delay at startup22 const delay = Number(process.env["SCHEDULE_DELAY"] ?? "0");23 // default: run every 30 minutes24 const timeout = Number(25 process.env["SCHEDULE_TIMEOUT"] ?? String(1000 * 60 * 30)26 );27 app.log.info({ delay, timeout }, "Scheduler");28 if (timeout < 0) {29 return;30 }31 await waitUntil(Date.now() + delay);32 running = true;33 while (running) {34 const next = Date.now() + timeout;35 await runScheduled(app);36 await waitUntil(next);37 }38}39async function runScheduled(app: Probot): Promise<void> {40 const appOctokit = await app.auth();41 const installations = await appOctokit.paginate(42 appOctokit.apps.listInstallations,43 { per_page: 100 }44 );45 for (const installation of installations) {46 if (!running) {47 break;48 }49 const octokit = await app.auth(installation.id);50 const repositories = await octokit.paginate(51 octokit.apps.listReposAccessibleToInstallation,52 { per_page: 100 }53 );54 for (const repository of repositories) {55 if (!running) {56 break;57 }58 const context = new Context<WebhookPayloadWithRepository>(59 {60 id: `event.scheduled.${repository.id}`,61 name: "scheduled" as any,62 payload: {63 repository: {64 ...repository,65 mirror_url: null,66 },67 },68 },69 octokit,70 app.log71 );72 try {73 await onScheduled(context);74 } catch (e) {75 context.log.warn(76 e,77 `Unable to run scheduler on ${repository.full_name}`78 );79 }80 }81 }82}83async function onScheduled(context: Context<any>) {84 const prs = await context.octokit.paginate(85 context.octokit.pulls.list,86 context.repo({87 state: "open" as const,88 per_page: 100,89 })90 );91 for (const pr of prs) {92 if (!running) {93 break;94 }95 const pullRequest: PullRequestBase = {96 ...pr,97 state: pr.state as "open" | "closed",98 labels: pr.labels.map((label) => label.name),99 };100 await match(context, pullRequest, {101 async managed(managed) {102 enqueue(103 context,104 `scheduled update of ${managed}`,105 synchronizeManaged(context, managed)106 );107 },108 });109 }...
handle-installation.js
Source:handle-installation.js
1module.exports = handleInstallation;2const pluralize = require("pluralize");3const getConfig = require("./app-config");4const resetRepositories = require("./common/reset-repositories");5/**6 * On install or accepted permissions: update all PRs for installs7 * On uninstall: just log8 *9 * @param {import('probot').Probot} app10 * @param {import('probot').Context} context11 */12async function handleInstallation(app, context) {13 const {14 action,15 repositories,16 repositories_added: added,17 repositories_removed: removed,18 installation: { account, repository_selection: selection },19 } = context.payload;20 const log = context.log.child({21 name: getConfig().name,22 event: context.name,23 action,24 account: account.id,25 accountType: account.type.toLowerCase(),26 accountName: account.login,27 selection: selection,28 });29 if (action === "deleted") {30 log.info(`ð ${account.type} ${account.login} uninstalled`);31 return;32 }33 if (action === "removed") {34 log.info(35 `â ${account.type} ${account.login} removed ${pluralize(36 "repository",37 removed.length,38 true39 )}`40 );41 return;42 }43 if (action === "created") {44 log.info(45 `ð¤ ${account.type} ${account.login} installed on ${pluralize(46 "repository",47 repositories.length,48 true49 )}`50 );51 return resetRepositories({52 app,53 context,54 account,55 repositories,56 });57 }58 if (action === "added") {59 log.info(60 `â ${account.type} ${account.login} added ${pluralize(61 "repository",62 added.length,63 true64 )}`65 );66 return resetRepositories({67 app,68 context,69 account,70 repositories: added,71 });72 }73 if (action === "new_permissions_accepted") {74 log.info(`ð ${account.type} ${account.login} accepted new permissions`);75 return resetRepositories({76 app,77 context,78 account,79 repositories: await context.octokit.paginate(80 context.octokit.apps.listReposAccessibleToInstallation,81 { per_page: 100 }82 ),83 });84 }85 log.info(`â¹ï¸ installation.${action} by ${account.login}`);...
app-added.ts
Source:app-added.ts
1import { EventTypesPayload, WebhookEvent } from "@octokit/webhooks";2import type { Context } from "probot";3import { setupBot } from "../setup";4export async function onAppInstalled(5 probotContext: EventTypesPayload["installation.created"] &6 Omit<Context<any>, keyof WebhookEvent<any>>7) {8 for (const repository of probotContext.payload.repositories) {9 await setupRepository(10 probotContext,11 probotContext.payload.installation.account.login,12 repository.name13 );14 }15}16export async function onRepositoriesAdded(17 probotContext: EventTypesPayload["installation_repositories.added"] &18 Omit<Context<any>, keyof WebhookEvent<any>>19) {20 if (probotContext.payload.repository_selection === "selected") {21 for (const repository of probotContext.payload.repositories_added) {22 await setupRepository(23 probotContext,24 probotContext.payload.installation.account.login,25 repository.name26 );27 }28 } else {29 const repositories = await probotContext.octokit.paginate(30 probotContext.octokit.apps.listReposAccessibleToInstallation31 );32 for (const repository of repositories) {33 await setupRepository(34 probotContext,35 probotContext.payload.installation.account.login,36 repository.name37 );38 }39 }40}41async function setupRepository(42 probotContext: Omit<Context<any>, keyof WebhookEvent<any>>,43 owner: string,44 repo: string45): Promise<void> {46 // For this payload `context.repo` is not available in probot,47 // so we create our own wrapper48 const context = {49 ...probotContext,50 repo: <T>(object: T) => ({51 owner,52 repo,53 ...object,54 }),55 };56 try {57 await setupBot(context);58 } catch (e) {59 context.log.error(e, `Failed to setup repository ${owner}/${repo}`);60 }...
Using AI Code Generation
1const { Octokit } = require("@octokit/rest");2const octokit = new Octokit({3});4 .listReposAccessibleToInstallation({5 })6 .then((response) => {7 console.log(response);8 });
Using AI Code Generation
1const { Octokit } = require('qawolf');2const octokit = new Octokit({3});4async function main() {5 const response = await octokit.apps.listReposAccessibleToInstallation({6 });7 console.log(response.data.repositories);8}9main();10at processTicksAndRejections (internal/process/task_queues.js:93:5)11at async main (/Users/abhisheksingh/Desktop/abhi/test.js:14:3)12at processTicksAndRejections (internal/process/task_queues.js:93:5)13at async main (/Users/abhisheksingh/Desktop/abhi/test.js:14:3)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!