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