I have a task to copy directory, and paste it in an another folder with conditions using Go.
For example I have a directory tree such like that:
project
---app(where to copy)
---packages(from where copy)
------process
---------client01
------------build(folder)
---------------main.go
---------------config.json
---------------someFolder
------------someText.txt
---------client02
------------test4
---------------build
------------testProject
---------client04
------------projectX
------------test.go
The condition is copying only directory which only has child folder with name "build" and in the copied parent folder should be only build folder within its files.
package main
import (
"io"
"io/ioutil"
"os"
"path"
)
// File copies a single file from src to dst
func File(src, dst string) error {
var err error
var srcfd *os.File
var dstfd *os.File
var srcinfo os.FileInfo
if srcfd, err = os.Open(src); err != nil {
return err
}
defer srcfd.Close()
if dstfd, err = os.Create(dst); err != nil {
return err
}
defer dstfd.Close()
if _, err = io.Copy(dstfd, srcfd); err != nil {
return err
}
if srcinfo, err = os.Stat(src); err != nil {
return err
}
return os.Chmod(dst, srcinfo.Mode())
}
// Dir copies a whole directory recursively
func Dir(src string, dst string) error {
//var files Files
var err error
var fds []os.FileInfo
var srcinfo os.FileInfo
if srcinfo, err = os.Stat(src); err != nil {
return err
}
if fds, err = ioutil.ReadDir(src); err != nil {
return err
}
if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
return err
}
for _, fd := range fds {
srcfp := path.Join(src, fd.Name())
dstfp := path.Join(dst, fd.Name())
if fd.IsDir() && srcfp == src + "/build" {
//files = append(files, dstfp)
println(srcfp)
if err = Dir(srcfp, dstfp); err != nil {
return err
}
if err = File(srcfp, dstfp); err != nil {
return err
}
} else if fd.IsDir() && srcfp == srcfp {
if err = Dir(srcfp, dstfp); err != nil {
return err
}
} else {
if err = File(srcfp, dstfp); err != nil {
return err
}
}
}
return nil
}
func main () {
err := Dir("./packages", "./app")
if err != nil {
println(err)
}
}
I expected a result directory tree in app:
project
---app(where to copy)
------client01
---------build
------------main.go
------------config.json
------------someFolder
------test4
---------build
For instance, test4 and client01 copied because it has "build" child-folder, and it copies only build folder
But I got that result directory tree:
project
---app
------process(that folder should not be copied)
---------client01
-----------build
--------------main.go
--------------config.json