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)
| 1888 | |
| 1889 | |
| 1890 | def CheckForHeaderGuard(filename, clean_lines, error): |
| 1891 | """Checks that the file contains a header guard. |
| 1892 | |
| 1893 | Logs an error if no #ifndef header guard is present. For other |
| 1894 | headers, checks that the full pathname is used. |
| 1895 | |
| 1896 | Args: |
| 1897 | filename: The name of the C++ header file. |
| 1898 | clean_lines: A CleansedLines instance containing the file. |
| 1899 | error: The function to call with any errors found. |
| 1900 | """ |
| 1901 | |
| 1902 | # Don't check for header guards if there are error suppression |
| 1903 | # comments somewhere in this file. |
| 1904 | # |
| 1905 | # Because this is silencing a warning for a nonexistent line, we |
| 1906 | # only support the very specific NOLINT(build/header_guard) syntax, |
| 1907 | # and not the general NOLINT or NOLINT(*) syntax. |
| 1908 | raw_lines = clean_lines.lines_without_raw_strings |
| 1909 | for i in raw_lines: |
| 1910 | if Search(r'//\s*NOLINT\(build/header_guard\)', i): |
| 1911 | return |
| 1912 | |
| 1913 | cppvar = GetHeaderGuardCPPVariable(filename) |
| 1914 | |
| 1915 | ifndef = '' |
| 1916 | ifndef_linenum = 0 |
| 1917 | define = '' |
| 1918 | endif = '' |
| 1919 | endif_linenum = 0 |
| 1920 | for linenum, line in enumerate(raw_lines): |
| 1921 | linesplit = line.split() |
| 1922 | if len(linesplit) >= 2: |
| 1923 | # find the first occurrence of #ifndef and #define, save arg |
| 1924 | if not ifndef and linesplit[0] == '#ifndef': |
| 1925 | # set ifndef to the header guard presented on the #ifndef line. |
| 1926 | ifndef = linesplit[1] |
| 1927 | ifndef_linenum = linenum |
| 1928 | if not define and linesplit[0] == '#define': |
| 1929 | define = linesplit[1] |
| 1930 | # find the last occurrence of #endif, save entire line |
| 1931 | if line.startswith('#endif'): |
| 1932 | endif = line |
| 1933 | endif_linenum = linenum |
| 1934 | |
| 1935 | if not ifndef or not define or ifndef != define: |
| 1936 | error(filename, 0, 'build/header_guard', 5, |
| 1937 | 'No #ifndef header guard found, suggested CPP variable is: %s' % |
| 1938 | cppvar) |
| 1939 | return |
| 1940 | |
| 1941 | # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ |
| 1942 | # for backward compatibility. |
| 1943 | if ifndef != cppvar: |
| 1944 | error_level = 0 |
| 1945 | if ifndef != cppvar + '_': |
| 1946 | error_level = 5 |
| 1947 |
no test coverage detected