28 """Shared code for validating generated_file_staleness_test() rules.
30 This code is used by test scripts generated from
31 generated_file_staleness_test() rules.
34 from __future__
import absolute_import
35 from __future__
import print_function
39 from shutil
import copyfile
43 """Represents a single (target, generated) file pair."""
51 """Represents the configuration for a single staleness test target."""
55 file_list = list(file_list)
67 """Generates the list of file pairs.
70 config: a Config object representing this target's config.
73 A list of _FilePair objects.
78 has_bazel_genfiles = os.path.exists(
"bazel-bin")
80 for filename
in config.file_list:
81 target = os.path.join(config.package_name, filename)
82 generated = os.path.join(config.package_name, config.pattern % filename)
83 if has_bazel_genfiles:
84 generated = os.path.join(
"bazel-bin", generated)
88 if not os.path.isfile(generated):
89 print(
"Generated file '%s' does not exist." % generated)
90 print(
"Please run this command to generate it:")
91 print(
" bazel build %s:%s" % (config.package_name, config.target_name))
99 """Generates lists of missing and stale files.
102 file_pairs: a list of _FilePair objects.
105 missing_files: a list of _FilePair objects representing missing files.
106 These target files do not exist at all.
107 stale_files: a list of _FilePair objects representing stale files.
108 These target files exist but have stale contents.
114 for pair
in file_pairs:
115 if not os.path.isfile(pair.target):
116 missing_files.append(pair)
119 with open(pair.generated)
as g,
open(pair.target)
as t:
120 if g.read() != t.read():
121 stale_files.append(pair)
123 return missing_files, stale_files
127 """Copies all generated files to the corresponding target file.
129 The target files must be writable already.
132 file_pairs: a list of _FilePair objects that we want to copy.
135 for pair
in file_pairs:
136 target_dir = os.path.dirname(pair.target)
137 if not os.path.isdir(target_dir):
138 os.makedirs(target_dir)
139 copyfile(pair.generated, pair.target)
143 """Implements the --fix option: overwrites missing or out-of-date files.
146 config: the Config object for this test.
156 """Checks whether each target file matches the corresponding generated file.
159 config: the Config object for this test.
162 None if everything matches, otherwise a string error message.
170 for pair
in missing_files:
171 diff_errors.append(
"File %s does not exist" % pair.target)
174 for pair
in stale_files:
175 diff_errors.append(
"File %s is out of date" % pair.target)
178 error_msg =
"Files out of date!\n\n"
179 error_msg +=
"To fix run THIS command:\n"
180 error_msg +=
" bazel-bin/%s/%s --fix\n\n" % (config.package_name,
182 error_msg +=
"Errors:\n"
183 error_msg +=
" " +
"\n ".join(diff_errors)