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