├── .flake8
├── .github
└── workflows
│ ├── publish.yml
│ └── test.yml
├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── compiledb
├── __init__.py
├── __main__.py
├── cli.py
├── commands
│ ├── __init__.py
│ └── make.py
├── compiler.py
├── parser.py
└── utils.py
├── examples
└── compiledb-aosp.sh
├── pyproject.toml
├── sh-completion
└── compiledb.bash
├── tests
├── __init__.py
├── common.py
├── conftest.py
├── data
│ ├── autotools_simple.txt
│ ├── compile_commands.json
│ ├── compile_commands2.json
│ └── multiple_commands_oneline.txt
├── test_json_compdb.py
└── test_parser.py
└── tox.ini
/.flake8:
--------------------------------------------------------------------------------
1 | [flake8]
2 | ignore = E226, W504
3 | max-line-length = 120
4 | exclude =
5 | .git,
6 | __pycache__
7 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish to PyPI
2 |
3 | on:
4 | push:
5 | tags:
6 | - '*'
7 |
8 | jobs:
9 | build:
10 | name: Build
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v4
14 | with:
15 | persist-credentials: false
16 | fetch-depth: 0
17 | - name: Set up Python
18 | uses: actions/setup-python@v5
19 | with:
20 | python-version: "3.x"
21 | - name: Install pypa/build
22 | run: python3 -m pip install build --user
23 | - name: Build binary wheel and source tarball
24 | run: python3 -m build
25 | - name: Store the distribution packages
26 | uses: actions/upload-artifact@v4
27 | with:
28 | name: python-package-distributions
29 | path: dist/
30 |
31 | publish-to-pypi:
32 | name: Publish package to PyPI
33 | if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes
34 | needs:
35 | - build
36 | runs-on: ubuntu-latest
37 | environment:
38 | name: pypi
39 | url: https://pypi.org/p/compiledb
40 | permissions:
41 | id-token: write
42 | steps:
43 | - name: Download all the dists
44 | uses: actions/download-artifact@v4
45 | with:
46 | name: python-package-distributions
47 | path: dist/
48 | - name: Publish actifacts to PyPI
49 | uses: pypa/gh-action-pypi-publish@release/v1
50 |
51 | github-release:
52 | name: Sign and upload to GitHub Release
53 | needs:
54 | - publish-to-pypi
55 | runs-on: ubuntu-latest
56 | permissions:
57 | contents: write
58 | id-token: write
59 | steps:
60 | - name: Download all the dists
61 | uses: actions/download-artifact@v4
62 | with:
63 | name: python-package-distributions
64 | path: dist/
65 | - name: Sign the dists
66 | uses: sigstore/gh-action-sigstore-python@v3.0.0
67 | with:
68 | inputs: >-
69 | ./dist/*.tar.gz
70 | ./dist/*.whl
71 | - name: Create GitHub Release
72 | env:
73 | GITHUB_TOKEN: ${{ github.token }}
74 | run: >-
75 | gh release create
76 | "$GITHUB_REF_NAME"
77 | --repo "$GITHUB_REPOSITORY"
78 | --notes ""
79 | - name: Upload artifact signatures to GitHub Release
80 | env:
81 | GITHUB_TOKEN: ${{ github.token }}
82 | # Upload to GitHub Release using the `gh` CLI.
83 | # `dist/` contains the built packages, and the
84 | # sigstore-produced signatures and certificates.
85 | run: >-
86 | gh release upload
87 | "$GITHUB_REF_NAME" dist/**
88 | --repo "$GITHUB_REPOSITORY"
89 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 |
3 | on: [push, pull_request, workflow_dispatch]
4 |
5 | env:
6 | FORCE_COLOR: 1
7 |
8 | jobs:
9 | test:
10 | runs-on: ${{ matrix.os }}
11 | strategy:
12 | fail-fast: false
13 | matrix:
14 | python-version: ["3.8", "3.9", "3.10", "3.11"]
15 | os: [ubuntu-latest, macos-latest]
16 |
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: Set up Python ${{ matrix.python-version }}
20 | uses: actions/setup-python@v2
21 | with:
22 | python-version: ${{ matrix.python-version }}
23 |
24 | - name: Install dependencies
25 | run: |
26 | python -m pip install -U pip
27 | python -m pip install ".[dev]"
28 |
29 | - name: Lint
30 | run: python -m flake8 compiledb
31 |
32 | - name: Test
33 | run: python -m pytest
34 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *~
2 | logs/
3 |
4 | # Byte-compiled / optimized / DLL files
5 | __pycache__/
6 | *.py[cod]
7 | *$py.class
8 |
9 | # C extensions
10 | *.so
11 |
12 | # Distribution / packaging
13 | .Python
14 | env/
15 | build/
16 | develop-eggs/
17 | dist/
18 | downloads/
19 | eggs/
20 | .eggs/
21 | lib/
22 | lib64/
23 | parts/
24 | sdist/
25 | var/
26 | wheels/
27 | *.egg-info/
28 | .installed.cfg
29 | *.egg
30 |
31 | # PyInstaller
32 | # Usually these files are written by a python script from a template
33 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
34 | *.manifest
35 | *.spec
36 |
37 | # Installer logs
38 | pip-log.txt
39 | pip-delete-this-directory.txt
40 |
41 | # Unit test / coverage reports
42 | htmlcov/
43 | .tox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | .hypothesis/
51 | .pytest_cache/
52 | test-report.xml
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 |
62 | # Flask stuff:
63 | instance/
64 | .webassets-cache
65 |
66 | # Scrapy stuff:
67 | .scrapy
68 |
69 | # Sphinx documentation
70 | docs/_build/
71 |
72 | # PyBuilder
73 | target/
74 |
75 | # Jupyter Notebook
76 | .ipynb_checkpoints
77 |
78 | # pyenv
79 | .python-version
80 |
81 | # celery beat schedule file
82 | celerybeat-schedule
83 |
84 | # SageMath parsed files
85 | *.sage.py
86 |
87 | # dotenv
88 | .env
89 |
90 | # virtualenv
91 | .venv
92 | venv/
93 | ENV/
94 |
95 | # Spyder project settings
96 | .spyderproject
97 | .spyproject
98 |
99 | # Rope project settings
100 | .ropeproject
101 |
102 | # mkdocs documentation
103 | /site
104 |
105 | # mypy
106 | .mypy_cache/
107 |
108 | # vim-related
109 | *.swp
110 | *.swo
111 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python:
3 | - "2.7"
4 | - "3.6"
5 | install:
6 | - pip install tox-travis
7 | script:
8 | - tox
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
676 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Compilation Database Generator
2 |
3 | [](https://circleci.com/gh/nickdiego/compiledb)
4 | [](https://pypi.org/project/compiledb/)
5 | [](https://pypi.org/project/compiledb)
6 | [](https://github.com/nickdiego/compiledb/blob/master/LICENSE)
7 |
8 | Tool for generating [Clang's JSON Compilation Database][compdb] file for GNU
9 | `make`-based build systems.
10 |
11 | It's aimed mainly at non-cmake (cmake already generates compilation database)
12 | large codebases. Inspired by projects like [YCM-Generator][ycm-gen] and [Bear][bear],
13 | but faster (mainly with large projects), since in most cases it **doesn't need a clean
14 | build** (as the mentioned tools do) to generate the compilation database file, to
15 | achieve this it uses the make options such as `-n`/`--dry-run` and `-k`/`--keep-going`
16 | to extract the compile commands. Also, it's more **cross-compiling friendly** than
17 | YCM-generator's fake-toolchanin approach.
18 |
19 | ## Installation
20 |
21 | ```
22 | # pip install compiledb
23 | ```
24 | - Supports Python >= 3.3
25 | - For bash completion support, add the content of `sh-completion/compiledb.bash` file
26 | to your `.bashrc` file, for example.
27 |
28 | ## Usage
29 |
30 | `compiledb` provides a `make` python wrapper script which, besides to execute the make
31 | build command, updates the JSON compilation database file corresponding to that build,
32 | resulting in a command-line interface similar to [Bear][bear].
33 |
34 | To generate `compile_commands.json` file using compiledb's "make wrapper" script,
35 | executing Makefile target `all`:
36 | ```bash
37 | $ compiledb make
38 | ```
39 |
40 | `compiledb` forwards all the options/arguments passed after `make` subcommand to GNU Make,
41 | so one can, for example, generate `compile_commands.json` using `core/main.mk`
42 | as main makefile (`-f` flag), starting the build from `build` directory (`-C` flag):
43 | ```bash
44 | $ compiledb make -f core/main.mk -C build
45 | ```
46 |
47 | By default, `compiledb make` generates the compilation database and runs the actual build
48 | command requested (acting as a make wrapper), the build step can be skipped using the `-n`
49 | or `--no-build` options.
50 | ```bash
51 | $ compiledb -n make
52 | ```
53 |
54 | `compiledb` base command has been designed so that it can be used to parse compile commands
55 | from arbitrary text files (or stdin), assuming it has a build log (ideally generated using
56 | `make -Bnwk` command), and generates the corresponding JSON Compilation database.
57 |
58 | For example, to generate the compilation database from `build-log.txt` file, use the following
59 | command.
60 | ```bash
61 | $ compiledb --parse build-log.txt
62 | ```
63 |
64 | or its equivalent:
65 | ```bash
66 | $ compiledb < build-log.txt
67 | ```
68 |
69 | Or even, to pipe make's output and print the compilation database to the standard output:
70 | ```bash
71 | $ make -Bnwk | compiledb -o-
72 | ```
73 |
74 | By default `compiledb` generates a JSON compilation database in the "arguments" list
75 | [format](https://clang.llvm.org/docs/JSONCompilationDatabase.html). The "command" string
76 | format is also supported through the use of the `--command-style` flag:
77 | ```bash
78 | $ compiledb --command-style make
79 | ```
80 |
81 | ## Testing / Contributing
82 |
83 | I've implemented this tool because I needed to index some [AOSP][aosp]'s modules for navigating
84 | and studying purposes (after having no satisfatory results with current tools available by the
85 | time such as [YCM-Generator][ycm] and [Bear][bear]). So I've reworked YCM-Generator, which resulted
86 | in the initial version of [compiledb/parser.py](compiledb/parser.py) and used successfully to generate
87 | `compile_commands.json` for some AOSP modules in ~1min running in a [Docker][docker] container and then
88 | could use it with some great tools, such as:
89 |
90 | - [Vim][vim] + [YouCompleteMe][ycm] + [rtags][rtags] + [chromatica.nvim][chrom]
91 | - [Neovim][neovim] + [LanguageClient-neovim][lsp] + [cquery][cquery] + [deoplete][deoplete]
92 | - [Neovim][neovim] + [ALE][ale] + [ccls][ccls]
93 |
94 | Notice:
95 | - _Windows: tested on Windows 10 with cmd, wsl(Ubuntu), mingw32_
96 | - _Linux: tested only on Arch Linux and Ubuntu 18 so far_
97 | - _Mac: tested on macOS 10.13 and 10.14_
98 |
99 | Patches are always welcome :)
100 |
101 | ## License
102 | GNU GPLv3
103 |
104 | ## Related Project
105 | [compiledb-go]: compiledb go version
106 |
107 | [compdb]: https://clang.llvm.org/docs/JSONCompilationDatabase.html
108 | [ycm]: https://github.com/Valloric/YouCompleteMe
109 | [rtags]: https://github.com/Andersbakken/rtags
110 | [chrom]: https://github.com/arakashic/chromatica.nvim
111 | [ycm-gen]: https://github.com/rdnetto/YCM-Generator
112 | [bear]: https://github.com/rizsotto/Bear
113 | [aosp]: https://source.android.com/
114 | [docker]: https://www.docker.com/
115 | [vim]: https://www.vim.org/
116 | [neovim]: https://neovim.io/
117 | [lsp]: https://github.com/autozimu/LanguageClient-neovim
118 | [cquery]: https://github.com/cquery-project/cquery
119 | [deoplete]: https://github.com/Shougo/deoplete.nvim
120 | [ccls]: https://github.com/MaskRay/ccls
121 | [ale]: https://github.com/w0rp/ale
122 | [compiledb-go]: https://github.com/fcying/compiledb-go
123 |
--------------------------------------------------------------------------------
/compiledb/__init__.py:
--------------------------------------------------------------------------------
1 | #
2 | # compiledb: Tool for generating LLVM Compilation Database
3 | # files for make-based build systems.
4 | #
5 | # Copyright (c) 2017 Nick Diego Yamane
6 | #
7 | # This program is free software; you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation; either version 2 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # This program is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with this program. If not, see .
19 | #
20 | # ex: ts=2 sw=4 et filetype=python
21 |
22 | import json
23 | import os
24 | import sys
25 | import logging
26 |
27 | from compiledb.parser import parse_build_log, Error
28 |
29 |
30 | logger = logging.getLogger(__name__)
31 |
32 |
33 | def __is_stdout(pfile):
34 | try:
35 | return pfile.name == sys.stdout.name or isinstance(pfile.name, int)
36 | except AttributeError:
37 | return pfile == sys.stdout
38 |
39 |
40 | def basename(stream):
41 | if __is_stdout(stream):
42 | return ""
43 | else:
44 | return os.path.basename(stream.name)
45 |
46 |
47 | def generate_json_compdb(instream=None, proj_dir=os.getcwd(), exclude_files=[], add_predefined_macros=False,
48 | use_full_path=False, command_style=False):
49 | if not os.path.isdir(proj_dir):
50 | raise Error("Project dir '{}' does not exists!".format(proj_dir))
51 |
52 | logger.info("## Processing build commands from {}".format(basename(instream)))
53 | result = parse_build_log(instream, proj_dir, exclude_files, add_predefined_macros=add_predefined_macros,
54 | use_full_path=use_full_path, command_style=command_style)
55 | return result
56 |
57 |
58 | def write_json_compdb(compdb, outstream, force=False, pretty_output=True):
59 | logger.info("## Writing compilation database with {} entries to {}".format(
60 | len(compdb), basename(outstream)))
61 |
62 | # We could truncate after reading, but here is easier to understand
63 | if not __is_stdout(outstream):
64 | outstream.seek(0)
65 | outstream.truncate()
66 | json.dump(compdb, outstream, indent=pretty_output)
67 | outstream.write(os.linesep)
68 |
69 |
70 | def load_json_compdb(outstream):
71 | try:
72 | if __is_stdout(outstream):
73 | return []
74 |
75 | # Read from beggining of file
76 | outstream.seek(0)
77 | compdb = json.load(outstream)
78 | logger.info("## Loaded compilation database with {} entries from {}".format(
79 | len(compdb), basename(outstream)))
80 | return compdb
81 | except Exception as e:
82 | logger.debug("## Failed to read previous {}: {}".format(basename(outstream), e))
83 | return []
84 |
85 |
86 | def merge_compdb(compdb, new_compdb, check_files=True):
87 | def gen_key(entry):
88 | if 'directory' in entry:
89 | return os.path.join(entry['directory'], entry['file'])
90 | return entry['directory']
91 |
92 | def check_file(path):
93 | return True if not check_files else os.path.exists(path)
94 |
95 | orig = {gen_key(c): c for c in compdb if 'file' in c}
96 | new = {gen_key(c): c for c in new_compdb if 'file' in c}
97 | orig.update(new)
98 | return [v for k, v in orig.items() if check_file(k)]
99 |
100 |
101 | def generate(infile, outfile, build_dir, exclude_files, overwrite=False, strict=False,
102 | add_predefined_macros=False, use_full_path=False, command_style=False):
103 | try:
104 | r = generate_json_compdb(infile, proj_dir=build_dir, exclude_files=exclude_files,
105 | add_predefined_macros=add_predefined_macros, use_full_path=use_full_path,
106 | command_style=command_style)
107 | compdb = [] if overwrite else load_json_compdb(outfile)
108 | compdb = merge_compdb(compdb, r.compdb, strict)
109 | write_json_compdb(compdb, outfile)
110 | logger.info("## Done.")
111 | return True
112 | except Error as e:
113 | logger.error(e)
114 | return False
115 |
--------------------------------------------------------------------------------
/compiledb/__main__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #
3 | # compiledb: Tool for generating LLVM Compilation Database
4 | # files for make-based build systems.
5 | #
6 | # Copyright (c) 2017 Nick Diego Yamane
7 | #
8 | # This program is free software; you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation; either version 2 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | from compiledb import cli
23 |
24 | if (__name__ == "__main__"):
25 | cli.cli()
26 |
27 | # ex: ts=2 sw=4 et filetype=python
28 |
--------------------------------------------------------------------------------
/compiledb/cli.py:
--------------------------------------------------------------------------------
1 | #
2 | # compiledb: Tool for generating LLVM Compilation Database
3 | # files for make-based build systems.
4 | #
5 | # Copyright (c) 2017 Nick Diego Yamane
6 | #
7 | # This program is free software; you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation; either version 2 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # This program is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with this program. If not, see .
19 | #
20 | # ex: ts=2 sw=4 et filetype=python
21 |
22 |
23 | import click
24 | import os
25 | import sys
26 | import logging
27 |
28 | from . import generate
29 | from .commands import make
30 |
31 | CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
32 |
33 |
34 | class Options(object):
35 | """ Simple data class used to store command line options
36 | shared by all compiledb subcommands"""
37 |
38 | def __init__(self, infile, outfile, build_dir, exclude_files, no_build,
39 | verbose, overwrite, strict, add_predefined_macros, use_full_path, command_style):
40 | self.infile = infile
41 | self.outfile = outfile
42 | self.build_dir = build_dir
43 | self.exclude_files = exclude_files
44 | self.verbose = verbose
45 | self.no_build = no_build
46 | self.overwrite = overwrite
47 | self.strict = strict
48 | self.add_predefined_macros = add_predefined_macros
49 | self.use_full_path = use_full_path
50 | self.command_style = command_style
51 |
52 |
53 | @click.group(context_settings=CONTEXT_SETTINGS, invoke_without_command=True)
54 | @click.option('-p', '--parse', 'infile', type=click.File('r'),
55 | help='Build log file to parse compilation commands from.' +
56 | '(Default: stdin)', required=False, default=sys.stdin)
57 | @click.option('-o', '--output', 'outfile', type=click.File('a+'),
58 | help="Output file path (Default: compile_commands.json). " +
59 | 'If -f/--overwrite is not specified, this file is updated ' +
60 | 'with the new contents. Use \'-\' to output to stdout',
61 | required=False, default='compile_commands.json')
62 | @click.option('-d', '--build-dir', 'build_dir', type=click.Path(),
63 | help="Path to be used as initial build dir", default=os.getcwd())
64 | @click.option('-e', '--exclude', 'exclude_files', multiple=True,
65 | help="Regular expressions to exclude files.")
66 | @click.option('-n', '--no-build', is_flag=True, default=False,
67 | help='Only generates compilation db file.')
68 | @click.option('-v', '--verbose', is_flag=True, default=False,
69 | help='Print verbose messages.')
70 | @click.option('-f', '--overwrite', is_flag=True, default=False,
71 | help='Overwrite compile_commands.json instead of just updating it.')
72 | @click.option('-S', '--no-strict', is_flag=True, default=False,
73 | help='Do not check if source files exist in the file system.')
74 | @click.option('-m', '--macros', 'add_predefined_macros', is_flag=True, default=False,
75 | help='Add predefined compiler macros to the compilation database. Make sure that ' +
76 | 'all of the used compilers are in your $PATH')
77 | @click.option('--full-path', 'use_full_path', is_flag=True, default=False,
78 | help='Write full path to the compiler executable.')
79 | @click.option('--command-style', is_flag=True, default=False,
80 | help='Output compilation database with single "command" '
81 | 'string rather than the default "arguments" list of strings.')
82 | @click.pass_context
83 | def cli(ctx, infile, outfile, build_dir, exclude_files, no_build, verbose, overwrite, no_strict, add_predefined_macros,
84 | use_full_path, command_style):
85 | """Clang's Compilation Database generator for make-based build systems.
86 | When no subcommand is used it will parse build log/commands and generates
87 | its corresponding Compilation database."""
88 | log_level = logging.DEBUG if verbose else logging.ERROR
89 | logging.basicConfig(level=log_level, format=None)
90 | if ctx.invoked_subcommand is None:
91 | done = generate(infile, outfile, build_dir, exclude_files, overwrite, not no_strict, add_predefined_macros,
92 | use_full_path, command_style)
93 | exit(0 if done else 1)
94 | else:
95 | ctx.obj = Options(infile, outfile, build_dir, exclude_files, no_build, verbose, overwrite, not no_strict,
96 | add_predefined_macros, use_full_path, command_style)
97 |
98 |
99 | # Add subcommands
100 | cli.add_command(make.command)
101 |
--------------------------------------------------------------------------------
/compiledb/commands/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nickdiego/compiledb/2550745e6d205db4d1ff92c81801d1c738bf03b1/compiledb/commands/__init__.py
--------------------------------------------------------------------------------
/compiledb/commands/make.py:
--------------------------------------------------------------------------------
1 | import click
2 | import os
3 | import stat
4 | import tempfile
5 |
6 | from subprocess import call, PIPE
7 | from sys import exit, stdout, stderr
8 |
9 | from compiledb import generate
10 | from compiledb.utils import popen, cmd_join
11 |
12 |
13 | class AutoconfMockScript:
14 | """This hack is intended to make it possible/feasible
15 | to use "make --dry-run --always-make" to speed up the compilation
16 | commands extraction with autoconf/automake based build systems.
17 | Without this ugly hack, particularly `--always-make` causes the
18 | autoconf's configure script to be executed to every make target,
19 | severely slowing down the process.
20 | To work around this issue we use a mock/empty script to be used
21 | in place of config.status and missing is they exist.
22 | """
23 | def __init__(self, verbose):
24 | self.verbose = verbose
25 | self.path = None
26 | self.mock_script = """#!/bin/bash
27 | ## Auto generated by compiledb. Do not modify!
28 | ## https://github.com/nickdiego/compiledb
29 | case "$*" in
30 | ./config.status*|*/missing*)
31 | #echo "Skipping $@" >>/tmp/compiledb.log
32 | exit 0
33 | ;;
34 | *)
35 | shift && test $# -gt 0 && /bin/sh -c "$@"
36 | exit $?
37 | ;;
38 | esac
39 | """
40 |
41 | def __enter__(self):
42 | if not os.path.isfile("config.status"):
43 | return self
44 | try:
45 | fd, tmp = tempfile.mkstemp()
46 | with os.fdopen(fd, 'w') as out:
47 | out.write(self.mock_script)
48 | os.chmod(tmp, stat.S_IEXEC | stat.S_IREAD)
49 | self.path = tmp
50 | return self
51 | except Exception as e:
52 | self.cleanup()
53 | raise e
54 |
55 | def __exit__(self, exc_type, exc_value, traceback):
56 | self.cleanup()
57 |
58 | def cleanup(self):
59 | if not self.path:
60 | return
61 | if self.verbose:
62 | print("Cleaning up autoconf mock resources..")
63 | if os.path.isfile(self.path):
64 | os.remove(self.path)
65 |
66 |
67 | @click.command(name='make', context_settings=dict(ignore_unknown_options=True))
68 | @click.option('-c', '--cmd', 'make_cmd', nargs=1, required=False,
69 | help="Command to be used as make executable.")
70 | @click.argument('make_args', nargs=-1, type=click.UNPROCESSED)
71 | @click.pass_context
72 | def command(ctx, make_cmd, make_args):
73 | """Generates compilation database file for an arbitrary GNU Make command.
74 | Acts like a make wrapper, forwarding all MAKE_ARGS to make command"""
75 | make_cmd = make_cmd or 'make'
76 | logging_mode_flags = "-Bnkw"
77 |
78 | options = ctx.obj
79 |
80 | if not options.no_build:
81 | cmd = [make_cmd] + list(make_args)
82 | print("## Building [{}]...".format(' '.join(cmd)))
83 | ret = call(cmd, stdout=stdout, stderr=stderr)
84 | print()
85 | if ret != 0:
86 | exit(1)
87 |
88 | done = False
89 | args = vars(options)
90 | del args['no_build']
91 | with AutoconfMockScript(options.verbose) as mock_script:
92 | cmd = [make_cmd, logging_mode_flags] + list(make_args)
93 | if mock_script.path:
94 | cmd.append("SHELL={}".format(mock_script.path))
95 | pipe = popen(cmd_join(cmd), stdout=PIPE)
96 | options.infile = pipe.stdout
97 | del args['verbose']
98 | done = generate(**args)
99 | pipe.wait()
100 | exit(0 if done else 1)
101 |
--------------------------------------------------------------------------------
/compiledb/compiler.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | from shutil import which
4 | from subprocess import PIPE
5 |
6 | from compiledb.utils import popen
7 |
8 | _logger = logging.getLogger(__name__)
9 |
10 |
11 | class Compiler:
12 | def __init__(self, name="gcc"):
13 | # Name of the compiler executable
14 | self._name = name
15 |
16 | # Full path to the compiler executable
17 | self._full_path = self._find_full_path()
18 |
19 | # Supported languages by the compiler
20 | self._languages = {
21 | "c": {
22 | "extensions": ["c"]
23 | },
24 | "c++": {
25 | "extensions": ["cpp", "cc", "cx", "cxx"],
26 | },
27 | }
28 |
29 | # Keep a list of macros for each language since, for example, gcc can be used both for C and C++ sources.
30 | self._predefined_macros = {
31 | # language: ["-DMACRO1", "-DMACRO2=1"]
32 | }
33 |
34 | def __str__(self):
35 | return self.name
36 |
37 | def _find_full_path(self):
38 | """Get a full path to the compiler executable."""
39 | full_path = which(self.name)
40 |
41 | if full_path is None:
42 | full_path = self.name
43 |
44 | return full_path
45 |
46 | def _get_language(self, arguments, source_file):
47 | """Attempt to find the language from flags or the source name."""
48 | default = "c"
49 |
50 | for arg_idx, arg in enumerate(arguments):
51 | if arg == "-x" and arg_idx < len(arguments) - 1:
52 | return arguments[arg_idx + 1]
53 |
54 | if "-std=" in arg:
55 | if "++" in arg:
56 | return "c++"
57 | else:
58 | return default
59 |
60 | _, extension = os.path.splitext(source_file)
61 |
62 | if extension in self._languages["c++"]["extensions"]:
63 | return "c++"
64 | else:
65 | return default
66 |
67 | def _add_predefined_macros(self, language):
68 | """Add a list of macros predefined by the compiler for future use."""
69 | self._predefined_macros[language] = []
70 | # Dump all predefined compiler macros
71 | cmd = "echo | " + self.name + " -x " + language + " -dM -E -"
72 |
73 | try:
74 | pipe = popen(cmd, stdout=PIPE)
75 | except (OSError, ValueError) as e:
76 | _logger.error(e)
77 | return
78 |
79 | for line in pipe.stdout:
80 | columns = line.split()
81 | size = len(columns)
82 |
83 | if size <= 1:
84 | continue
85 | elif size == 2:
86 | def_arg = "-D" + columns[1]
87 | else:
88 | def_arg = "-D" + columns[1] + "=" + " ".join(columns[2:])
89 |
90 | self._predefined_macros[language].append(def_arg)
91 |
92 | pipe.wait()
93 |
94 | @property
95 | def name(self):
96 | return self._name
97 |
98 | @property
99 | def full_path(self):
100 | return self._full_path
101 |
102 | def get_predefined_macros(self, arguments, source_file):
103 | """Return a list of macros predefined by the compiler."""
104 | language = self._get_language(arguments, source_file)
105 |
106 | if language not in self._predefined_macros:
107 | self._add_predefined_macros(language)
108 |
109 | return self._predefined_macros[language]
110 |
111 |
112 | _compilers = []
113 |
114 |
115 | def get_compiler(name):
116 | c = next((compiler for compiler in _compilers if name == compiler.name), None)
117 |
118 | if c is None:
119 | c = Compiler(name)
120 | _compilers.append(c)
121 |
122 | return c
123 |
--------------------------------------------------------------------------------
/compiledb/parser.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #
3 | # compiledb: Tool for generating LLVM Compilation Database
4 | # files for make-based build systems.
5 | #
6 | # Copyright (c) 2017 Nick Diego Yamane
7 | #
8 | # This program is free software; you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation; either version 2 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 | import bashlex
22 | import re
23 | import logging
24 |
25 | from compiledb.compiler import get_compiler
26 | from compiledb.utils import run_cmd
27 |
28 | # Internal variables used to parse build log entries
29 | cc_compile_regex = re.compile(r"^.*-?g?cc-?[0-9.]*$|^.*-?clang-?[0-9.]*$")
30 | cpp_compile_regex = re.compile(r"^.*-?[gc]\+\+-?[0-9.]*$|^.*-?clang\+\+-?[0-9.]*$")
31 | file_regex = re.compile(r"^.+\.c$|^.+\.cc$|^.+\.cpp$|^.+\.cxx$|^.+\.s$", re.IGNORECASE)
32 | compiler_wrappers = {"ccache", "icecc", "sccache"}
33 |
34 | # Leverage `make --print-directory` option
35 | make_enter_dir = re.compile(r"^\s*make\[\d+\]: Entering directory [`\'\"](?P.*)[`\'\"]\s*$")
36 | make_leave_dir = re.compile(r"^\s*make\[\d+\]: Leaving directory .*$")
37 |
38 | # We want to skip such lines from configure to avoid spurious MAKE expansion errors.
39 | checking_make = re.compile(r"^checking whether .* sets \$\(\w+\)\.\.\. (yes|no)$")
40 |
41 | logger = logging.getLogger(__name__)
42 |
43 |
44 | class ParsingResult(object):
45 | def __init__(self):
46 | self.skipped = 0
47 | self.count = 0
48 | self.compdb = []
49 |
50 | def __str__(self):
51 | return "Line count: {}, Skipped: {}, Entries: {}".format(self.count, self.skipped, str(self.compdb))
52 |
53 |
54 | class Error(Exception):
55 | def __init__(self, msg):
56 | self.msg = msg
57 |
58 | def __str__(self):
59 | return "Error: {}".format(self.msg)
60 |
61 |
62 | def parse_build_log(build_log, proj_dir, exclude_files, command_style=False, add_predefined_macros=False,
63 | use_full_path=False, extra_wrappers=[]):
64 | result = ParsingResult()
65 |
66 | def skip_line(cmd, reason):
67 | logger.debug("Line {}: {}. Ignoring: '{}'".format(lineno, reason, cmd))
68 | result.skipped += 1
69 |
70 | exclude_files_regex = None
71 | if len(exclude_files) > 0:
72 | try:
73 | exclude_files = "|".join(exclude_files)
74 | exclude_files_regex = re.compile(exclude_files)
75 | except re.error:
76 | raise Error('Exclude files regex not valid: {}'.format(exclude_files))
77 |
78 | compiler_wrappers.update(extra_wrappers)
79 |
80 | dir_stack = [proj_dir]
81 | working_dir = proj_dir
82 | lineno = 0
83 |
84 | # Process build log
85 | for line in build_log:
86 | lineno += 1
87 | # Concatenate line if need
88 | accumulate_line = line
89 | while (line.endswith('\\\n')):
90 | accumulate_line = accumulate_line[:-2]
91 | line = next(build_log, '')
92 | accumulate_line += line
93 | line = accumulate_line.rstrip()
94 |
95 | # Parse directory that make entering/leaving
96 | enter_dir = make_enter_dir.match(line)
97 | if (make_enter_dir.match(line)):
98 | working_dir = enter_dir.group('dir')
99 | dir_stack.append(working_dir)
100 | continue
101 | if (make_leave_dir.match(line)):
102 | dir_stack.pop()
103 | working_dir = dir_stack[-1]
104 | continue
105 | if (checking_make.match(line)):
106 | continue
107 |
108 | commands = []
109 | try:
110 | commands = CommandProcessor.process(line, working_dir)
111 | except Exception as err:
112 | msg = 'Failed to parse build command [Details: ({}) {}]'.format(type(err), str(err))
113 | skip_line(line, msg)
114 | continue
115 |
116 | if not commands:
117 | result.skipped += 1
118 |
119 | for c in commands:
120 | filepath = c['filepath']
121 | cmd = c['cmd']
122 | if filepath is None:
123 | skip_line(cmd, 'Empty file name')
124 | continue
125 | else:
126 | result.count += 1
127 |
128 | if filepath and exclude_files_regex and exclude_files_regex.match(filepath):
129 | skip_line(cmd, "Excluding file (regex='{}')".format(exclude_files))
130 | continue
131 |
132 | wrappers = c['wrappers']
133 | unknown = ["'%s'" % w for w in wrappers if w not in compiler_wrappers]
134 | if unknown:
135 | unknown = ', '.join(unknown)
136 | logger.debug("Add command with unknown wrapper(s) {}".format(unknown))
137 |
138 | # add entry to database
139 | tokens = c['tokens']
140 | arguments = [unescape(a) for a in tokens[len(wrappers):]]
141 |
142 | compiler = get_compiler(arguments[0])
143 |
144 | if add_predefined_macros:
145 | predefined_macros = compiler.get_predefined_macros(arguments, filepath)
146 | arguments.extend(predefined_macros)
147 |
148 | if use_full_path:
149 | arguments[0] = compiler.full_path
150 |
151 | command_str = ' '.join(arguments)
152 |
153 | logger.debug("Adding command {}: {}".format(len(result.compdb), command_str))
154 |
155 | if command_style:
156 | result.compdb.append({
157 | 'directory': working_dir,
158 | 'command': command_str,
159 | 'file': filepath,
160 | })
161 | else:
162 | result.compdb.append({
163 | 'directory': working_dir,
164 | 'arguments': arguments,
165 | 'file': filepath,
166 | })
167 |
168 | return result
169 |
170 |
171 | class SubstCommandVisitor(bashlex.ast.nodevisitor):
172 | """Uses bashlex to parse and process sh/bash substitution commands.
173 | May result in a parsing exception for invalid commands."""
174 | def __init__(self):
175 | self.substs = []
176 |
177 | def visitcommandsubstitution(self, n, cmd):
178 | self.substs.append(n)
179 | return False
180 |
181 |
182 | class CommandProcessor(bashlex.ast.nodevisitor):
183 | """Uses bashlex to parse and traverse the resulting bash AST
184 | looking for and extracting compilation commands."""
185 | @staticmethod
186 | def process(line, wd):
187 | trees = bashlex.parser.parse(line)
188 | if not trees:
189 | return []
190 | for tree in trees:
191 | svisitor = SubstCommandVisitor()
192 | svisitor.visit(tree)
193 | substs = svisitor.substs
194 | substs.reverse()
195 | preprocessed = list(line)
196 | for s in substs:
197 | start, end = s.command.pos
198 | s_cmd = line[start:end]
199 | out = run_cmd(s_cmd, shell=True, cwd=wd)
200 | start, end = s.pos
201 | preprocessed[start:end] = out.strip()
202 | preprocessed = ''.join(preprocessed)
203 |
204 | trees = bashlex.parser.parse(preprocessed)
205 | processor = CommandProcessor(preprocessed, wd)
206 | for tree in trees:
207 | processor.do_process(tree)
208 | return processor.commands
209 |
210 | def __init__(self, line, wd):
211 | self.line = line
212 | self.wd = wd
213 | self.commands = []
214 | self.reset()
215 |
216 | def reset(self):
217 | self.compiler = None
218 | self.cmd = None
219 | self.filepath = None
220 | self.tokens = []
221 | self.wrappers = []
222 |
223 | def do_process(self, tree):
224 | self.visit(tree)
225 | self.check_last_cmd()
226 | return self.commands
227 |
228 | def visitcommand(self, node, cmd):
229 | self.check_last_cmd()
230 | self.cmd = self.line[node.pos[0]:node.pos[1]]
231 | logger.debug('New command: {}'.format(self.cmd))
232 | return True
233 |
234 | def visitword(self, node, word):
235 | # Check if it looks like an entry of interest and
236 | # and try to determine the compiler
237 | if self.compiler is None:
238 | if ((cc_compile_regex.match(word) or cpp_compile_regex.match(word)) and
239 | word not in compiler_wrappers):
240 | self.compiler = word
241 | else:
242 | self.wrappers.append(word)
243 | elif (file_regex.match(word)):
244 | self.filepath = word
245 |
246 | self.tokens.append(word)
247 | return True
248 |
249 | def check_last_cmd(self):
250 | # check if it seems to be a compilation command
251 | if self.compiler is not None:
252 | self.commands.append(dict(cmd=self.cmd, wrappers=self.wrappers, tokens=self.tokens,
253 | compiler=self.compiler, filepath=self.filepath))
254 | # reset state to process new command
255 | self.reset()
256 |
257 |
258 | def unescape(s):
259 | return s.encode().decode('unicode_escape')
260 |
261 | # ex: ts=2 sw=4 et filetype=python
262 |
--------------------------------------------------------------------------------
/compiledb/utils.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | from sys import version_info
3 |
4 | if version_info.major >= 3 and version_info.minor >= 6:
5 | def popen(cmd, encoding='utf-8', **kwargs):
6 | return subprocess.Popen(cmd, encoding=encoding, shell=True, **kwargs)
7 |
8 | def run_cmd(cmd, encoding='utf-8', **kwargs):
9 | return subprocess.check_output(cmd, encoding=encoding, **kwargs)
10 | else: # Python 2 and Python <= 3.5
11 | def popen(cmd, encoding='utf-8', **kwargs):
12 | return subprocess.Popen(cmd, shell=True, **kwargs)
13 |
14 | def run_cmd(cmd, encoding='utf-8', **kwargs):
15 | return subprocess.check_output(cmd, **kwargs)
16 |
17 | try:
18 | from shlex import quote as cmd_quote
19 | except ImportError:
20 | from pipes import quote as cmd_quote
21 |
22 |
23 | def cmd_join(cmd):
24 | return ' '.join(cmd_quote(s) for s in cmd)
25 |
--------------------------------------------------------------------------------
/examples/compiledb-aosp.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | #
3 | # compiledb: Tool for generating LLVM Compilation Database
4 | # files for make-based build systems.
5 | #
6 | # Copyright (c) 2017 Nick Diego Yamane
7 | #
8 | # This program is free software; you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation; either version 2 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 | set -e
22 |
23 | scriptdir=$(dirname "$(realpath "${BASH_SOURCE[0]}")")
24 |
25 | VERBOSE=0
26 |
27 | show_help() {
28 | cat << EOF
29 |
30 | usage: compiledb-aosp [-h] [-v] [-f] [-o OUTPUT] [-i INPUT] [-p INCLUDE_PREFIX] MODULE
31 |
32 | Generates compilation database file for an AOSP (Android Open Source Project) modules.
33 |
34 | positional arguments:
35 | MODULE The AOSP module directory (relative path)
36 |
37 | optional arguments:
38 | -h, --help show this help message and exit
39 | -v, --verbose Show output from build process
40 | -o OUTPUT, --output OUTPUT
41 | Save the compilation database file as OUTPUT. Default:
42 | MODULE/compile_commands.json
43 | -r AOSP_ROOT, --aosp-root AOSP_ROOT
44 | AOSP root path. Default: current directory
45 | -H AOSP_ROOT_HOST, --aosp-root-host AOSP_ROOT_HOST
46 | AOSP root path on host machine. For cases where one is running aosp
47 | builds inside a Docker container and using compilation database outside it.
48 | Default: AOSP_ROOT
49 |
50 | EOF
51 | }
52 |
53 | while (( $# )); do
54 | case $1 in
55 | -o | --output)
56 | shift && comp_db=$1
57 | ;;
58 | -r | --aosp-root)
59 | shift && aosp_root=$1
60 | ;;
61 | -H | --aosp-root-host)
62 | shift && aosp_root_host=$1
63 | ;;
64 | -h | --help)
65 | show_help
66 | exit 0;;
67 | -v | --verbose)
68 | VERBOSE=1
69 | ;;
70 | -*)
71 | echo "Unrecognized option $1" >&2
72 | echo >&2; show_help
73 | exit 1
74 | ;;
75 | *)
76 | module=$1
77 | esac
78 | shift
79 | done
80 |
81 | aosp_root=${aosp_root:-$(pwd)}
82 | aosp_root_host=${aosp_root_host:-${aosp_root}}
83 | module=${module:-bionic/libc}
84 |
85 | build_err="/tmp/build-err.txt"
86 | comp_db="${aosp_root}/${module}/compile_commands.json"
87 |
88 | if [ ! -e "${aosp_root}/build/envsetup.sh" ]; then
89 | echo "Error: ${aosp_root} not a valid AOSP root path!" >&2
90 | exit 1
91 | fi
92 | echo "# Loading build env"
93 | source ${aosp_root}/build/envsetup.sh >/dev/null
94 |
95 | echo "# Configuring x86_64 build"
96 | lunch aosp_x86_64-eng >/dev/null
97 | unset -v USE_CCACHE
98 |
99 | declare -a module_opts
100 |
101 | if [ -n "$module" ]; then
102 | if [ ! -d "${aosp_root}/${module}" ]; then
103 | echo "!! Error: Module '${module}' not found in AOSP tree!"
104 | exit 1
105 | fi
106 | module_opts=( all_modules "BUILD_MODULES_IN_PATHS=${module}" )
107 | echo "# Chosen module: $module"
108 | else
109 | echo "# Full AOSP indexing!"
110 | fi
111 |
112 | num_cpus=$(grep -c ^processor /proc/cpuinfo)
113 | make_opts=( "-j${num_cpus}" -C "$aosp_root" -f 'build/core/main.mk' )
114 | parser_opts=(
115 | "--output=${comp_db}"
116 | "--include-prefix=${aosp_root_host}"
117 | "--build-dir" "${aosp_root}" )
118 |
119 | (( VERBOSE )) && parser_opts+=( --verbose )
120 |
121 | echo "# Generating compilation database file $(readlink -f $comp_db)"
122 | compiledb "${parser_opts[@]}" make "${make_opts[@]}" "${module_opts[@]}" 2>$build_err
123 |
124 | # ex: ts=2 sw=4 et filetype=sh
125 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=64", "setuptools-scm>=8", "wheel"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [tool.setuptools_scm]
6 | version_scheme = "post-release"
7 | local_scheme = "node-and-date"
8 |
9 | [project]
10 | name = "compiledb"
11 | dynamic = ["version"] # determined dynamically from git refs. See tools.setuptool_scm above.
12 | description = "Tool for generating Clang JSON Compilation Database files for make-based build systems."
13 | license = {text = "GPL-3.0-or-later"}
14 | authors = [{name = "Nick Yamane", email = "nickdiego@igalia.com"}]
15 | requires-python = ">=3.3"
16 | dependencies = [
17 | "click",
18 | "bashlex",
19 | ]
20 | readme = "README.md"
21 | keywords = [
22 | "compilation-database",
23 | "clang",
24 | "c",
25 | "cpp",
26 | "makefile",
27 | "make",
28 | "language-server",
29 | "lsp"
30 | ]
31 | classifiers = [
32 | "Development Status :: 4 - Beta",
33 | "Intended Audience :: Developers",
34 | "Topic :: Software Development :: Build Tools",
35 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
36 | "Programming Language :: Python :: 3",
37 | "Programming Language :: Python :: 3.3",
38 | "Operating System :: OS Independent"
39 | ]
40 |
41 | [project.scripts]
42 | compiledb = "compiledb.cli:cli"
43 |
44 | [project.optional-dependencies]
45 | dev = [
46 | "pytest",
47 | "coverage",
48 | "pytest-cov",
49 | "pycodestyle",
50 | "flake8",
51 | "tox"
52 | ]
53 |
54 | [project.urls]
55 | Repository = "https://github.com/nickdiego/compiledb.git"
56 | Issues = "https://github.com/nickdiego/compiledb/issues"
57 |
58 |
--------------------------------------------------------------------------------
/sh-completion/compiledb.bash:
--------------------------------------------------------------------------------
1 | eval "$(_COMPILEDB_COMPLETE=source compiledb)"
2 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nickdiego/compiledb/2550745e6d205db4d1ff92c81801d1c738bf03b1/tests/__init__.py
--------------------------------------------------------------------------------
/tests/common.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #
3 | # compiledb: Tool for generating LLVM Compilation Database
4 | # files for make-based build systems.
5 | #
6 | # Copyright (c) 2019 Nick Diego Yamane
7 | #
8 | # This program is free software; you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation; either version 2 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 | from os import path
22 |
23 | data_dir = path.abspath(path.join(path.dirname(__file__), 'data'))
24 |
25 |
26 | def full_path(relpath):
27 | return path.join(data_dir, relpath)
28 |
29 |
30 | def input_file(relpath):
31 | relpath = '{}'.format(relpath)
32 | return open(full_path(relpath), 'r')
33 |
34 |
35 | def output_file(relpath):
36 | relpath = '{}'.format(relpath)
37 | return open(full_path(relpath), 'a+')
38 |
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
--------------------------------------------------------------------------------
/tests/data/autotools_simple.txt:
--------------------------------------------------------------------------------
1 | gcc -DPACKAGE_NAME=\"hello\" -DPACKAGE_VERSION=\"1.0.0\" -DSTDC_HEADERS=1 -I. -I../../src/libhello -c -o hello_world1-main.o `test -f 'main.c' || echo './'`main.c
2 |
--------------------------------------------------------------------------------
/tests/data/compile_commands.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "file": "foo.cpp",
4 | "directory": "data",
5 | "arguments": [
6 | "g++",
7 | "foo.cpp",
8 | "-o",
9 | "foo.o"
10 | ]
11 | }
12 | ]
--------------------------------------------------------------------------------
/tests/data/compile_commands2.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "file": "bar.cpp",
4 | "directory": "data",
5 | "arguments": [
6 | "g++",
7 | "bar.cpp",
8 | "-o",
9 | "bar.o"
10 | ]
11 | }
12 | ]
--------------------------------------------------------------------------------
/tests/data/multiple_commands_oneline.txt:
--------------------------------------------------------------------------------
1 | if true; then g++ -c "./path/src/`/bin/echo -n "hein$(/bin/echo -n '.cpp')"`" -o out.o; else echo 'aeeee'; fi
2 | gcc -c -o main.o main.c || echo 'mucho loko'; if test -d fulano; then echo 'blz fera'; fi
3 |
--------------------------------------------------------------------------------
/tests/test_json_compdb.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #
3 | # compiledb: Tool for generating LLVM Compilation Database
4 | # files for make-based build systems.
5 | #
6 | # Copyright (c) 2019 Nick Diego Yamane
7 | #
8 | # This program is free software; you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation; either version 2 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 | import os
22 | import shutil
23 | import json
24 | import pytest
25 | import sys
26 | from os.path import basename
27 | from compiledb import load_json_compdb, generate
28 | from tests.common import input_file, output_file, data_dir, full_path
29 |
30 |
31 | multiple_commands_oneline_compdb = [
32 | {
33 | 'directory': os.getcwd(),
34 | 'file': './path/src/hein.cpp',
35 | 'arguments': [
36 | 'g++',
37 | '-c', './path/src/hein.cpp',
38 | '-o', 'out.o'
39 | ]
40 | },
41 | {
42 | 'directory': os.getcwd(),
43 | 'file': 'main.c',
44 | 'arguments': [
45 | 'gcc',
46 | '-c',
47 | '-o', 'main.o',
48 | 'main.c'
49 | ]
50 | }
51 | ]
52 | nonexistent_files = ['compile_commands.json', 'nonexistent.json']
53 |
54 |
55 | def test_load_compdb_path_file_exists(caplog):
56 | try:
57 | orig_pwd = os.getcwd()
58 | os.chdir(data_dir)
59 | expected_compdb = [
60 | {
61 | 'file': 'foo.cpp',
62 | 'directory': 'data',
63 | 'arguments': [
64 | 'g++',
65 | 'foo.cpp',
66 | '-o',
67 | 'foo.o'
68 | ]
69 | }
70 | ]
71 | with input_file('compile_commands.json') as outfile:
72 | assert load_json_compdb(outfile) == expected_compdb
73 | assert (
74 | 'Loaded compilation database with 1 entries from compile_commands.json'
75 | in caplog.text
76 | )
77 | finally:
78 | os.chdir(orig_pwd)
79 |
80 |
81 | def test_load_compdb_ignores_stdout_filename(caplog):
82 | assert load_json_compdb(sys.stdout) == []
83 | assert caplog.text == ''
84 |
85 |
86 | def test_generate_input_file_exists_no_overwrite(caplog):
87 | shutil.copy(full_path('compile_commands2.json'),
88 | full_path('result.json'))
89 | with output_file("result.json") as outfile:
90 | assert_generate_is_true(outfile, overwrite=False)
91 |
92 | expected_compdb = multiple_commands_oneline_compdb + [
93 | {
94 | 'file': 'bar.cpp',
95 | 'directory': 'data',
96 | 'arguments': [
97 | 'g++',
98 | 'bar.cpp',
99 | '-o',
100 | 'bar.o'
101 | ]
102 | }
103 | ]
104 | assert_compdb_file_equals(outfile.name, expected_compdb)
105 | assert 'Loaded compilation database with 1 entries from ' + basename(outfile.name) in caplog.text
106 | assert 'Writing compilation database with 3 entries to ' + basename(outfile.name) in caplog.text
107 |
108 |
109 | def test_generate_input_file_exists_overwrite(caplog):
110 | shutil.copy(full_path('compile_commands2.json'),
111 | full_path('result.json'))
112 | with output_file("result.json") as outfile:
113 | assert_generate_is_true(outfile, overwrite=True)
114 |
115 | assert_compdb_file_equals(outfile.name, multiple_commands_oneline_compdb)
116 | assert 'Loaded compilation database with 1 entries from ' + basename(outfile.name) not in caplog.text
117 | assert 'Writing compilation database with 2 entries to ' + basename(outfile.name) in caplog.text
118 |
119 |
120 | @pytest.mark.parametrize('overwrite', [False, True])
121 | def test_generate_output_stdout(capsys, caplog, overwrite):
122 | assert_generate_is_true(sys.stdout, overwrite=overwrite)
123 | assert not os.path.exists("")
124 | output = capsys.readouterr().out
125 | assert 'Writing compilation database with 2 entries to ' in caplog.text
126 |
127 | # Find where the JSON file starts and ends and decode it
128 | start_index = output.index('[')
129 | end_index = output.rindex(']') + 1
130 | compdb = json.loads(output[start_index:end_index])
131 |
132 | assert_compdb_equals(compdb, multiple_commands_oneline_compdb)
133 |
134 |
135 | def assert_generate_is_true(outstream, overwrite):
136 | with input_file('multiple_commands_oneline.txt') as instream:
137 | assert generate(
138 | infile=instream,
139 | outfile=outstream,
140 | build_dir=os.getcwd(),
141 | exclude_files=[],
142 | overwrite=overwrite,
143 | strict=False
144 | )
145 |
146 |
147 | def assert_compdb_file_equals(outfile_path, expected_compdb):
148 | try:
149 | with open(outfile_path, 'r') as instream:
150 | compdb = json.load(instream)
151 | assert_compdb_equals(compdb, expected_compdb)
152 | finally:
153 | if os.path.exists(outfile_path):
154 | os.remove(outfile_path)
155 |
156 |
157 | def assert_compdb_equals(compdb, expected_compdb):
158 | def get_key(item):
159 | return item['directory'], item['file'], item['arguments']
160 |
161 | assert sorted(compdb, key=get_key) == sorted(expected_compdb, key=get_key)
162 |
--------------------------------------------------------------------------------
/tests/test_parser.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #
3 | # compiledb: Tool for generating LLVM Compilation Database
4 | # files for make-based build systems.
5 | #
6 | # Copyright (c) 2017 Nick Diego Yamane
7 | #
8 | # This program is free software; you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation; either version 2 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 | from os import getcwd
22 |
23 | from compiledb.parser import parse_build_log
24 | from tests.common import input_file
25 |
26 |
27 | def test_empty():
28 | build_log = ''
29 | proj_dir = '/tmp'
30 | exclude_files = []
31 |
32 | result = parse_build_log(build_log, proj_dir, exclude_files)
33 | assert result.count == 0
34 | assert result.skipped == 0
35 | assert result.compdb is not None
36 | assert type(result.compdb) == list
37 | assert len(result.compdb) == 0
38 |
39 |
40 | def test_trivial_build_command():
41 | pwd = getcwd()
42 | build_log = ['gcc -o hello.o -c hello.c']
43 | result = parse_build_log(
44 | build_log,
45 | proj_dir=pwd,
46 | exclude_files=[])
47 |
48 | assert result.count == 1
49 | assert result.skipped == 0
50 | assert len(result.compdb) == 1
51 | assert result.compdb[0] == {
52 | 'directory': pwd,
53 | 'file': 'hello.c',
54 | 'arguments': ['gcc', '-o', 'hello.o', '-c', 'hello.c']
55 | }
56 |
57 |
58 | def test_build_commands_with_version():
59 | pwd = getcwd()
60 | build_log = ['clang-5.0 -o hello.o -c hello.c']
61 | result = parse_build_log(
62 | build_log,
63 | proj_dir=pwd,
64 | exclude_files=[])
65 |
66 | assert result.count == 1
67 | assert result.skipped == 0
68 | assert len(result.compdb) == 1
69 | assert result.compdb[0] == {
70 | 'directory': pwd,
71 | 'file': 'hello.c',
72 | 'arguments': ['clang-5.0', '-o', 'hello.o', '-c', 'hello.c']
73 | }
74 |
75 |
76 | def test_build_commands_with_wrapper():
77 | pwd = getcwd()
78 | build_log = [
79 | 'ccache gcc -o hello.o -c hello.c\n'
80 | 'icecc clang++ -c somefile.cpp\n'
81 | 'icecc ccache arm1999-gnu-etc-g++ -c main.cpp -o main.o\n'
82 | 'unknown-wrapper g++ -c main.cpp -o main.o\n'
83 | ]
84 | result = parse_build_log(
85 | build_log,
86 | proj_dir=pwd,
87 | exclude_files=[])
88 |
89 | assert result.count == 4
90 | assert result.skipped == 0
91 | assert len(result.compdb) == 4
92 | assert result.compdb == [{
93 | 'directory': pwd,
94 | 'file': 'hello.c',
95 | 'arguments': ['gcc', '-o', 'hello.o', '-c', 'hello.c']
96 | }, {
97 | 'directory': pwd,
98 | 'file': 'somefile.cpp',
99 | 'arguments': ['clang++', '-c', 'somefile.cpp']
100 | }, {
101 | 'directory': pwd,
102 | 'file': 'main.cpp',
103 | 'arguments': ['arm1999-gnu-etc-g++', '-c', 'main.cpp', '-o', 'main.o']
104 | }, {
105 | 'directory': pwd,
106 | 'file': 'main.cpp',
107 | 'arguments': ['g++', '-c', 'main.cpp', '-o', 'main.o']
108 | }]
109 |
110 |
111 | def test_parse_with_non_build_cmd_entries():
112 | pwd = getcwd()
113 | build_log = [
114 | 'random build log message..\n',
115 | 'gcc -c valid.c\n',
116 | 'some other random build log message with g++ or gcc included.\n',
117 | '\n',
118 | '',
119 | 'g++ -c valid2.cc\n',
120 | ]
121 | # These ones will reach the bashlex parsing code and
122 | # would generate a parsing exception
123 | # https://github.com/nickdiego/compiledb/issues/38
124 | build_log += [
125 | 'checking for gcc... (cached) gcc\n',
126 | 'checking whether gcc accepts -g... (cached) yes\n'
127 | ]
128 | result = parse_build_log(
129 | build_log,
130 | proj_dir=pwd,
131 | exclude_files=[])
132 |
133 | assert result.count == 2
134 | assert result.skipped == 6
135 | assert len(result.compdb) == 2
136 | assert result.compdb == [{
137 | 'directory': pwd,
138 | 'file': 'valid.c',
139 | 'arguments': ['gcc', '-c', 'valid.c'],
140 | }, {
141 | 'directory': pwd,
142 | 'file': 'valid2.cc',
143 | 'arguments': ['g++', '-c', 'valid2.cc']
144 | }]
145 |
146 |
147 | def test_automake_command():
148 | pwd = getcwd()
149 | with input_file('autotools_simple.txt') as build_log:
150 | result = parse_build_log(
151 | build_log,
152 | proj_dir=pwd,
153 | exclude_files=[])
154 |
155 | assert result.count == 1
156 | assert result.skipped == 0
157 | assert len(result.compdb) == 1
158 | assert result.compdb[0] == {
159 | 'directory': pwd,
160 | 'file': './main.c',
161 | 'arguments': [
162 | 'gcc',
163 | '-DPACKAGE_NAME="hello"',
164 | '-DPACKAGE_VERSION="1.0.0"',
165 | '-DSTDC_HEADERS=1',
166 | '-I.',
167 | '-I../../src/libhello',
168 | '-c',
169 | '-o', 'hello_world1-main.o',
170 | './main.c'
171 | ]
172 | }
173 |
174 |
175 | def test_multiple_commands_per_line():
176 | pwd = getcwd()
177 | with input_file('multiple_commands_oneline.txt') as build_log:
178 | result = parse_build_log(
179 | build_log,
180 | proj_dir=pwd,
181 | exclude_files=[])
182 |
183 | assert result.count == 2
184 | assert result.skipped == 0
185 | assert len(result.compdb) == 2
186 | assert result.compdb[0] == {
187 | 'directory': pwd,
188 | 'file': './path/src/hein.cpp',
189 | 'arguments': [
190 | 'g++',
191 | '-c', './path/src/hein.cpp',
192 | '-o', 'out.o'
193 | ]
194 | }
195 |
196 | def test_multiple_commands_per_line_command_style():
197 | """Test the command_style option using the multiple_commands_oneline.txt build log.
198 | """
199 | cwd = getcwd()
200 |
201 | with input_file('multiple_commands_oneline.txt') as build_log:
202 | result = parse_build_log(
203 | build_log,
204 | proj_dir=cwd,
205 | exclude_files=[],
206 | command_style=True,
207 | )
208 |
209 | assert result.count == 2
210 | assert result.skipped == 0
211 | assert result.compdb == [
212 | {
213 | 'command': 'g++ -c ./path/src/hein.cpp -o out.o',
214 | 'directory': cwd,
215 | 'file': './path/src/hein.cpp',
216 | },
217 | {
218 | 'command': 'gcc -c -o main.o main.c',
219 | 'directory': cwd,
220 | 'file': 'main.c',
221 | }
222 | ]
223 |
224 |
225 | def test_parse_file_extensions():
226 | pwd = getcwd()
227 | build_log = [
228 | 'gcc -c somefile.cpp\n'
229 | 'gcc -c main.cxx -o main.o\n'
230 | 'gcc -c main.cc -o main.o\n'
231 | 'gcc -c -o swtch.o swtch.S\n'
232 | 'gcc -c -o what.o what.s\n'
233 | ]
234 | result = parse_build_log(
235 | build_log,
236 | proj_dir=pwd,
237 | exclude_files=[])
238 |
239 | assert result.count == 5
240 | assert result.skipped == 0
241 | assert len(result.compdb) == 5
242 | assert result.compdb == [{
243 | 'directory': pwd,
244 | 'file': 'somefile.cpp',
245 | 'arguments': ['gcc', '-c', 'somefile.cpp']
246 | }, {
247 | 'directory': pwd,
248 | 'file': 'main.cxx',
249 | 'arguments': ['gcc', '-c', 'main.cxx', '-o', 'main.o']
250 | }, {
251 | 'directory': pwd,
252 | 'file': 'main.cc',
253 | 'arguments': ['gcc', '-c', 'main.cc', '-o', 'main.o']
254 | }, {
255 | 'directory': pwd,
256 | 'file': 'swtch.S',
257 | 'arguments': ['gcc', '-c', '-o', 'swtch.o', 'swtch.S']
258 | }, {
259 | 'directory': pwd,
260 | 'file': 'what.s',
261 | 'arguments': ['gcc', '-c', '-o', 'what.o', 'what.s']
262 | }]
263 |
264 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | # Tox (http://tox.testrun.org/) is a tool for running tests
2 | # in multiple virtualenvs. This configuration file will run the
3 | # test suite on all supported python versions. To use it, "pip install tox"
4 | # and then run "tox" from this directory.
5 |
6 | [tox]
7 | envlist = py311,lint
8 |
9 | [pycodestyle]
10 | ignore = E226, W504
11 | max-line-length = 120
12 | exclude = tests
13 |
14 | [pytest]
15 | testpaths = tests
16 | addopts = --junitxml=test-report.xml
17 | log_level = DEBUG
18 | log_format = %(message)s
19 | log_date_format = %Y-%m-%d %H:%M:%S
20 |
21 | [testenv]
22 | commands =
23 | py.test {posargs:tests/}
24 | deps =
25 | pytest
26 | coverage
27 | pytest-cov
28 | pycodestyle
29 | extras = all
30 |
31 | [testenv:lint]
32 | commands =
33 | pycodestyle compiledb tests
34 |
--------------------------------------------------------------------------------