Removing a directory from GitHub with the help of octokit/rest

I am attempting to utilize octokit/rest in order to programmatically remove a directory. Below is the code I am using:

import {Octokit as Github} from '@octokit/rest';

const githubToken = "read from vault";

// Functions for retrieving current commit, creating new commit, setting branch to commit, 
// getting directory SHA, and deleting from repository

export const deleteDirectoryFromGithubRepo = async (
    directoryName: string
) => {
  // Code logic here...
}

Upon calling deleteDirectoryFromGithubRepo, it creates an empty commit on GitHub. This means that a commit is made without any changes.

I have researched that passing the current commit may be causing the deleted files to be restored. However, removing it results in an error message saying Update is not a fast forward.

Full response from GitHub:

{
  "name": "HttpError",
  "status": 422,
  "response": {
    "url": "https://api.github.com/repos/myOrg/myRepo/git/refs/heads%2Fmain",
    "status": 422,
    "headers": {
      "header1": "*",
      "header2": "*"
    },
    "data": {
      "message": "Update is not a fast forward",
      "documentation_url": "https://docs.github.com/rest/reference/git#update-a-reference"
    }
  },
  "request": {
    "method": "PATCH",
    "url": "https://api.github.com/repos/myOrg/myRepo/git/refs/heads%2Fmain",
    "headers": {
      "accept": "application/vnd.github.v3+json",
      "user-agent": "octokit-rest.js/18.12.0 octokit-core.js/3.6.0 Node.js/14.19.3 (linux; x64)",
      "authorization": "token [REDACTED]",
      "content-type": "application/json; charset=utf-8"
    },
    "body": "{\"sha\":\"75dd3**************ee3da188d4\"}",
    "request": {}
  }
}

The version of octokit-rest.js being used is 18.12.0.

Do you have any suggestions on how to resolve this issue?

Answer №1

This solution was presented in this forum thread, showcasing a method for deleting a directory effectively.

