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