VirtualBox

source: vbox/trunk/doc/manual/add_file_to_id_only_references.py@ 107518

Last change on this file since 107518 was 107409, checked in by vboxsync, 4 weeks ago

Docs: ​bugref:10705. bugref:10829. Reverting some unintended changes from r166433.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 6.1 KB
Line 
1# -*- coding: utf-8 -*-
2# $Id: add_file_to_id_only_references.py 107409 2025-01-02 15:42:02Z vboxsync $
3
4"""
5Makes id-only reference in the given file into dita-compliant file#id
6references, using the mapping database generated by build_id_to_file_mapping.py.
7"""
8
9__copyright__ = \
10"""
11Copyright (C) 2023-2024 Oracle and/or its affiliates.
12
13This file is part of VirtualBox base platform packages, as
14available from https://www.virtualbox.org.
15
16This program is free software; you can redistribute it and/or
17modify it under the terms of the GNU General Public License
18as published by the Free Software Foundation, in version 3 of the
19License.
20
21This program is distributed in the hope that it will be useful, but
22WITHOUT ANY WARRANTY; without even the implied warranty of
23MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24General Public License for more details.
25
26You should have received a copy of the GNU General Public License
27along with this program; if not, see <https://www.gnu.org/licenses>.
28
29SPDX-License-Identifier: GPL-3.0-only
30"""
31__version__ = "$Revision: 107409 $"
32
33# Standard python imports.
34import glob;
35import os;
36import re;
37import sys;
38
39
40g_oReHref = re.compile(r'\bhref=("[^">#./]+"|\'[^\'>#./]+\')');
41
42def modifyDitaFile(dIdToFile, sContent):
43 """
44 Modifies the href attributes in this file.
45 """
46 current_file_is_refentry = False
47 if any(current_file_name.lower() in s.lower() for s in refentry_files):
48 current_file_is_refentry = True
49 sModified = '';
50 offPrev = 0;
51 for oMatch in g_oReHref.finditer(sContent):
52 sId = oMatch.group(1)[1:-1];
53 if sId in dIdToFile:
54 reference_is_refentry = False
55 if any(os.path.splitext(dIdToFile[sId])[0].lower() in s.lower() for s in refentry_files):
56 reference_is_refentry = True
57 if current_file_is_refentry and not reference_is_refentry:
58 sModified += sContent[offPrev : oMatch.start(1)] + '"../topics/' + dIdToFile[sId] + '#' + sId + '"';
59 else:
60 sModified += sContent[offPrev : oMatch.start(1)] + '"' + dIdToFile[sId] + '#' + sId + '"';
61 offPrev = oMatch.end(1);
62 if offPrev < len(sContent):
63 sModified += sContent[offPrev:];
64 return sModified;
65
66def info(sMessage):
67 """ Info message. """
68 print('add_file_to_id_only_references.py: info: %s' % sMessage);
69 return 1;
70
71def error(sMessage):
72 """ Reports an error. """
73 print('add_file_to_id_only_references.py: error: %s' % sMessage, file = sys.stderr);
74 return 1;
75
76def syntax(sMessage):
77 """ Reports a syntax error. """
78 print('add_file_to_id_only_references.py: syntax error: %s' % sMessage, file = sys.stderr);
79 return 2;
80
81def usage():
82 """ Reports usage. """
83 print('usage: add_file_to_id_only_references.py [--verbose|--quiet] --mapping-file <map.db> file1.dita [file2.dita [...]]');
84 return 0;
85
86def main(asArgs):
87 """
88 C-like main function.
89 """
90 #
91 # Process arguments.
92 #
93 dIdToFile = None;
94 fEndOfArgs = False;
95 fVerbose = False;
96 iArg = 1;
97 while iArg < len(asArgs):
98 sArg = asArgs[iArg];
99 if sArg[0] == '-' and not fEndOfArgs:
100 # Options.
101 if sArg == '--':
102 fEndOfArgs = True;
103 elif sArg in ('--help', '-h', '-?'):
104 return usage();
105 elif sArg in ('--version', '-V' ):
106 print(__version__[__version__.find(':') + 2:-2]);
107 elif sArg in ('--quiet', '-q' ):
108 fVerbose = False;
109 elif sArg in ('--verbose', '-v' ):
110 fVerbose = True;
111 elif sArg in ('--refentry_file_list', '-f' ):
112 iArg += 1;
113 if iArg >= len(asArgs):
114 return syntax('Expected a list of refentry files following "--refentry_file_list"!');
115 global refentry_files
116 refentry_files = asArgs[iArg].split(' ')
117 elif sArg in ('--mapping-file', '-m'):
118 iArg += 1;
119 if iArg >= len(asArgs):
120 return syntax('Expected filename following "--mapping-file"!');
121 # Load the database file.
122 sArg = asArgs[iArg];
123 try:
124 with open(sArg, 'r', encoding = 'utf-8') as oFile:
125 dIdToFile = {};
126 for sLine in oFile:
127 sId, sFile = sLine.split('=');
128 dIdToFile[sId.strip()] = sFile.strip();
129 except Exception as oXcpt: # pylint: disable=broad-exception-caught
130 return error('Failed to open and parse "%s": %s' % (sArg, oXcpt,));
131 if fVerbose:
132 info('Loaded %s IDs from "%s"' % (len(dIdToFile), sArg));
133 else:
134 return syntax('Unknown option: %s' % (sArg,));
135 else:
136 # File to modify.
137 if dIdToFile is None:
138 return syntax('A mapping database must be given before any other files!');
139
140 try:
141 with open(sArg, 'r', encoding = 'utf-8') as oFile:
142 sContent = oFile.read();
143 except Exception as oXcpt: # pylint: disable=broad-exception-caught
144 return error('Failed to open and read "%s": %s' % (sArg, oXcpt,));
145 global current_file_name
146 current_file_name = os.path.splitext(os.path.basename(sArg))[0]
147 prefix = "flat-"
148 if current_file_name.startswith(prefix):
149 current_file_name = current_file_name[len(prefix):]
150 sModified = modifyDitaFile(dIdToFile, sContent);
151 if sModified != sContent:
152 if fVerbose:
153 info('Writing out modified "%s"...' % (sArg,));
154 try:
155 with open(sArg, 'w', encoding = 'utf-8') as oFile:
156 oFile.write(sModified);
157 except Exception as oXcpt: # pylint: disable=broad-exception-caught
158 return error('Failed to open and write back "%s": %s' % (sArg, oXcpt,));
159 elif fVerbose:
160 info('No changes to "%s"...' % (sArg,));
161
162 iArg += 1;
163 return 0;
164
165if __name__ == "__main__":
166 sys.exit(main(sys.argv));
167
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette