Created
October 27, 2017 10:39
-
-
Save 0sc/838b41c7f5d8bbddb89dbaf557fae893 to your computer and use it in GitHub Desktop.
Checks and returns true/false if there's any closed file (i.e not open file) in the given directory. anyclosedfile.In('/abs/path/to/dir')
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package anyclosedfile | |
import ( | |
"log" | |
"os" | |
"os/exec" | |
"path/filepath" | |
) | |
// In checks the given directory for files that are not being actively written to | |
// It return true if any file is found and return false otherwise | |
// It return any error that occurs | |
func In(dir string) (bool, error) { | |
// Initalize the verdict to false | |
foundClosedFile := false | |
// filepath.Walk iteratively executes the given function for each file in the specified directory | |
// and returns an error if something goes wrong | |
err := filepath.Walk(dir, func(path string, file os.FileInfo, er error) error { | |
// if an error occurs for the given file | |
if er != nil { | |
return er // return the error | |
} | |
// the walk function nicely recurses into subdirectory as well | |
// so we check that the current file in focus is not a directory | |
// and then check that it's not closed using the 'lsof' shell command | |
if !file.IsDir() && exec.Command("lsof", path).Run() != nil { | |
// in here means | |
// 1. file is not a directory | |
// 2. file is not open by any known process | |
log.Printf("Error: file -> %s is completed\n", file.Name()) // log the file | |
foundClosedFile = true // update the initial verdict | |
} | |
return nil // return nil since we didn't encounter any error | |
}) | |
return foundClosedFile, err // return the verdict and err (if any) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment