github.com/jbendotnet/noms@v0.0.0-20190904222105-c43e4293ea92/tools/file/file.go (about) 1 // Copyright 2016 Attic Labs, Inc. All rights reserved. 2 // Licensed under the Apache License, version 2.0: 3 // http://www.apache.org/licenses/LICENSE-2.0 4 5 package file 6 7 import ( 8 "fmt" 9 "io" 10 "os" 11 "path/filepath" 12 "runtime" 13 14 "github.com/attic-labs/noms/go/d" 15 ) 16 17 // DumbCopy copies the contents of a regular file at srcPath (following symlinks) to a new regular file at dstPath. New file is created with same mode. 18 func DumbCopy(srcPath, dstPath string) { 19 chkClose := func(c io.Closer) { d.PanicIfError(c.Close()) } 20 21 info, err := os.Stat(srcPath) 22 d.PanicIfError(err) 23 24 if info.IsDir() { 25 d.PanicIfError(ErrNoCopyDir) 26 } 27 28 src, err := os.Open(srcPath) 29 d.PanicIfError(err) 30 defer chkClose(src) 31 32 dst, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, info.Mode()) 33 d.PanicIfError(err) 34 defer chkClose(dst) 35 _, err = io.Copy(dst, src) 36 d.PanicIfError(err) 37 } 38 39 // MyDir returns the directory in which the file containing the calling source code resides. 40 func MyDir() string { 41 _, path, _, ok := runtime.Caller(1) 42 if !ok { 43 d.Panic("Should have been able to get Caller.") 44 } 45 return filepath.Dir(path) 46 } 47 48 var ErrNoCopyDir = fmt.Errorf("attempted to copy a directory")