Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. error: The fun
(filename, clean_lines, error)
| 2361 | |
| 2362 | |
| 2363 | def CheckForHeaderGuard(filename, clean_lines, error): |
| 2364 | """Checks that the file contains a header guard. |
| 2365 | |
| 2366 | Logs an error if no #ifndef header guard is present. For other |
| 2367 | headers, checks that the full pathname is used. |
| 2368 | |
| 2369 | Args: |
| 2370 | filename: The name of the C++ header file. |
| 2371 | clean_lines: A CleansedLines instance containing the file. |
| 2372 | error: The function to call with any errors found. |
| 2373 | """ |
| 2374 | |
| 2375 | # Don't check for header guards if there are error suppression |
| 2376 | # comments somewhere in this file. |
| 2377 | # |
| 2378 | # Because this is silencing a warning for a nonexistent line, we |
| 2379 | # only support the very specific NOLINT(build/header_guard) syntax, |
| 2380 | # and not the general NOLINT or NOLINT(*) syntax. |
| 2381 | raw_lines = clean_lines.lines_without_raw_strings |
| 2382 | for i in raw_lines: |
| 2383 | if Search(r'//\s*NOLINT\(build/header_guard\)', i): |
| 2384 | return |
| 2385 | |
| 2386 | # Allow pragma once instead of header guards |
| 2387 | for i in raw_lines: |
| 2388 | if Search(r'^\s*#pragma\s+once', i): |
| 2389 | return |
| 2390 | |
| 2391 | cppvar = GetHeaderGuardCPPVariable(filename) |
| 2392 | |
| 2393 | ifndef = '' |
| 2394 | ifndef_linenum = 0 |
| 2395 | define = '' |
| 2396 | endif = '' |
| 2397 | endif_linenum = 0 |
| 2398 | for linenum, line in enumerate(raw_lines): |
| 2399 | linesplit = line.split() |
| 2400 | if len(linesplit) >= 2: |
| 2401 | # find the first occurrence of #ifndef and #define, save arg |
| 2402 | if not ifndef and linesplit[0] == '#ifndef': |
| 2403 | # set ifndef to the header guard presented on the #ifndef line. |
| 2404 | ifndef = linesplit[1] |
| 2405 | ifndef_linenum = linenum |
| 2406 | if not define and linesplit[0] == '#define': |
| 2407 | define = linesplit[1] |
| 2408 | # find the last occurrence of #endif, save entire line |
| 2409 | if line.startswith('#endif'): |
| 2410 | endif = line |
| 2411 | endif_linenum = linenum |
| 2412 | |
| 2413 | if not ifndef or not define or ifndef != define: |
| 2414 | error(filename, 0, 'build/header_guard', 5, |
| 2415 | 'No #ifndef header guard found, suggested CPP variable is: %s' % |
| 2416 | cppvar) |
| 2417 | return |
| 2418 | |
| 2419 | # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ |
| 2420 | # for backward compatibility. |
no test coverage detected