Edits history of script submission #23196 for ' Create or Update File Contents (github)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create or Update File Contents
     * Commit a text file to a branch, creating it or replacing its content. The existing file's SHA is looked up automatically.
     */
    export async function main(
      auth: RT.Github,
      owner: string,
      repo: string,
      path: string,
      content: string,
      message: string,
      branch: string | undefined
    ) {
      const headers = {
        Authorization: `Bearer ${auth.token}`,
        Accept: "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28",
      }
      const url = new URL(
        `https://api.github.com/repos/${owner}/${repo}/contents/${path}`
      )
    
      // Updating needs the current blob SHA; a 404 means the file is new.
      const lookup = new URL(url)
      if (branch) lookup.searchParams.append("ref", branch)
      const existing = await fetch(lookup, { headers })
      if (!existing.ok && existing.status !== 404) {
        throw new Error(`${existing.status} ${await existing.text()}`)
      }
      const sha = existing.ok
        ? ((await existing.json()) as { sha: string }).sha
        : undefined
    
      // UTF-8 safe base64
      let binary = ""
      for (const byte of new TextEncoder().encode(content))
        binary += String.fromCharCode(byte)
    
      const response = await fetch(url, {
        method: "PUT",
        headers: { ...headers, "Content-Type": "application/json" },
        body: JSON.stringify({ message, content: btoa(binary), branch, sha }),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 2 hours ago