2023-06-08 13:08:51 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
/*help to copy the file, ioutil doesn't offer the feature*/
|
|
|
|
|
|
|
|
func copyFileContents(src, dst string) (err error) {
|
|
|
|
in, err := os.Open(src)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer in.Close()
|
2024-01-03 09:55:41 +00:00
|
|
|
|
2023-06-08 13:08:51 +00:00
|
|
|
out, err := os.Create(dst)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2024-01-03 09:55:41 +00:00
|
|
|
|
2023-06-08 13:08:51 +00:00
|
|
|
defer func() {
|
|
|
|
cerr := out.Close()
|
|
|
|
if err == nil {
|
|
|
|
err = cerr
|
|
|
|
}
|
|
|
|
}()
|
2024-01-03 09:55:41 +00:00
|
|
|
|
2023-06-08 13:08:51 +00:00
|
|
|
if _, err = io.Copy(out, in); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2024-01-03 09:55:41 +00:00
|
|
|
|
2023-06-08 13:08:51 +00:00
|
|
|
err = out.Sync()
|
2024-01-03 09:55:41 +00:00
|
|
|
|
2023-06-08 13:08:51 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
/*copy the file, ioutile doesn't offer the feature*/
|
2024-01-24 16:31:34 +00:00
|
|
|
func CopyFile(sourceSymLink, destinationFile string) error {
|
2023-06-08 13:08:51 +00:00
|
|
|
sourceFile, err := filepath.EvalSymlinks(sourceSymLink)
|
|
|
|
if err != nil {
|
|
|
|
log.Infof("Not a symlink : %s", err)
|
2024-01-03 09:55:41 +00:00
|
|
|
|
2023-06-08 13:08:51 +00:00
|
|
|
sourceFile = sourceSymLink
|
|
|
|
}
|
|
|
|
|
|
|
|
sourceFileStat, err := os.Stat(sourceFile)
|
|
|
|
if err != nil {
|
2024-01-24 16:31:34 +00:00
|
|
|
return err
|
2023-06-08 13:08:51 +00:00
|
|
|
}
|
2024-01-03 09:55:41 +00:00
|
|
|
|
2023-06-08 13:08:51 +00:00
|
|
|
if !sourceFileStat.Mode().IsRegular() {
|
|
|
|
// cannot copy non-regular files (e.g., directories,
|
|
|
|
// symlinks, devices, etc.)
|
|
|
|
return fmt.Errorf("copyFile: non-regular source file %s (%q)", sourceFileStat.Name(), sourceFileStat.Mode().String())
|
|
|
|
}
|
2024-01-03 09:55:41 +00:00
|
|
|
|
2023-06-08 13:08:51 +00:00
|
|
|
destinationFileStat, err := os.Stat(destinationFile)
|
|
|
|
if err != nil {
|
|
|
|
if !os.IsNotExist(err) {
|
2024-01-24 16:31:34 +00:00
|
|
|
return err
|
2023-06-08 13:08:51 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if !(destinationFileStat.Mode().IsRegular()) {
|
|
|
|
return fmt.Errorf("copyFile: non-regular destination file %s (%q)", destinationFileStat.Name(), destinationFileStat.Mode().String())
|
|
|
|
}
|
|
|
|
if os.SameFile(sourceFileStat, destinationFileStat) {
|
2024-01-24 16:31:34 +00:00
|
|
|
return err
|
2023-06-08 13:08:51 +00:00
|
|
|
}
|
|
|
|
}
|
2024-01-03 09:55:41 +00:00
|
|
|
|
2023-06-08 13:08:51 +00:00
|
|
|
if err = os.Link(sourceFile, destinationFile); err != nil {
|
|
|
|
err = copyFileContents(sourceFile, destinationFile)
|
|
|
|
}
|
2024-01-03 09:55:41 +00:00
|
|
|
|
2024-01-24 16:31:34 +00:00
|
|
|
return err
|
2023-06-08 13:08:51 +00:00
|
|
|
}
|
|
|
|
|