Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove Temporary Files if the program terminates abnormal #800

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
}
}
Loading