UNPKG

octokit-plugin-create-pull-request

Version:

Octokit plugin to create a pull request with multiple file changes

100 lines (99 loc) 2.62 kB
import { valueToTreeObject } from "./value-to-tree-object.js"; import { DELETE_FILE } from "./constants.js"; async function createTree(state, changes) { const { octokit, owner, repo, ownerOrFork, latestCommitSha, latestCommitTreeSha } = state; let tree = []; for (const path of Object.keys(changes.files)) { const value = changes.files[path]; if (value === DELETE_FILE) { try { await octokit.request("HEAD /repos/{owner}/{repo}/contents/:path", { owner: ownerOrFork, repo, ref: latestCommitSha, path }); tree.push({ path, mode: "100644", sha: null }); continue; } catch (error) { continue; } } if (typeof value === "function") { let result; try { const { data: file } = await octokit.request( "GET /repos/{owner}/{repo}/contents/:path", { owner: ownerOrFork, repo, ref: latestCommitSha, path } ); result = await value( Object.assign(file, { exists: true }) ); if (result === DELETE_FILE) { try { await octokit.request("HEAD /repos/{owner}/{repo}/contents/:path", { owner: ownerOrFork, repo, ref: latestCommitSha, path }); tree.push({ path, mode: "100644", sha: null }); continue; } catch (error) { continue; } } } catch (error) { if (error.status !== 404) throw error; result = await value({ exists: false }); } if (result === null || typeof result === "undefined" || typeof result === "symbol") { continue; } tree.push( // @ts-expect-error - Argument result can never be of type Symbol at this branch // because the above condition will catch it and move on to the next iteration cycle await valueToTreeObject(octokit, ownerOrFork, repo, path, result) ); continue; } tree.push(await valueToTreeObject(octokit, ownerOrFork, repo, path, value)); continue; } tree = tree.filter(Boolean); if (tree.length === 0) { return null; } const { data: { sha: newTreeSha } } = await octokit.request("POST /repos/{owner}/{repo}/git/trees", { owner: ownerOrFork, repo, base_tree: latestCommitTreeSha, tree }); return newTreeSha; } export { createTree };