pw_toolchain: Fix copy rules on Mac

Copy rules are always dirty on Mac because cp -af doesn't preserve the
timestamps with full fidelity.

Change-Id: Ib7b7e346ca46bebe5e38832ae491fafeedfd0035
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/12665
Reviewed-by: Keir Mierle <keir@google.com>
Commit-Queue: Keir Mierle <keir@google.com>
diff --git a/pw_toolchain/generate_toolchain.gni b/pw_toolchain/generate_toolchain.gni
index 30e5b97..f5b0a97 100644
--- a/pw_toolchain/generate_toolchain.gni
+++ b/pw_toolchain/generate_toolchain.gni
@@ -216,7 +216,30 @@
       }
 
       tool("copy") {
-        command = "cp -af {{source}} {{output}}"
+        if (host_os != "win") {
+          # Use a hard link if possible as this is faster. Also, Mac doesn't
+          # preserve timestamps properly with cp -af.
+          fallback_command = string_join(" ",
+                                         [
+                                           "rm -rf",
+                                           "{{output}}",
+                                           "&&",
+                                           "cp -af",
+                                           "{{source}}",
+                                           "{{output}}",
+                                         ])
+          command = string_join(" ",
+                                [
+                                  "ln -f",
+                                  "{{source}}",
+                                  "{{output}}",
+                                  "2>/dev/null",
+                                  "||",
+                                  "($fallback_command)",
+                                ])
+        } else {
+          command = "cp -af {{source}} {{output}}"
+        }
         description = "cp {{source}} {{output}}"
       }