If I were to do it on Linux alone, it'd be easy with the following code:
package main
import (
"fmt"
"log"
"os/exec"
)
func main() {
err := exec.Command("cp", "-rl", "src/path", "target/path").Run()
if err != nil {
log.Fatal(err)
}
}
However, I am looking for a way to do so in Golang so that it works across different operating systems.
It's really depends on the underling filesystem that support for linking a file or not. but below is the code snippet that i think works for the most OS (tested on macOS and ubuntu 20.04)
package main
import (
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
)
func main() {
err := filepath.WalkDir("src/path", func(path string, d fs.DirEntry, err error) error {
if err != nil {
log.Fatal(err)
}
if d.IsDir() {
return nil
}
destinationFile := fmt.Sprintf("/target/%s", path)
err = os.Link(path, destinationFile)
if err != nil {
log.Fatal(err)
}
return nil
})
if err != nil {
log.Fatal(err)
}
}