This repository has been archived by the owner on Dec 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharchive.go
75 lines (66 loc) · 2.11 KB
/
archive.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
)
// gets the array of files which should be archived by searchFileByFileSize() and destFolder
func archive(sourceFiles []string, filenames []string, destFolder string, randPrefix string) error {
if whichOS == "windows" {
destFolder = filepath.FromSlash(destFolder) //only for windows
}
fileCount := 0
for i, sourceFile := range sourceFiles {
// Because moving files with os.Rename to other hard-drives is not allowed, files must be created by new
// os.Rename only works on the same hard-drive
/*err := os.Rename(sourceFile, destFolder+randPrefix+strconv.Itoa(fileCount)+filenames[i])
if err != nil {
return err
}
*/
//open the sourceFile
inputFile, err := os.Open(sourceFile)
if err != nil {
return fmt.Errorf("couldn't open source file: %s", err)
}
//create the new file
outputFile, err := os.Create(destFolder + randPrefix + strconv.Itoa(fileCount) + filenames[i])
if err != nil {
err = inputFile.Close()
return fmt.Errorf("could not open dest file: %s", err)
}
//copy the content from source to destination
_, err = io.Copy(outputFile, inputFile)
if err != nil {
return fmt.Errorf("writing to output file failed: %s", err)
}
err = inputFile.Close()
if err != nil {
return fmt.Errorf("closing inputFile failed: %s", err)
}
err = outputFile.Close()
if err != nil {
return fmt.Errorf("closing outputFile failed: %s", err)
}
// The copy was successful, so now delete the original file
err = os.Remove(sourceFile)
if err != nil {
return fmt.Errorf("failed removing original file: %s", err)
}
err = sysLogging(sourceFile, destFolder+randPrefix+strconv.Itoa(fileCount)+filenames[i])
if err != nil {
return err
}
//new output name is, something random + file-id + file-name, this prevent matching file-names
err = os.Symlink(destFolder+randPrefix+strconv.Itoa(fileCount)+filenames[i], sourceFile)
if err != nil {
return err
}
message(0, "[archive]", sourceFile, destFolder+randPrefix+strconv.Itoa(fileCount)+filenames[i])
fileCount++
}
message(0, "[archive]")
return nil
}