blob: 01cb02523d04463d62aa1ccf684fc830ec1a9bf5 [file] [log] [blame]
Ole Troan5c318c72020-05-05 12:23:47 +02001#!/usr/bin/env python3
2
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02003"""
Ole Troanab9f5732020-12-15 10:19:25 +01004crcchecker is a tool to used to enforce that .api messages do not change.
5API files with a semantic version < 1.0.0 are ignored.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02006"""
Ole Troanab9f5732020-12-15 10:19:25 +01007
Ole Troan5c318c72020-05-05 12:23:47 +02008import sys
9import os
10import json
11import argparse
Ole Troanab9f5732020-12-15 10:19:25 +010012import re
Ole Troan5c318c72020-05-05 12:23:47 +020013from subprocess import run, PIPE, check_output, CalledProcessError
14
Ole Troanab9f5732020-12-15 10:19:25 +010015# pylint: disable=subprocess-run-check
16
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020017ROOTDIR = os.path.dirname(os.path.realpath(__file__)) + "/../.."
18APIGENBIN = f"{ROOTDIR}/src/tools/vppapigen/vppapigen.py"
Ole Troanab9f5732020-12-15 10:19:25 +010019
Ole Troan5c318c72020-05-05 12:23:47 +020020
21def crc_from_apigen(revision, filename):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020022 """Runs vppapigen with crc plugin returning a JSON object with CRCs for
23 all APIs in filename"""
Ole Troan5c318c72020-05-05 12:23:47 +020024 if not revision and not os.path.isfile(filename):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020025 print(f"skipping: {filename}", file=sys.stderr)
Dave Barach592dbd02021-03-11 15:12:29 -050026 # Return <class 'set'> instead of <class 'dict'>
27 return {-1}
Ole Troanab9f5732020-12-15 10:19:25 +010028
Ole Troan5c318c72020-05-05 12:23:47 +020029 if revision:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020030 apigen = (
31 f"{APIGENBIN} --git-revision {revision} --includedir src "
32 f"--input {filename} CRC"
33 )
Ole Troan5c318c72020-05-05 12:23:47 +020034 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020035 apigen = f"{APIGENBIN} --includedir src --input {filename} CRC"
Ole Troanab9f5732020-12-15 10:19:25 +010036 returncode = run(apigen.split(), stdout=PIPE, stderr=PIPE)
37 if returncode.returncode == 2: # No such file
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020038 print(f"skipping: {revision}:{filename} {returncode}", file=sys.stderr)
Ole Troan5c318c72020-05-05 12:23:47 +020039 return {}
Ole Troanab9f5732020-12-15 10:19:25 +010040 if returncode.returncode != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020041 print(
42 f"vppapigen failed for {revision}:{filename} with "
43 "command\n {apigen}\n error: {rv}",
44 returncode.stderr.decode("ascii"),
45 file=sys.stderr,
46 )
Ole Troan5c318c72020-05-05 12:23:47 +020047 sys.exit(-2)
48
Ole Troanab9f5732020-12-15 10:19:25 +010049 return json.loads(returncode.stdout)
Ole Troan5c318c72020-05-05 12:23:47 +020050
51
Ole Troanab9f5732020-12-15 10:19:25 +010052def dict_compare(dict1, dict2):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020053 """Compare two dictionaries returning added, removed, modified
54 and equal entries"""
Ole Troanab9f5732020-12-15 10:19:25 +010055 d1_keys = set(dict1.keys())
56 d2_keys = set(dict2.keys())
Ole Troan5c318c72020-05-05 12:23:47 +020057 intersect_keys = d1_keys.intersection(d2_keys)
58 added = d1_keys - d2_keys
59 removed = d2_keys - d1_keys
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020060 modified = {
61 o: (dict1[o], dict2[o])
62 for o in intersect_keys
63 if dict1[o]["crc"] != dict2[o]["crc"]
64 }
Ole Troanab9f5732020-12-15 10:19:25 +010065 same = set(o for o in intersect_keys if dict1[o] == dict2[o])
Ole Troan5c318c72020-05-05 12:23:47 +020066 return added, removed, modified, same
67
68
69def filelist_from_git_ls():
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020070 """Returns a list of all api files in the git repository"""
Ole Troan5c318c72020-05-05 12:23:47 +020071 filelist = []
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020072 git_ls = "git ls-files *.api"
Ole Troanab9f5732020-12-15 10:19:25 +010073 returncode = run(git_ls.split(), stdout=PIPE, stderr=PIPE)
74 if returncode.returncode != 0:
75 sys.exit(returncode.returncode)
Ole Troan5c318c72020-05-05 12:23:47 +020076
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020077 for line in returncode.stdout.decode("ascii").split("\n"):
Ole Troanab9f5732020-12-15 10:19:25 +010078 if line:
79 filelist.append(line)
Ole Troan5c318c72020-05-05 12:23:47 +020080 return filelist
81
82
83def is_uncommitted_changes():
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020084 """Returns true if there are uncommitted changes in the repo"""
85 git_status = "git status --porcelain -uno"
Ole Troanab9f5732020-12-15 10:19:25 +010086 returncode = run(git_status.split(), stdout=PIPE, stderr=PIPE)
87 if returncode.returncode != 0:
88 sys.exit(returncode.returncode)
Ole Troan5c318c72020-05-05 12:23:47 +020089
Ole Troanab9f5732020-12-15 10:19:25 +010090 if returncode.stdout:
Ole Troan5c318c72020-05-05 12:23:47 +020091 return True
92 return False
93
94
95def filelist_from_git_grep(filename):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020096 """Returns a list of api files that this <filename> api files imports."""
Ole Troan5c318c72020-05-05 12:23:47 +020097 filelist = []
98 try:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020099 returncode = check_output(
100 f'git grep -e "import .*{filename}"' " -- *.api", shell=True
101 )
Ole Troanab9f5732020-12-15 10:19:25 +0100102 except CalledProcessError:
Ole Troan5c318c72020-05-05 12:23:47 +0200103 return []
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200104 for line in returncode.decode("ascii").split("\n"):
Ole Troanab9f5732020-12-15 10:19:25 +0100105 if line:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200106 filename, _ = line.split(":")
Ole Troanab9f5732020-12-15 10:19:25 +0100107 filelist.append(filename)
Ole Troan5c318c72020-05-05 12:23:47 +0200108 return filelist
109
110
Ole Troanab9f5732020-12-15 10:19:25 +0100111def filelist_from_patchset(pattern):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200112 """Returns list of api files in changeset and the list of api
113 files they import."""
Ole Troan5c318c72020-05-05 12:23:47 +0200114 filelist = []
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200115 git_cmd = (
116 "((git diff HEAD~1.. --name-only;git ls-files -m) | "
117 'sort -u | grep "\\.api$")'
118 )
Ole Troanab9f5732020-12-15 10:19:25 +0100119 try:
120 res = check_output(git_cmd, shell=True)
121 except CalledProcessError:
122 return []
Ole Troan5c318c72020-05-05 12:23:47 +0200123
124 # Check for dependencies (imports)
125 imported_files = []
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200126 for line in res.decode("ascii").split("\n"):
Ole Troanab9f5732020-12-15 10:19:25 +0100127 if not line:
128 continue
129 if not re.search(pattern, line):
130 continue
131 filelist.append(line)
132 imported_files.extend(filelist_from_git_grep(os.path.basename(line)))
Ole Troan5c318c72020-05-05 12:23:47 +0200133
134 filelist.extend(imported_files)
135 return set(filelist)
136
Ole Troanab9f5732020-12-15 10:19:25 +0100137
138def is_deprecated(message):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200139 """Given a message, return True if message is deprecated"""
140 if "options" in message:
141 if "deprecated" in message["options"]:
Andrew Yourtchenko6a3d4cc2020-09-22 15:11:51 +0000142 return True
143 # recognize the deprecated format
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200144 if (
145 "status" in message["options"]
146 and message["options"]["status"] == "deprecated"
147 ):
Andrew Yourtchenko6a3d4cc2020-09-22 15:11:51 +0000148 print("WARNING: please use 'option deprecated;'")
149 return True
Ole Troan5c318c72020-05-05 12:23:47 +0200150 return False
151
Ole Troanab9f5732020-12-15 10:19:25 +0100152
153def is_in_progress(message):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200154 """Given a message, return True if message is marked as in_progress"""
155 if "options" in message:
156 if "in_progress" in message["options"]:
Ole Troan5c318c72020-05-05 12:23:47 +0200157 return True
Andrew Yourtchenko6a3d4cc2020-09-22 15:11:51 +0000158 # recognize the deprecated format
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200159 if (
160 "status" in message["options"]
161 and message["options"]["status"] == "in_progress"
162 ):
Andrew Yourtchenko6a3d4cc2020-09-22 15:11:51 +0000163 print("WARNING: please use 'option in_progress;'")
164 return True
165 return False
Ole Troan5c318c72020-05-05 12:23:47 +0200166
Ole Troanab9f5732020-12-15 10:19:25 +0100167
Andrew Yourtchenko62bd50d2020-09-11 17:40:52 +0000168def report(new, old):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200169 """Given a dictionary of new crcs and old crcs, print all the
Ole Troanab9f5732020-12-15 10:19:25 +0100170 added, removed, modified, in-progress, deprecated messages.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200171 Return the number of backwards incompatible changes made."""
Ole Troanab9f5732020-12-15 10:19:25 +0100172
173 # pylint: disable=too-many-branches
174
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200175 new.pop("_version", None)
176 old.pop("_version", None)
Ole Troanab9f5732020-12-15 10:19:25 +0100177 added, removed, modified, _ = dict_compare(new, old)
Ole Troan5c318c72020-05-05 12:23:47 +0200178 backwards_incompatible = 0
Ole Troanab9f5732020-12-15 10:19:25 +0100179
Andrew Yourtchenko8b0cd692020-09-16 09:48:59 +0000180 # print the full list of in-progress messages
181 # they should eventually either disappear of become supported
182 for k in new.keys():
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200183 newversion = int(new[k]["version"])
Ole Troanab9f5732020-12-15 10:19:25 +0100184 if newversion == 0 or is_in_progress(new[k]):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200185 print(f"in-progress: {k}")
Ole Troan5c318c72020-05-05 12:23:47 +0200186 for k in added:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200187 print(f"added: {k}")
Ole Troan5c318c72020-05-05 12:23:47 +0200188 for k in removed:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200189 oldversion = int(old[k]["version"])
190 if oldversion > 0 and not is_deprecated(old[k]) and not is_in_progress(old[k]):
Ole Troan5c318c72020-05-05 12:23:47 +0200191 backwards_incompatible += 1
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200192 print(f"removed: ** {k}")
Ole Troan5c318c72020-05-05 12:23:47 +0200193 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200194 print(f"removed: {k}")
Ole Troan5c318c72020-05-05 12:23:47 +0200195 for k in modified.keys():
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200196 oldversion = int(old[k]["version"])
197 newversion = int(new[k]["version"])
Ole Troanab9f5732020-12-15 10:19:25 +0100198 if oldversion > 0 and not is_in_progress(old[k]):
Ole Troan5c318c72020-05-05 12:23:47 +0200199 backwards_incompatible += 1
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200200 print(f"modified: ** {k}")
Ole Troan5c318c72020-05-05 12:23:47 +0200201 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200202 print(f"modified: {k}")
Andrew Yourtchenko62bd50d2020-09-11 17:40:52 +0000203
204 # check which messages are still there but were marked for deprecation
205 for k in new.keys():
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200206 newversion = int(new[k]["version"])
Ole Troanab9f5732020-12-15 10:19:25 +0100207 if newversion > 0 and is_deprecated(new[k]):
Andrew Yourtchenko62bd50d2020-09-11 17:40:52 +0000208 if k in old:
Ole Troanab9f5732020-12-15 10:19:25 +0100209 if not is_deprecated(old[k]):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200210 print(f"deprecated: {k}")
Andrew Yourtchenko62bd50d2020-09-11 17:40:52 +0000211 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200212 print(f"added+deprecated: {k}")
Andrew Yourtchenko62bd50d2020-09-11 17:40:52 +0000213
Ole Troan5c318c72020-05-05 12:23:47 +0200214 return backwards_incompatible
215
216
Ole Troanab9f5732020-12-15 10:19:25 +0100217def check_patchset():
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200218 """Compare the changes to API messages in this changeset.
Ole Troanab9f5732020-12-15 10:19:25 +0100219 Ignores API files with version < 1.0.0.
220 Only considers API files located under the src directory in the repo.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200221 """
222 files = filelist_from_patchset("^src/")
223 revision = "HEAD~1"
Ole Troanab9f5732020-12-15 10:19:25 +0100224
225 oldcrcs = {}
226 newcrcs = {}
227 for filename in files:
228 # Ignore files that have version < 1.0.0
229 _ = crc_from_apigen(None, filename)
Dave Barach592dbd02021-03-11 15:12:29 -0500230 # Ignore removed files
231 if isinstance(_, set) == 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200232 if isinstance(_, set) == 0 and _["_version"]["major"] == "0":
Dave Barach592dbd02021-03-11 15:12:29 -0500233 continue
234 newcrcs.update(_)
Ole Troanab9f5732020-12-15 10:19:25 +0100235
Ole Troanab9f5732020-12-15 10:19:25 +0100236 oldcrcs.update(crc_from_apigen(revision, filename))
237
238 backwards_incompatible = report(newcrcs, oldcrcs)
239 if backwards_incompatible:
240 # alert on changing production API
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200241 print(
242 "crcchecker: Changing production APIs in an incompatible way",
243 file=sys.stderr,
244 )
Ole Troanab9f5732020-12-15 10:19:25 +0100245 sys.exit(-1)
246 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200247 print("*" * 67)
248 print("* VPP CHECKAPI SUCCESSFULLY COMPLETED")
249 print("*" * 67)
Ole Troanab9f5732020-12-15 10:19:25 +0100250
251
Ole Troan5c318c72020-05-05 12:23:47 +0200252def main():
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200253 """Main entry point."""
254 parser = argparse.ArgumentParser(description="VPP CRC checker.")
255 parser.add_argument("--git-revision", help="Git revision to compare against")
256 parser.add_argument(
257 "--dump-manifest", action="store_true", help="Dump CRC for all messages"
258 )
259 parser.add_argument(
260 "--check-patchset",
261 action="store_true",
262 help="Check patchset for backwards incompatbile changes",
263 )
264 parser.add_argument("files", nargs="*")
265 parser.add_argument("--diff", help="Files to compare (on filesystem)", nargs=2)
Ole Troan5c318c72020-05-05 12:23:47 +0200266
267 args = parser.parse_args()
268
269 if args.diff and args.files:
270 parser.print_help()
271 sys.exit(-1)
272
273 # Diff two files
274 if args.diff:
275 oldcrcs = crc_from_apigen(None, args.diff[0])
276 newcrcs = crc_from_apigen(None, args.diff[1])
Andrew Yourtchenko62bd50d2020-09-11 17:40:52 +0000277 backwards_incompatible = report(newcrcs, oldcrcs)
Ole Troan5c318c72020-05-05 12:23:47 +0200278 sys.exit(0)
279
280 # Dump CRC for messages in given files / revision
281 if args.dump_manifest:
282 files = args.files if args.files else filelist_from_git_ls()
283 crcs = {}
Ole Troanab9f5732020-12-15 10:19:25 +0100284 for filename in files:
285 crcs.update(crc_from_apigen(args.git_revision, filename))
286 for k, value in crcs.items():
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200287 print(f"{k}: {value}")
Ole Troan5c318c72020-05-05 12:23:47 +0200288 sys.exit(0)
289
290 # Find changes between current patchset and given revision (previous)
291 if args.check_patchset:
292 if args.git_revision:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200293 print("Argument git-revision ignored", file=sys.stderr)
Ole Troan5c318c72020-05-05 12:23:47 +0200294 # Check there are no uncomitted changes
295 if is_uncommitted_changes():
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200296 print("Please stash or commit changes in workspace", file=sys.stderr)
Ole Troan5c318c72020-05-05 12:23:47 +0200297 sys.exit(-1)
Ole Troanab9f5732020-12-15 10:19:25 +0100298 check_patchset()
299 sys.exit(0)
300
301 # Find changes between current workspace and revision
302 # Find changes between a given file and a revision
303 files = args.files if args.files else filelist_from_git_ls()
Ole Troan5c318c72020-05-05 12:23:47 +0200304
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200305 revision = args.git_revision if args.git_revision else "HEAD~1"
Ole Troan5c318c72020-05-05 12:23:47 +0200306
307 oldcrcs = {}
308 newcrcs = {}
Ole Troanab9f5732020-12-15 10:19:25 +0100309 for file in files:
310 newcrcs.update(crc_from_apigen(None, file))
311 oldcrcs.update(crc_from_apigen(revision, file))
Ole Troan5c318c72020-05-05 12:23:47 +0200312
Andrew Yourtchenko62bd50d2020-09-11 17:40:52 +0000313 backwards_incompatible = report(newcrcs, oldcrcs)
Ole Troan5c318c72020-05-05 12:23:47 +0200314
315 if args.check_patchset:
316 if backwards_incompatible:
317 # alert on changing production API
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200318 print(
319 "crcchecker: Changing production APIs in an incompatible way",
320 file=sys.stderr,
321 )
Ole Troan5c318c72020-05-05 12:23:47 +0200322 sys.exit(-1)
323 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200324 print("*" * 67)
325 print("* VPP CHECKAPI SUCCESSFULLY COMPLETED")
326 print("*" * 67)
Ole Troan5c318c72020-05-05 12:23:47 +0200327
Ole Troanab9f5732020-12-15 10:19:25 +0100328
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200329if __name__ == "__main__":
Ole Troan5c318c72020-05-05 12:23:47 +0200330 main()