Skip to content

Instantly share code, notes, and snippets.

@vladfil
Last active January 5, 2018 08:58
Show Gist options
  • Select an option

  • Save vladfil/2bda13a8b9aa43f3cb6bb27877ec6797 to your computer and use it in GitHub Desktop.

Select an option

Save vladfil/2bda13a8b9aa43f3cb6bb27877ec6797 to your computer and use it in GitHub Desktop.
CLI for copy files and folders to current directory
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
func returnError(err error) error {
if err != nil {
return err
fmt.Println("Error")
}
return nil
}
// Copy and paste file in another folder
func copyPasteFile(path, dest string) error {
filePath := path
file, err := os.Open(filePath)
returnError(err)
defer file.Close()
out, err := os.Create(dest + strings.Replace(filepath.Base(filePath), "/", "\\", -1))
returnError(err)
defer out.Close()
_, err = io.Copy(out, file)
returnError(err)
return nil
}
// Copy and paste folder in another folder
func copyPasteFolder(path, dest string) error {
sourceinfo, err := os.Stat(path)
returnError(err)
err = os.MkdirAll(dest, sourceinfo.Mode())
returnError(err)
dir, _ := os.Open(path)
objects, err := dir.Readdir(-1)
for _, obj := range objects {
srcFilePointer := path + "/" + obj.Name()
destinationFilePointer := dest + "/" + obj.Name()
if obj.IsDir() {
err := copyPasteFolder(srcFilePointer, destinationFilePointer)
returnError(err)
} else {
err := copyPasteFile(srcFilePointer, destinationFilePointer)
returnError(err)
}
}
return nil
}
func main() {
if len(os.Args) == 3 {
if os.Args[1] == "-f" {
copyPasteFile(os.Args[2], "")
} else if os.Args[1] == "-fd" {
ex, err := os.Executable()
returnError(err)
currentPathDir := filepath.Dir(ex)
folderPath := os.Args[2]
symPos := strings.LastIndex(os.Args[2], "/")
if symPos == -1 {
symPos = strings.LastIndex(os.Args[2], "\\")
}
copyPasteFolder(folderPath, currentPathDir+folderPath[symPos:])
} else {
fmt.Println("Use -f for copy file, or -fd for copy folder.\nFor example: ./custom-cli -f file.name")
}
} else {
fmt.Println("Use 3 params. Second param must be: -f for copy file, or -fd for copy folder.\nFor example: ./custom-cli -f file.name")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment