package main
import (
"crypto/md5"
"fmt"
"io"
"os"
"path/filepath"
)
// Function to calculate the MD5 checksum of a file
func fileMD5(path string) ([16]byte, error) {
var result [16]byte
file, err := os.Open(path)
if err != nil {
return result, err
}
defer file.Close()
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return result, err
}
copy(result[:], hash.Sum(nil))
return result, nil
}
// Function to copy a file from src to dst
func copyFile(src, dst string, perm os.FileMode) error {
// Open the source file
sourceFile, err := os.Open(src)
if err != nil {
return err
}
defer sourceFile.Close()
// Create the destination file
destFile, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, perm)
if err != nil {
return err
}
defer destFile.Close()
// Copy the content
_, err = io.Copy(destFile, sourceFile)
return err
}
func main() {
if len(os.Args) != 3 {
fmt.Println("Usage: rsync-go <source_dir> <destination_dir>")
os.Exit(1)
}
sourceDir := os.Args[1]
destinationDir := os.Args[2]
// Walk through the source directory
err := filepath.Walk(sourceDir, func(srcPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Compute the relative path
relPath, err := filepath.Rel(sourceDir, srcPath)
if err != nil {
return err
}
destPath := filepath.Join(destinationDir, relPath)
if info.IsDir() {
// Ensure the destination directory exists
if _, err := os.Stat(destPath); os.IsNotExist(err) {
err := os.Mkdir(destPath, info.Mode())
if err != nil {
return err
}
fmt.Printf("Created directory: %s\n", destPath)
}
} else {
// Check if the file exists in the destination
needCopy := false
if destInfo, err := os.Stat(destPath); os.IsNotExist(err) {
// File doesn't exist in destination
needCopy = true
} else {
// Compare file sizes and MD5 checksums
if info.Size() != destInfo.Size() {
needCopy = true
} else {
srcMD5, err := fileMD5(srcPath)
if err != nil {
return err
}
destMD5, err := fileMD5(destPath)
if err != nil {
return err
}
if srcMD5 != destMD5 {
needCopy = true
}
}
}
if needCopy {
// Copy the file
err := copyFile(srcPath, destPath, info.Mode())
if err != nil {
return err
}
fmt.Printf("Copied file: %s\n", destPath)
}
}
return nil
})
if err != nil {
fmt.Printf("Error during synchronization: %v\n", err)
}
}
This basic Go program provides foundational functionality similar to rsync for local directories. It's a great starting point for learning about file synchronization, directory traversal, and file manipulation in Go. You can extend and customize it to meet more specific needs or to handle more complex synchronization tasks.