import type { Changes , State , TreeParameter , UpdateFunctionFile , } from "./types" ; import { valueToTreeObject } from "./value-to-tree-object" ; export async function createTree ( state , changes ) { const { octokit , owner , repo , fork , latestCommitSha , latestCommitTreeSha , } = state ; const tree = ( await Promise . all ( Object . keys ( changes . files ) . map ( async ( path ) => { const value = changes . files [ path ] ; if ( value === null ) { try { await octokit . request ( "HEAD /repos/{owner}/{repo}/contents/:path" , { owner : fork , repo , ref : latestCommitSha , path , } ) ; return { path , mode : "100644" , sha : null , } ; } catch ( error ) { return ; } } if ( typeof value === "function" ) { let result ; try { const { data : file } = await octokit . request ( "GET /repos/{owner}/{repo}/contents/:path" , { owner : fork , repo , ref : latestCommitSha , path , } ) ; result = await value ( Object . assign ( file , { exists : true } ) as UpdateFunctionFile ) ; } catch ( error ) { if ( error . status !== 404 ) throw error ; result = await value ( { exists : false } ) ; } if ( result === null || typeof result === "undefined" ) return ; return valueToTreeObject ( octokit , owner , repo , path , result ) ; } return valueToTreeObject ( octokit , owner , repo , path , value ) ; } ) ) ) . filter ( Boolean ) as TreeParameter ; if ( tree . length === 0 ) { return null ; } const { data : { sha : newTreeSha } , } = await octokit . request ( "POST /repos/{owner}/{repo}/git/trees" , { owner : fork , repo , base_tree : latestCommitTreeSha , tree , } ) ; return newTreeSha ; }