OSDN Git Service

928bc4d5d91c80d76ef228b86119f34b8a7ee588
[bytom/vapor.git] / toolbar / osssync / util / file.go
1 package util
2
3 import "os"
4
5 // FileUtil is a struct of File utility
6 type FileUtil struct {
7         LocalDir string
8 }
9
10 // IsExists if file or directory exist
11 func IsExists(path string) bool {
12         _, err := os.Stat(path)
13         if err != nil && !os.IsExist(err) {
14                 return false
15         }
16         return true
17 }
18
19 // IfNoFileToCreate if the file is not exist, create the file
20 func IfNoFileToCreate(fileName string) (file *os.File) {
21         var f *os.File
22         var err error
23         if !IsExists(fileName) {
24                 f, err = os.Create(fileName)
25                 if err != nil {
26                         return
27                 }
28                 defer f.Close()
29         }
30         return f
31 }
32
33 // PathExists return if path exists
34 func PathExists(path string) (bool, error) {
35         _, err := os.Stat(path)
36         if err == nil {
37                 return true, nil
38         }
39
40         return false, err
41 }
42
43 // RemoveLocal deletes file
44 func (f *FileUtil) RemoveLocal(filename string) error {
45         return os.Remove(f.LocalDir + "/" + filename)
46 }
47
48 // BlockDirInitial initializes the blocks directory
49 func (f *FileUtil) BlockDirInitial() error {
50         ifPathExist, err := PathExists(f.LocalDir)
51         if err != nil {
52                 return err
53         }
54
55         if ifPathExist {
56                 err = os.RemoveAll(f.LocalDir)
57                 if err != nil {
58                         return err
59                 }
60         }
61
62         err = os.Mkdir(f.LocalDir, 0755)
63         return err
64 }