eric5-api.py

changeset 15
f6ccc31d6e72
child 18
3b1f5d872fd7
equal deleted inserted replaced
14:092aa8fafa4e 15:f6ccc31d6e72
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2003 - 2010 Detlev Offenbach <detlev@die-offenbachs.de>
5 #
6
7 """
8 Eric4 API Generator
9
10 This is the main Python script of the API generator. It is
11 this script that gets called via the API generation interface.
12 This script can be used via the commandline as well.
13 """
14
15 import glob
16 import os
17 import sys
18 import fnmatch
19
20 import Utilities.ModuleParser
21 from DocumentationTools.APIGenerator import APIGenerator
22 from UI.Info import Version
23 import Utilities
24 import Preferences
25 import DocumentationTools
26
27 def usage():
28 """
29 Function to print some usage information.
30
31 It prints a reference of all commandline parameters that may
32 be used and ends the application.
33 """
34 print("eric5-api")
35 print()
36 print("Copyright (c) 2004 - 2010 Detlev Offenbach <detlev@die-offenbachs.de>.")
37 print()
38 print("Usage:")
39 print()
40 print(" eric5-api [options] files...")
41 print()
42 print("where files can be either python modules, package")
43 print("directories or ordinary directories.")
44 print()
45 print("Options:")
46 print()
47 print(" -b name or --base name")
48 print(" Use the given name as the name of the base package.")
49 print(" -h or --help")
50 print(" Show this help and exit.")
51 print(" -o filename or --output=filename")
52 print(" Write the API information to the named file. A '%L' placeholder")
53 print(" is replaced by the language of the API file (see --language).")
54 print(" --oldstyle")
55 print(" Generate API files for QScintilla prior to 1.7.")
56 print(" -p or --private")
57 print(" Include private methods and functions.")
58 print(" -R, -r or --recursive")
59 print(" Perform a recursive search for source files.")
60 print(" -t ext or --extension=ext")
61 print(" Add the given extension to the list of file extensions.")
62 print(" This option may be given multiple times.")
63 print(" -V or --version")
64 print(" Show version information and exit.")
65 print(" -x directory or --exclude=directory")
66 print(" Specify a directory basename to be excluded.")
67 print(" This option may be repeated multiple times.")
68 print(" --exclude-file=pattern")
69 print(" Specify a filename pattern of files to be excluded.")
70 print(" This option may be repeated multiple times.")
71 print(" -l language or --language=language")
72 print(" Generate an API file for the given programming language.")
73 print(" Supported programming languages are:")
74 for lang in sorted(DocumentationTools.supportedExtensionsDictForApis.keys()):
75 print(" * %s" % lang)
76 print(" The default is 'Python'.")
77 print(" This option may be repeated multiple times.")
78 sys.exit(1)
79
80 def version():
81 """
82 Function to show the version information.
83 """
84 print("""eric5-api %s
85
86 Eric4 API generator.
87
88 Copyright (c) 2004 - 2010 Detlev Offenbach <detlev@die-offenbachs.de>
89 This is free software; see the LICENSE.GPL3 for copying conditions.
90 There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
91 PARTICULAR PURPOSE.""" % Version)
92 sys.exit(1)
93
94 def main():
95 """
96 Main entry point into the application.
97 """
98 global supportedExtensions
99
100 import getopt
101
102 try:
103 opts, args = getopt.getopt(sys.argv[1:], "b:hl:o:pRrt:Vx:",
104 ["base=", "exclude=", "exclude-file=", "extension=", "help",
105 "language=", "oldstyle", "output=", "private", "recursive",
106 "version", ])
107 except getopt.error:
108 usage()
109
110 excludeDirs = ["CVS", ".svn", "_svn", ".ropeproject", "_ropeproject",
111 ".eric5project", "_eric5project", "dist", "build", "doc", "docs"]
112 excludePatterns = []
113 outputFileName = ""
114 recursive = False
115 newStyle = True
116 basePackage = ""
117 includePrivate = False
118 progLanguages = []
119 extensions = []
120
121 # Set the applications string encoding
122 try:
123 sys.setappdefaultencoding(str(Preferences.getSystem("StringEncoding")))
124 except AttributeError:
125 pass
126
127 for k, v in opts:
128 if k in ["-o", "--output"]:
129 outputFileName = v
130 elif k in ["-R", "-r", "--recursive"]:
131 recursive = True
132 elif k in ["-x", "--exclude"]:
133 excludeDirs.append(v)
134 elif k == "--exclude-file":
135 excludePatterns.append(v)
136 elif k in ["-h", "--help"]:
137 usage()
138 elif k in ["-V", "--version"]:
139 version()
140 elif k in ["-t", "--extension"]:
141 if not v.startswith("."):
142 v = ".%s" % v
143 extensions.append(v)
144 elif k in ["--oldstyle"]:
145 newStyle = False
146 elif k in ["-b", "--base"]:
147 basePackage = v
148 elif k in ["-p", "--private"]:
149 includePrivate = True
150 elif k in ["-l", "--language"]:
151 if v not in progLanguages:
152 if v not in list(DocumentationTools.supportedExtensionsDictForApis.keys()):
153 sys.stderr.write("Wrong language given: %s. Aborting\n" % v)
154 sys.exit(1)
155 else:
156 progLanguages.append(v)
157
158 if not args:
159 usage()
160
161 if outputFileName == "":
162 sys.stderr.write("No output file given. Aborting\n")
163 sys.exit(1)
164
165 if len(progLanguages) == 0:
166 progLanguages = ["Python"]
167
168 for progLanguage in sorted(progLanguages):
169 basename = ""
170 apis = []
171
172 supportedExtensions = \
173 DocumentationTools.supportedExtensionsDictForApis[progLanguage]
174 supportedExtensions.extend(extensions)
175 if "%L" in outputFileName:
176 outputFile = outputFileName.replace("%L", progLanguage)
177 else:
178 if len(progLanguages) == 1:
179 outputFile = outputFileName
180 else:
181 root, ext = os.path.splitext(outputFileName)
182 outputFile = "%s-%s%s" % (root, progLanguage.lower(), ext)
183
184 for arg in args:
185 if os.path.isdir(arg):
186 if os.path.exists(os.path.join(arg,
187 Utilities.joinext("__init__", ".py"))):
188 basename = os.path.dirname(arg)
189 if arg == '.':
190 sys.stderr.write("The directory '.' is a package.\n")
191 sys.stderr.write("Please repeat the call giving its real name.\n")
192 sys.stderr.write("Ignoring the directory.\n")
193 continue
194 else:
195 basename = arg
196 if basename:
197 basename = "%s%s" % (basename, os.sep)
198
199 if recursive and not os.path.islink(arg):
200 names = [arg] + Utilities.getDirs(arg, excludeDirs)
201 else:
202 names = [arg]
203 else:
204 basename = ""
205 names = [arg]
206
207 for filename in sorted(names):
208 inpackage = False
209 if os.path.isdir(filename):
210 files = []
211 for ext in supportedExtensions:
212 files.extend(glob.glob(os.path.join(filename,
213 Utilities.joinext("*", ext))))
214 initFile = os.path.join(filename,
215 Utilities.joinext("__init__", ext))
216 if initFile in files:
217 inpackage = True
218 files.remove(initFile)
219 files.insert(0, initFile)
220 elif progLanguage != "Python":
221 # assume package
222 inpackage = True
223 else:
224 if Utilities.isWindowsPlatform() and glob.has_magic(filename):
225 files = glob.glob(filename)
226 else:
227 files = [filename]
228
229 for file in files:
230 skipIt = False
231 for pattern in excludePatterns:
232 if fnmatch.fnmatch(os.path.basename(file), pattern):
233 skipIt = True
234 break
235 if skipIt:
236 continue
237
238 try:
239 module = Utilities.ModuleParser.readModule(file,
240 basename = basename, inpackage = inpackage)
241 apiGenerator = APIGenerator(module)
242 api = apiGenerator.genAPI(newStyle, basePackage, includePrivate)
243 except IOError as v:
244 sys.stderr.write("%s error: %s\n" % (file, v[1]))
245 continue
246 except ImportError as v:
247 sys.stderr.write("%s error: %s\n" % (file, v))
248 continue
249
250 for apiEntry in api:
251 if not apiEntry in apis:
252 apis.append(apiEntry)
253 sys.stdout.write("-- %s -- %s ok\n" % (progLanguage, file))
254
255 outdir = os.path.dirname(outputFile)
256 if outdir and not os.path.exists(outdir):
257 os.makedirs(outdir)
258 try:
259 out = open(outputFile, "w")
260 out.write(os.linesep.join(sorted(apis)))
261 out.close()
262 except IOError as v:
263 sys.stderr.write("%s error: %s\n" % (outputFile, v[1]))
264 sys.exit(3)
265
266 sys.stdout.write('\nDone.\n')
267 sys.exit(0)
268
269 if __name__ == '__main__':
270 main()

eric ide

mercurial