Skip to content

Instantly share code, notes, and snippets.

@magicianzrh
Created March 20, 2015 07:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save magicianzrh/d29d08f4fdd8b3c2f8ee to your computer and use it in GitHub Desktop.
Save magicianzrh/d29d08f4fdd8b3c2f8ee to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io"
"log"
"os"
)
var target_path string
var source_path string
func main() {
source_path = os.Args[1]
target_path = os.Args[2]
err := copy_folder(source_path, target_path)
if err != nil {
log.Fatal(err)
} else {
fmt.Print("copy finish")
}
}
func copy_folder(source string, dest string) (err error) {
sourceinfo, err := os.Stat(source)
if err != nil {
return err
}
err = os.MkdirAll(dest, sourceinfo.Mode())
if err != nil {
return err
}
directory, _ := os.Open(source)
objects, err := directory.Readdir(-1)
for _, obj := range objects {
sourcefilepointer := source + "/" + obj.Name()
destinationfilepointer := dest + "/" + obj.Name()
if obj.IsDir() {
err = copy_folder(sourcefilepointer, destinationfilepointer)
if err != nil {
fmt.Println(err)
}
} else {
err = copy_file(sourcefilepointer, destinationfilepointer)
if err != nil {
fmt.Println(err)
}
}
}
return
}
func copy_file(source string, dest string) (err error) {
sourcefile, err := os.Open(source)
if err != nil {
return err
}
defer sourcefile.Close()
destfile, err := os.Create(dest)
if err != nil {
return err
}
defer destfile.Close()
_, err = io.Copy(destfile, sourcefile)
if err == nil {
sourceinfo, err := os.Stat(source)
if err != nil {
err = os.Chmod(dest, sourceinfo.Mode())
}
}
return
}
@r0l1
Copy link

r0l1 commented Sep 16, 2016

Come on. If you copy code, then please recheck everything.

Same error as here.
This is wrong:

sourceinfo, err := os.Stat(source)
if err != nil {
    err = os.Chmod(dest, sourceinfo.Mode())
}

@r0l1
Copy link

r0l1 commented Sep 16, 2016

And you didn't handle the error case here:

    objects, err := directory.Readdir(-1)

    for _, obj := range objects {

@r0l1
Copy link

r0l1 commented Sep 16, 2016

And don't use fmt.Println! Return the error!

if obj.IsDir() {
    err = copy_folder(sourcefilepointer, destinationfilepointer)
    if err != nil {
        fmt.Println(err)
    }
} else {
    err = copy_file(sourcefilepointer, destinationfilepointer)
    if err != nil {
        fmt.Println(err)
    }
}

@r0l1
Copy link

r0l1 commented Sep 16, 2016

@Foorack
Copy link

Foorack commented Jul 2, 2017

@rol1 That link is now broken.

@tyru
Copy link

tyru commented Sep 24, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment