Copybara | 854996b | 2021-09-07 19:36:02 +0000 | [diff] [blame^] | 1 | # Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style |
| 3 | # license that can be found in the LICENSE file or at |
| 4 | # https://developers.google.com/open-source/licenses/bsd |
| 5 | |
| 6 | """Helper functions for source code syntax highlighting.""" |
| 7 | from __future__ import print_function |
| 8 | from __future__ import division |
| 9 | from __future__ import absolute_import |
| 10 | |
| 11 | import ezt |
| 12 | |
| 13 | from framework import framework_constants |
| 14 | |
| 15 | |
| 16 | # We only attempt to do client-side syntax highlighting on files that we |
| 17 | # expect to be source code in languages that we support, and that are |
| 18 | # reasonably sized. |
| 19 | MAX_PRETTIFY_LINES = 3000 |
| 20 | |
| 21 | |
| 22 | def PrepareSourceLinesForHighlighting(file_contents): |
| 23 | """Parse a file into lines for highlighting. |
| 24 | |
| 25 | Args: |
| 26 | file_contents: string contents of the source code file. |
| 27 | |
| 28 | Returns: |
| 29 | A list of _SourceLine objects, one for each line in the source file. |
| 30 | """ |
| 31 | return [_SourceLine(num + 1, line) for num, line |
| 32 | in enumerate(file_contents.splitlines())] |
| 33 | |
| 34 | |
| 35 | class _SourceLine(object): |
| 36 | """Convenience class to represent one line of the source code display. |
| 37 | |
| 38 | Attributes: |
| 39 | num: The line's location in the source file. |
| 40 | line: String source code line to display. |
| 41 | """ |
| 42 | |
| 43 | def __init__(self, num, line): |
| 44 | self.num = num |
| 45 | self.line = line |
| 46 | |
| 47 | def __repr__(self): |
| 48 | return '%d: %s' % (self.num, self.line) |
| 49 | |
| 50 | |
| 51 | def BuildPrettifyData(num_lines, path): |
| 52 | """Return page data to help configure google-code-prettify. |
| 53 | |
| 54 | Args: |
| 55 | num_lines: int number of lines of source code in the file. |
| 56 | path: string path to the file, or just the filename. |
| 57 | |
| 58 | Returns: |
| 59 | Dictionary that can be passed to EZT to render a page. |
| 60 | """ |
| 61 | reasonable_size = num_lines < MAX_PRETTIFY_LINES |
| 62 | |
| 63 | filename_lower = path[path.rfind('/') + 1:].lower() |
| 64 | ext = filename_lower[filename_lower.rfind('.') + 1:] |
| 65 | |
| 66 | # Note that '' might be a valid entry in these maps. |
| 67 | prettify_class = framework_constants.PRETTIFY_CLASS_MAP.get(ext) |
| 68 | if prettify_class is None: |
| 69 | prettify_class = framework_constants.PRETTIFY_FILENAME_CLASS_MAP.get( |
| 70 | filename_lower) |
| 71 | supported_lang = prettify_class is not None |
| 72 | |
| 73 | return { |
| 74 | 'should_prettify': ezt.boolean(supported_lang and reasonable_size), |
| 75 | 'prettify_class': prettify_class, |
| 76 | } |