Search code examples
javascriptgithubgithub-actionsgithub-api

How to open a list of PRs automatically in Github?


We have a repo (SaaS project) that contains a list of branches (50-100), the master branch is up to date, So I want to open a list of PRs for every branch we have to take updates from

master -> client-*

So is there a way to handle this case automatically?


Solution

  • You can use Github's API to fetch all of your branches and to publish PRs. Unfortunately, Github doesn't provide a method for filtering when listing branches, so you will still need to apply that filter in your own code.

    Here's an example execution using Octokit. The two methods needed are repos.listBranches and pulls.create.

    Example Implementation
      // Fetching branches...
      const branches = await userClient.paginate(userClient.rest.repos.listBranches, {
        owner: ownerId,
        repo: reposId,
      });
    
      // Filtering the retrieved branches.
      const prefixedBranches = branches.filter((branch) => branch.name.startsWith(branchPrefix));
      console.log(`${prefixedBranches.length} branches match the filter`);
    
      // Creating pull requests...
      const result = await Promise.allSettled(
        prefixedBranches.map((branch) => {
          return userClient.rest.pulls.create({
            title: `Fusebit Generated PR from ${branch.name}`,
            head: branch.name,
            base: targetBranch,
            owner: ownerId,
            repo: reposId,
          });
        })
      );