Add denpendencies to AppSearch CmakeLists.txt commands. To allow it re-make when file is updated.

Bug: 170611579
Test: Manually: 1: checkout on an old branch
2. add denpendencies to cmake (changing cmakelists will invalidate a lot of caches)
3. build and generate cxx files
4. patch the head branch with the latest version
5. build again w/o any error.

Change-Id: Ie47826cb74a84160ef0646abbfd77869801f2c35
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 0830783..e520663 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -47,6 +47,27 @@
 set(ICU_TARGET_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/icu-target")
 add_subdirectory(${ICU_SOURCE_DIR} ${ICU_TARGET_BINARY_DIR})
 
+# Creates a file deps_name.cmake to save dependencies in it. This file should be
+# treated as part of CMakeLists.txt. This file should stay in .gitignore
+# TODO: When supporting cmake v3.12 or higher, use CONFIGURE_DEPENDS in the glob
+# and remove this section.
+function(update_deps_file deps_name deps)
+    set(DEPS_FILE ${deps_name}.cmake.gen)
+    set(CONTENT "# generated by make process.\nset(Tmp_${deps_name} ${deps})\n")
+    set(EXISTING_CONTENT "")
+    if(EXISTS ${DEPS_FILE})
+        file(READ ${DEPS_FILE} EXISTING_CONTENT)
+    endif()
+    # Compare the new contents with the existing file, if it exists and is the same
+    # we don't want to trigger a make by changing its timestamp.
+    if(NOT EXISTING_CONTENT STREQUAL CONTENT)
+        file(WRITE ${DEPS_FILE} ${CONTENT})
+    endif()
+    # Include the file so it's tracked as a generation dependency we don't
+    # need the content.
+    include(${DEPS_FILE})
+endfunction(update_deps_file)
+
 # Glob Icing proto sources. Results look like this: icing/proto/document.proto
 file(
     GLOB_RECURSE
@@ -55,7 +76,11 @@
     "*.proto")
 message(STATUS "Icing_PROTO_FILES=${Icing_PROTO_FILES}")
 
+update_deps_file("IcingProtoFiles" "${Icing_PROTO_FILES}")
+
 # Run protoc on Icing_PROTO_FILES to generate pb.cc and pb.h files
+# The DEPENDS section of add_custom_command could trigger a remake if any proto
+# source file has been updated.
 file(MAKE_DIRECTORY ${Icing_PROTO_GEN_DIR})
 foreach(FILE ${Icing_PROTO_FILES})
     # Find the name of the proto file without the .proto extension
@@ -71,7 +96,7 @@
           --cpp_out ${Icing_PROTO_GEN_DIR}
           ${FILE}
         WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
-        DEPENDS ${Protobuf_PROTOC_PATH}
+        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/proto/${FILE}
     )
 endforeach()
 message(STATUS "Icing_PROTO_SOURCES=${Icing_PROTO_SOURCES}")
@@ -89,6 +114,9 @@
     # Glob expressions
     icing/*.cc icing/*.h
 )
+
+update_deps_file("IcingCCSources" "${Icing_CC_SOURCES}")
+
 # Exclude the same types of files as Android.bp. See the comments there.
 list(FILTER Icing_CC_SOURCES EXCLUDE REGEX "^icing/.*[^a-zA-Z0-9]test[^a-zA-Z0-9].*$")
 list(FILTER Icing_CC_SOURCES EXCLUDE REGEX "^icing/.*_benchmark\.cc$")