Skip to content

Commit

Permalink
Merge pull request #800 from Prince-Bhagat/adding-temp-directory-for-…
Browse files Browse the repository at this point in the history
…managing-temporary-files

Remove Temporary Files if the program terminates abnormal
  • Loading branch information
schollz authored Sep 3, 2024
2 parents defee4b + e663aa9 commit cdf3aa0
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 5 deletions.
28 changes: 25 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ package main

import (
"log"
"os"
"os/signal"
"syscall"

"github.com/schollz/croc/v10/src/cli"
"github.com/schollz/croc/v10/src/utils"
)

func main() {
Expand All @@ -27,7 +31,25 @@ func main() {
// fmt.Println("wrote profile")
// }
// }()
if err := cli.Run(); err != nil {
log.Fatalln(err)
}

// Create a channel to receive OS signals
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

go func() {
if err := cli.Run(); err != nil {
log.Fatalln(err)
}
}()

// Wait for a termination signal
sig := <-sigs
log.Println("Received signal:", sig)

// Perform any necessary cleanup here
log.Println("Performing cleanup...")
utils.CleanupTempData()

// Exit the program gracefully
os.Exit(0)
}
10 changes: 8 additions & 2 deletions src/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -446,9 +446,15 @@ func getStdin() (fnames []string, err error) {
fnames = []string{f.Name()}
return
}

func makeTempFolder() {
path := "temp"
if _, err := os.Stat(path); os.IsNotExist(err) {
os.Mkdir(path, os.ModePerm)
}
}
func makeTempFileWithString(s string) (fnames []string, err error) {
f, err := os.CreateTemp(".", "croc-stdin-")
makeTempFolder()
f, err := os.CreateTemp("temp", "croc-stdin-")
if err != nil {
return
}
Expand Down
10 changes: 10 additions & 0 deletions src/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -610,3 +610,13 @@ func ValidFileName(fname string) (err error) {
}
return
}
func CleanupTempData() {
path := "temp"
// Remove the directory and its contents
err := os.RemoveAll(path)
if err != nil {
log.Fatal(err)
} else {
log.Println("temp directory and its contents deleted successfully")
}
}

0 comments on commit cdf3aa0

Please sign in to comment.