const removeDirectory = async (
    github: Github,
    org: string,
    repo: string,
    dirName: string
) => {
    const currentCommit = await getCurrentCommit(github, org, repo);

    const {data: repositoryTree} = await github.git.getTree({
        owner: org,
        repo,
        tree_sha: currentCommit.treeSha
    })

    const dirSha = await getDirectorySha(repositoryTree.tree, dirName);

    if (!dirSha) {
        throw new Error(`The directory '${dirName}' was not found`)
    }

    const {data: folderTree} = await github.git.getTree({
        owner: org,
        repo,
        tree_sha: dirSha
    })

    const blobs: Blob[] = folderTree.tree.map((blob) => {
        return {'url': `${dirName}/${blob.path}`, 'sha': null}
    });

    const newTree = await createNewTree(
        github,
        org,
        repo,
        blobs,
        currentCommit.treeSha
    )

    const commitMessage = `Removing files from directory '${dirName}'.`
    const newCommit = await createNewCommit(
        github,
        org,
        repo,
        commitMessage,
        newTree.sha,
        currentCommit.commitSha
    )
    await setBranchToCommit(github, org, repo, newCommit.sha)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for TypeScript inferring the generic type as an empty string?

I have developed a React component known as StateWithValidation. import { useStateWithValidation } from "./useStateWithValidation"; export const StateWithValidation = () => { const [username, setUserName, isValid] = useStateWithValidation( ( ...

FIREBASE_AUTHCHECK_DEBUG: Error - 'self' is undefined in the debug reference

I'm encountering an issue while trying to implement Firebase Appcheck in my Next.js Typescript project. firebase.ts const fbapp = initializeApp(firebaseConfig); if (process.env.NODE_ENV === "development") { // @ts-ignore self.FIREBASE_ ...

Angular form retains the previous value when saving

I encountered an issue with my form component where it displays previous values instead of updated ones during a save operation. The strange part is that if I close the form and reopen it, the new values are then shown correctly. It seems like the problem ...

Upgrading a Basic ReactJS Example to Typescript

Beginner Inquiry I recently converted a ReactJS script from Javascript to Typescript. Is there a more concise way to do this without relying heavily on "any" types? Original Javascript version: const App = ({title}) => ( <div>{title}</div& ...

Disable inline imports when implementing an interface in vscode by selecting the "Implement interface" option

When using TypeScript, if I perform an auto-fix on a class name by selecting "Implement interface", it will generate the methods with inline imports like this: getInbox(): Observable<import('../../model/Message').Interactions[]> { t ...

Guide to iterating through different endpoints in a predetermined sequence

I am facing a challenge with testing various endpoints using different login credentials. When looping through the endpoints, the results are not appearing in the sequential order due to asynchronous nature. My goal is to iterate through each endpoint wit ...

Troubleshooting Next.js Mobile Freeze Issue: Unresponsive Scroll After Page Transition

Encountered a strange bug while testing my Next.js + Bootstrap demo project on mobile view. When using the burger menu to navigate to a new page on a mobile phone, attempting to scroll down causes it to stick/freeze/hang inexplicably. Despite my efforts to ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

What is the best way to incorporate an interface in TypeScript that is both callable and has properties?

Given the scenario where an interface is defined as: interface FooWithBar { ():void; bar():void; } I am struggling with writing the implementation. I attempted the following: function foo(){ } foo.bar = function(){ }; This approach did not wo ...

Create a new visual masterpiece using Canvas by repurposing an

I am currently working on the following code snippet; export default async function draw(elRef : RefObject<HTMLCanvasElement>, tileData : TileProps) { const canvas = elRef.current!; const ctx = canvas.getContext('2d')!; ctx.clearRect( ...

Having trouble getting a React Hook to function properly in NextJS with TypeScript. Let's troubleshoot

I'm currently utilizing NextJS to showcase information fetched from a database in a table format. After retrieving the data, my intention is to leverage the map function to generate table rows and then incorporate them into the table. import React, {u ...

What steps are needed to have typescript recognize a typed function as a throw-statement?

I'm grappling with a typescript issue - I have a custom function that consistently throws an error, which is used to handle null variables. Strangely, if I directly throw an error without using the function, typescript recognizes that the variable can ...

Having difficulty transitioning a function with a promise from JavaScript to TypeScript

I am currently in the process of transitioning my existing NodeJS JavaScript code to TypeScript for a NodeJS base, which will then be converted back to JavaScript when running on NodeJS. This approach helps me maintain clear types and utilize additional fe ...

Guidance on transferring information from a parent component to an Angular Material table child component

Currently, I am implementing an angular material table with sorting functionality. You can view the example here: Table Sorting Example I intend to transform this into a reusable component so that in the parent component, all I have to do is pass the colu ...

Can you explain how the "reduce" function can be implemented using an interface in TypeScript?

Can you explain the "reduce" function using an interface in TypeScript? https://i.stack.imgur.com/X1VxL.png ...

What is the key to mastering any concept in Angular2 for optimal results?

When creating a Pipe to filter data, I often use the datatype any, allowing for flexibility with types. However, I have some questions regarding this approach: Is it considered a best practice? Does it impact performance when handling large amounts of da ...

Having trouble setting up mongodb-memory-server 8 to work with jest

I am currently working on integrating the latest version of mongodb-memory-server with jest on a node express server. While following the guide provided in the mongodb-memory-server documentation (), I encountered some gaps that I am struggling to fill in. ...

A comprehensive guide on extracting data from the query string in Angular

There is a specific query string format that we need to handle. The input parameter of the method comes in the form of a string and it's not an instance of ActivatedRoute. http://localhost:4200/users?param1=en&param2=nk I've attempted to rea ...

Issue encountered when trying to use Array.sort() method to sort an array of objects

I'm facing an issue sorting an array of objects by a name property present on each object. When utilizing the sort() method with the given code snippet, I encounter the following error: ERROR ReferenceError: b is not defined This is my code block: m ...

Issues with implementing AddEventListener in InAppBrowser on IONIC 2

I am currently working on implementing AddeventListener to listen for 'Exit' and 'LoadStart' events in InAppBrowser within IONIC2. Here is my HTML: <button (click)="browsersystem('https://www.google.com')" > Visit URL& ...