scripts: crosfw: Reconfigure automatically if needed

If anything has changed in Kconfig or the defconfig files, force a
reconfigure. This avoid build errors or building with the wrong config.

BUG=b:268384689
TEST=crosfw sandbox
Change a Kconfig and try again, see that it says it is reconfiguring
Do the same with configs/sandbox_spl_defconfig

Change-Id: I28590ab318a6e1090e93d77c09a06f5b9089ae7c
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/chromite/+/4248403
Tested-by: Simon Glass <sjg@chromium.org>
Reviewed-by: Mike Frysinger <vapier@chromium.org>
Commit-Queue: Simon Glass <sjg@chromium.org>
diff --git a/scripts/crosfw.py b/scripts/crosfw.py
index c82c942..6511621 100644
--- a/scripts/crosfw.py
+++ b/scripts/crosfw.py
@@ -99,6 +99,7 @@
 import logging
 import multiprocessing
 import os
+from pathlib import Path
 import re
 import subprocess
 import sys
@@ -457,6 +458,32 @@
     return base
 
 
+def CheckConfigChange() -> bool:
+    """See if we need to reconfigure due to config files changing
+
+    Checks if any defconfig or Kconfig file has changed in the source tree
+    since the last time U-Boot was configured for this build. For simplicity,
+    any defconfig change will trigger this, not just one for the board being
+    built, since the cost of a reconfigure is fairly small.
+
+    Returns:
+        True if any config file has changed since U-Boot was last configured
+    """
+    fname = os.path.join(outdir, ".config")
+    ref_time = os.path.getctime(fname)
+    for p in Path.cwd().glob("configs/*"):
+        if p.stat().st_ctime > ref_time:
+            logging.warning("config/ dir has changed - adding -f")
+            return True
+
+    for p in Path.cwd().glob("**/Kconfig*"):
+        if p.stat().st_ctime > ref_time:
+            logging.warning("Kconfig file(s) changed - adding -f")
+            return True
+
+    return False
+
+
 def RunBuild(options, base, target, queue):
     """Run the U-Boot build.
 
@@ -473,6 +500,9 @@
         # Ignore any error from this, some older U-Boots fail on this.
         cros_build_lib.run(base + ["distclean"], capture_output=True, **kwargs)
 
+    if not options.force_reconfig:
+        options.force_reconfig = CheckConfigChange()
+
     # Reconfigure U-Boot.
     if options.force_reconfig:
         if os.path.exists("tools/genboardscfg.py"):