├── .gitignore ├── .travis.yml ├── Changes.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── conf ├── cmake.conf ├── diff.conf ├── gcc.conf ├── make.conf └── mount.conf ├── contrib └── outproc.eselect ├── outproc ├── __init__.py ├── cli.py ├── config.py ├── cpp_helpers.py ├── logger.py ├── pp │ ├── __init__.py │ ├── c++.py │ ├── cc.py │ ├── cmake.py │ ├── diff.py │ ├── g++.py │ ├── gcc.py │ ├── make.py │ └── mount.py ├── processing.py └── term.py ├── pytest.ini ├── requirements-devel.txt ├── requirements.txt ├── setup.cfg ├── setup.py ├── test-requirements.txt └── test ├── conftest.py ├── context.py ├── data ├── SimpleCodeFormatter.test_0.expected ├── SimpleCodeFormatter.test_0.input ├── SimpleCodeFormatter.test_1.expected ├── SimpleCodeFormatter.test_1.input ├── SimpleCodeFormatter.test_10.expected ├── SimpleCodeFormatter.test_10.input ├── SimpleCodeFormatter.test_10a.expected ├── SimpleCodeFormatter.test_10a.input ├── SimpleCodeFormatter.test_10b.expected ├── SimpleCodeFormatter.test_10b.input ├── SimpleCodeFormatter.test_10c.expected ├── SimpleCodeFormatter.test_10c.input ├── SimpleCodeFormatter.test_11.expected ├── SimpleCodeFormatter.test_11.input ├── SimpleCodeFormatter.test_12.expected ├── SimpleCodeFormatter.test_12.input ├── SimpleCodeFormatter.test_2.expected ├── SimpleCodeFormatter.test_2.input ├── SimpleCodeFormatter.test_3.expected ├── SimpleCodeFormatter.test_3.input ├── SimpleCodeFormatter.test_4.expected ├── SimpleCodeFormatter.test_4.input ├── SimpleCodeFormatter.test_5.expected ├── SimpleCodeFormatter.test_5.input ├── SimpleCodeFormatter.test_6.expected ├── SimpleCodeFormatter.test_6.input ├── SimpleCodeFormatter.test_7.expected ├── SimpleCodeFormatter.test_7.input ├── SimpleCodeFormatter.test_8.expected ├── SimpleCodeFormatter.test_8.input ├── SimpleCodeFormatter.test_9.expected ├── SimpleCodeFormatter.test_9.input ├── SimpleCodeFormatter.test_9a.expected ├── SimpleCodeFormatter.test_9a.input └── sample.conf ├── test_config.py ├── test_cpp.py ├── test_gcc.py ├── test_mount.py └── test_term.py /.gitignore: -------------------------------------------------------------------------------- 1 | .*.swp 2 | *.kate-swp 3 | __pycache__ 4 | *.pyc 5 | *.egg 6 | MANIFEST 7 | dist/ 8 | outproc.egg-info/ 9 | dist/ 10 | build/ 11 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - "3.5" 5 | 6 | # command to install dependencies 7 | install: "pip install -r test-requirements.txt" 8 | # command to run tests 9 | script: pytest 10 | -------------------------------------------------------------------------------- /Changes.md: -------------------------------------------------------------------------------- 1 | Changes 2 | ======= 3 | 4 | All notable changes to this project will be documented in this file. 5 | 6 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 7 | and this project adheres to [Semantic Versioning](http://semver.org/). 8 | 9 | 10 | Version [0.20] 11 | -------------- 12 | 13 | * allow multiple parallel installations of the package. For example when 14 | one have a system-wide install and per user (into `~/.local`) maden via 15 | `pip install --editable=.` (or `./setup.py develop`). 16 | 17 | Version [0.19] 18 | -------------- 19 | 20 | * allow to put override symlinks to any location. The only requirement is 21 | that location must be the very first in `PATH`. 22 | 23 | Version [0.18] 24 | -------------- 25 | 26 | * fix exception in `cmake` processor when latter called from `make` process 27 | * since the recent KDE Frameworks 5 release, there was a strange bug, when moving 28 | cursor above to 1 line act like moving on 2 lines instead. It looks like 29 | somewhere lines count has moved to zero base or smth like this... 30 | 31 | Version [0.17] 32 | -------------- 33 | 34 | * add `-l` option to list available modules 35 | 36 | Version 0.16 37 | ------------ 38 | 39 | * break cycle dependency of `setup.py` on `termcolor` package (close #9) 40 | * fix install instructions, upload to PyPi (close #10) 41 | 42 | Version 0.14 43 | ------------ 44 | 45 | * few improvements in gcc colorizer 46 | * user may have his own configs in `~/.outproc/` to override system-wide 47 | settings from `/etc/outproc/` 48 | * support for true (16M) color terminals has been added! Now it is possible to 49 | specify `rgb(R,G,B)`, where components are numbers `0 <= N <= 255`. 50 | If all components are less than `6`, then `rgb` treated as (old) 256 color 51 | palette. Tested and work fine with KDE `konsole`. 52 | 53 | 54 | Version 0.10 55 | ------------ 56 | 57 | * `diff` module added (capable to handle unified mode only nowadays) 58 | * improve `gcc` module: handle `--help=` commands (w/ `-Q` as well) + 59 | few internal enhacements 60 | 61 | 62 | Version 0.9 63 | ----------- 64 | 65 | * make version info PEP 396 compliant 66 | * little improvements in modules: `gcc`, `cmake`, `make` 67 | 68 | 69 | Version 0.8 70 | ----------- 71 | 72 | * few improvements in `gcc` module 73 | * `make` module now can use `cmake` if found that latter running as its child 74 | * fix a 'crash' in `make` 75 | 76 | [Unreleased]: https://github.com/zaufi/pluggable-output-processor/compare/version-0.20...HEAD 77 | [0.20]: https://github.com/zaufi/pluggable-output-processor/compare/version-0.19...version-0.20 78 | [0.19]: https://github.com/zaufi/pluggable-output-processor/compare/version-0.18...version-0.19 79 | [0.18]: https://github.com/zaufi/pluggable-output-processor/compare/version-0.17...version-0.18 80 | [0.17]: https://github.com/zaufi/pluggable-output-processor/compare/version-0.16...version-0.17 81 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. {http://fsf.org/} 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 {http://www.gnu.org/licenses/}. 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 | pluggable-output-processor Copyright (C) 2013 Alex Turbov 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 | {http://www.gnu.org/licenses/}. 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 | {http://www.gnu.org/philosophy/why-not-lgpl.html}. 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include Changes.md 2 | include LICENSE 3 | include README.md 4 | 5 | include bin/* 6 | include conf/* 7 | include contrib/* 8 | 9 | recursive-include outproc *.py 10 | recursive-exclude outproc __pycache__ 11 | 12 | recursive-include test *.py 13 | recursive-include test/data * 14 | recursive-exclude . __pycache__ 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | What is This? 2 | ============= 3 | 4 | ![Travis CI](https://travis-ci.org/zaufi/pluggable-output-processor.svg?branch=master) 5 | 6 | _Pluggable Output Processor_ is an engine to wrap any executabe and capture its output through 7 | a pluggable module to colorize it and/or (re)format. 8 | 9 | 10 | Features 11 | -------- 12 | 13 | * easy (to Python programmers ;-) to extend 14 | * 256 color terminal support ;-) configuration files in addition to standard named colors 15 | may contain color definitions as `rgb(r,g,b)` or `gray(n)` 16 | * colorizers for `make`, `cmake`, `gcc` out of the box (more to come ;-) 17 | * some modules are not just a stupid colorizers ;-) For example `gcc` can reformat text for 18 | better readability (really helps to understand template errors). Also `cmake` module can reduce 19 | amount of lines printed during test by collapsing test _intro_ message and _result_ into a single one. 20 | 21 | 22 | Installation 23 | ------------ 24 | 25 | Easy! 26 | 27 | $ pip install outproc 28 | 29 | For Gentoo users there is a [live ebuild][raw-ebuild] in my [repository][my-overlay]. 30 | Also (for Gentoo users again ;-) `eselect` module from `contrib/` will be installed by the ebuild. 31 | Users of other distros have to make symlinks to required modules manually (replace `` 32 | with your actual path): 33 | 34 | $ ln -s /bin/outproc /usr/lib/outproc/bin/ 35 | 36 | and then make sure `/usr/lib/outproc/bin` placed __before__ `/usr/bin` (and anything else) in your 37 | user/system `PATH` environment. The path `/usr/lib/outproc/bin` is just an example. You can choose 38 | whatever you like instead (e.g. `/home//.local/bin/` for user based install layout). 39 | List of available modules (plugins) can be obtained from command: 40 | 41 | $ outproc -l 42 | List of available modules: 43 | c++ 44 | cc 45 | cmake 46 | diff 47 | g++ 48 | gcc 49 | make 50 | mount 51 | 52 | For example, to install the `make` module do the following: 53 | 54 | $ ln -s /bin/outproc /usr/lib/outproc/bin/make 55 | 56 | Then you may edit `/etc/outproc/make.conf` to adjust color settings. Note that `gcc`, `g++`, `cc` and `c++` 57 | are the same module actually (named after typical GCC executables) and use the same `/etc/outproc/gcc.conf` 58 | config file. 59 | 60 | [raw-ebuild]: https://github.com/zaufi/zaufi-overlay/blob/master/dev-util/pluggable-output-processor/pluggable-output-processor-scm.ebuild 61 | [my-overlay]: https://github.com/zaufi/zaufi-overlay/ "My ebuilds overlay" 62 | -------------------------------------------------------------------------------- /conf/cmake.conf: -------------------------------------------------------------------------------- 1 | # Color settings for cmake 2 | 3 | # Error strings 4 | fatal-error = red 5 | 6 | # Test success 7 | success-test = green+bold 8 | 9 | # Failed test 10 | fail-test = red+bold 11 | 12 | # When CMake running from `make` (i.e. after modifying some `CMakeLists.txt`), 13 | # assume lines started w/ double dash (aka CMake's STATUS messages') is a 14 | # CMake output, so `make` filter will use `cmake` to process this output 15 | dash-dash-is-cmake = true 16 | -------------------------------------------------------------------------------- /conf/diff.conf: -------------------------------------------------------------------------------- 1 | # Color settings for `diff` (nowadays colorize unified mode only) 2 | 3 | added = green 4 | removed = red 5 | address = cyan 6 | filename-1 = red 7 | filename-2 = green 8 | -------------------------------------------------------------------------------- /conf/gcc.conf: -------------------------------------------------------------------------------- 1 | # Settings for GNU gcc output processor 2 | 3 | # Message colors by severity level 4 | error = red 5 | warning = yellow 6 | notice = green 7 | 8 | # Source file and position 9 | location = cyan 10 | 11 | # Code snippet colors 12 | code = white 13 | code-keyword = yellow+bold 14 | code-builtin-type = red 15 | code-modifier = yellow 16 | code-std-namespace = green+bold 17 | code-boost-namespace = normal 18 | code-data-member = normal 19 | code-preprocessor = green 20 | code-numeric-literal = blue+bold 21 | code-string-literal = magenta 22 | code-comment = white 23 | code-cursor = red 24 | 25 | # Add a new line after source code snippet 26 | # NOTE The `gcc` module will remove lines w/ error position indicator ('^') 27 | # (error position will be indicated in a source line w/ a background color 28 | # specified by `code-cursor` color). As a result error messages become 29 | # slightly condensed ;-) -- So this setting allow you to control whether 30 | # a new line will be added instead of line w/ error position indicator. 31 | new-line-after-code = true 32 | 33 | # Code snippet length threshold 34 | max-code-snippet-length = 120 35 | 36 | # Colors for help screens (--help= -Q) 37 | enabled-option = bold+green 38 | disabled-option = bold+red 39 | neutral-option = normal 40 | -------------------------------------------------------------------------------- /conf/make.conf: -------------------------------------------------------------------------------- 1 | # Color settings for GNU make 2 | 3 | # Error strings 4 | error = red 5 | 6 | # `make` utility messages 7 | misc = grey+bold 8 | # Path in a make's messages 9 | misc-path = white 10 | 11 | # Recognize (some) GNU gcc command line options 12 | # NOTE Suffix here is a first letter of the option ;-) 13 | compiler-option-I = green 14 | compiler-option-D = yellow 15 | compiler-option-U = yellow 16 | compiler-option-f = cyan 17 | compiler-option-m = magenta 18 | compiler-option-W = yellow+bold 19 | compiler-option-L = green 20 | -------------------------------------------------------------------------------- /conf/mount.conf: -------------------------------------------------------------------------------- 1 | # Settings for GNU gcc output processor 2 | 3 | # Sometimes there are tool long mount points can appear 4 | # (when schroot used for example), so this setting will 5 | # limit size of too long of them. A path will be truncated 6 | # at nearest '/' 7 | mountpoint-max-size = 50 8 | 9 | # When a very long path gets trimmed, this prefix would be 10 | # added instead of leading part 11 | trim-char = ... 12 | 13 | # Color for kernel (service, not a real) filesystems 14 | kernel-fs = grey+bold 15 | 16 | # Color for real filesystems 17 | real-fs = normal 18 | 19 | # Color for network filesystems 20 | net-fs = blue+bold 21 | 22 | # Color for rebind filesystems 23 | rebind-fs = magenta 24 | 25 | # Background color for odd/even rows 26 | #odd-bg = gray(1) 27 | #even-bg = gray(2) 28 | -------------------------------------------------------------------------------- /contrib/outproc.eselect: -------------------------------------------------------------------------------- 1 | # -*-eselect-*- 2 | # 3 | # eselect module to manage `outproc` plugins 4 | # 5 | # Copyright (c) 2013 Alex Turbov 6 | # 7 | # Pluggable Output Processor is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by the 9 | # Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # Pluggable Output Processor is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 | # See the GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License along 18 | # with this program. If not, see . 19 | # 20 | 21 | DESCRIPTION="Manage plugins for Pluggable Output Processor" 22 | MAINTAINER="Alex Turbov " 23 | VERSION="0.1" 24 | 25 | ### Helper functions ### 26 | 27 | _get_outproc_modules_dir() { 28 | local -r _gomd__site=$(python -c 'import site; print(site.getsitepackages()[0])')/outproc/pp 29 | if [[ -d ${_gomd__site} ]]; then 30 | echo -n "${_gomd__site}" 31 | else 32 | die -q "Modules dir '${_gomd__site}' doesn't exist" 33 | fi 34 | } 35 | 36 | _list_outproc_modules() { 37 | local -r _lom__where=$(_get_outproc_modules_dir) 38 | local -a _lom__modules 39 | local _lom__module 40 | for _lom__module in ${_lom__where}/*; do 41 | if [[ -f ${_lom__module} ]]; then 42 | local _lom__name=$(basename ${_lom__module} '.py') 43 | if [[ "${_lom__name}.py" == "$(basename ${_lom__module})" ]]; then 44 | case ${_lom__name} in 45 | c++|cc|g++|__init__) 46 | # Ignore service modules and symlinked `gcc` duplicates 47 | ;; 48 | *) 49 | _lom__modules+=( ${_lom__name} ) 50 | ;; 51 | esac 52 | fi 53 | fi 54 | done 55 | local -r _lom__result_var=${1} 56 | eval "${_lom__result_var}=( ${_lom__modules[@]} )" 57 | } 58 | 59 | _try_remove() { 60 | local -r _tr__module_file=${1} 61 | if [[ -w $(dirname "${_tr__modulefile}") ]]; then 62 | rm "${_tr__module_file}" || die -q "Failed to remove ${_tr__module_file}" 63 | else 64 | die -q "You don't have permission to remove ${_tr__module_file}" 65 | fi 66 | } 67 | 68 | _try_symlink() { 69 | local -r _ts__dst=${1} 70 | local _ts_what=$(which --skip-alias --skip-functions outproc) 71 | local _ts_rel=$(relative_name ${_ts_what} $(dirname ${_ts__dst})) 72 | local _ts_outproc_bin=$(dirname ${_ts_rel})/outproc 73 | if [[ -w $(dirname "${_tr__dst}") ]]; then 74 | ln -s "${_ts_outproc_bin}" "${_ts__dst}" \ 75 | || die -q "Failed to make a symbolic link ${_ts_src} -> ${_ts__dst}" 76 | else 77 | die -q "You don't have permission to write to $(dirname ${_ts__dst})" 78 | fi 79 | } 80 | 81 | ### show action ### 82 | 83 | describe_show() { 84 | echo "Show current plugins enabled" 85 | } 86 | describe_show_options() { 87 | echo "--user : Show user enabled plugins (if ommited, system-wide will be shown)" 88 | } 89 | 90 | do_show() { 91 | local where=${ROOT%/}/usr/lib/outproc/bin 92 | local where_description='system-wide' 93 | if [[ "$1" == "--user" ]]; then 94 | where=${ROOT%/}/${HOME}/bin 95 | where_description='user' 96 | fi 97 | 98 | [[ ! -d ${where} ]] && die -e "No such directory: ${where}" 99 | 100 | local -a targets 101 | local module 102 | for module in ${where}/*; do 103 | if [[ -L ${module} ]]; then 104 | local name=$(basename ${module}) 105 | case ${name} in 106 | c++|cc|g++) 107 | # c++/cc/gcc is the same module -- gcc 108 | ;; 109 | *) 110 | targets+=( ${name} ) 111 | ;; 112 | esac 113 | fi 114 | done 115 | write_list_start "Installed modules (${where_description})" 116 | write_numbered_list -m "(none found)" "${targets[@]}" 117 | } 118 | 119 | ### list action ### 120 | 121 | describe_list() { 122 | echo "List plugins available" 123 | } 124 | 125 | do_list() { 126 | local -a modules 127 | _list_outproc_modules modules 128 | write_list_start "Available modules" 129 | write_numbered_list -m "(none found)" "${modules[@]}" 130 | } 131 | 132 | ### enable action ### 133 | 134 | describe_enable() { 135 | echo "Enable specified plugin(s)" 136 | } 137 | 138 | describe_enable_parameters() { 139 | echo "" 140 | } 141 | 142 | describe_enable_options() { 143 | echo "--user : Enable module at user level instead of system-wide" 144 | echo " : Module name or number (from 'list' action)" 145 | } 146 | 147 | do_enable() { 148 | local -r modules_dir=$(_get_outproc_modules_dir) 149 | local -r what=$(which --skip-alias --skip-functions outproc 2>/dev/null) 150 | [[ -z "${what}" ]] && die -q 'outproc executable not found' 151 | local where=${ROOT%/}/usr/lib/outproc/bin 152 | if [[ "$1" == "--user" ]]; then 153 | where=${ROOT%/}/${HOME}/bin 154 | shift 155 | fi 156 | 157 | [[ $# -eq 0 ]] && die -q "You didn't specify any module to enable" 158 | [[ ! -d ${where} ]] && die -e "No such directory: ${where}" 159 | [[ -w ${where} ]] || die -q "You don't have permission to write to ${where}" 160 | 161 | local -a modules 162 | _list_outproc_modules modules 163 | 164 | for module in $@; do 165 | is_number "${module}" && module=${modules[module-1]} 166 | [[ -z ${module} ]] && die "Module '${module}' doesn't appear to be valid!" 167 | local module_file="${modules_dir}/${module}.py" 168 | if [[ ! -e "${module_file}" ]]; then 169 | write_error_msg "Module '${module}' doesn't exist" 170 | continue 171 | fi 172 | # Already installed 173 | if [[ -L ${where}/${module} ]]; then 174 | write_error_msg "Module '${module}' already installed" 175 | continue 176 | fi 177 | # Symlink selected module 178 | _try_symlink ${where}/${module} 179 | # For 'gcc' module we have to remove few more symliks 180 | if [[ "${module}" == 'gcc' ]]; then 181 | _try_symlink ${where}/c++ 182 | _try_symlink ${where}/g++ 183 | _try_symlink ${where}/cc 184 | fi 185 | done 186 | } 187 | 188 | ### disable action ### 189 | 190 | describe_disable() { 191 | echo "Disable specified plugin(s)" 192 | } 193 | 194 | describe_disable_parameters() { 195 | echo "" 196 | } 197 | 198 | describe_disable_options() { 199 | echo "--user : Disable user level plugin(s)" 200 | echo " : Module name or number (from 'list' action)" 201 | } 202 | 203 | do_disable() { 204 | local where=${ROOT%/}/usr/lib/outproc/bin 205 | if [[ "$1" == "--user" ]]; then 206 | where=${ROOT%/}/${HOME}/bin 207 | shift 208 | fi 209 | 210 | [[ ! -d ${where} ]] && die -e "No such directory: ${where}" 211 | [[ $# -eq 0 ]] && die -q "You didn't specify any module to disable" 212 | 213 | local -a modules 214 | _list_outproc_modules modules 215 | 216 | for module in $@; do 217 | is_number "${module}" && module=${modules[module-1]} 218 | [[ -z ${module} ]] && die "Module '${module}' doesn't appear to be valid!" 219 | local module_file="${where}/${module}" 220 | if [[ ! -e "${module_file}" ]]; then 221 | write_error_msg "${module} is not installed" 222 | continue 223 | fi 224 | # Remove selected module 225 | _try_remove ${module_file} 226 | # For 'gcc' module we have to remove few more symliks 227 | if [[ "${module}" == 'gcc' ]]; then 228 | _try_remove ${where}/c++ 229 | _try_remove ${where}/cc 230 | _try_remove ${where}/g++ 231 | fi 232 | done 233 | } 234 | 235 | # kate: hl bash; 236 | -------------------------------------------------------------------------------- /outproc/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is a part of Pluggable Output Processor 4 | # 5 | # Copyright (c) 2013-2017 Alex Turbov 6 | # 7 | # Pluggable Output Processor is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by the 9 | # Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # Pluggable Output Processor is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 | # See the GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License along 18 | # with this program. If not, see . 19 | 20 | # Set PEP396 version attribute 21 | __version__ = '0.20' 22 | -------------------------------------------------------------------------------- /outproc/cli.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # Pluggable Output Processor (main module) 5 | # 6 | # Copyright (c) 2013-2017 Alex Turbov 7 | # 8 | # Pluggable Output Processor is free software: you can redistribute it and/or modify it 9 | # under the terms of the GNU General Public License as published by the 10 | # Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # Pluggable Output Processor is distributed in the hope that it will be useful, but 14 | # WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 16 | # See the GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License along 19 | # with this program. If not, see . 20 | 21 | 22 | # Project specific imports 23 | import outproc.pp 24 | from outproc.config import Config 25 | from outproc.logger import log 26 | from outproc.processing import Processor, report_error_with_backtrace, SYSCONFDIR 27 | 28 | # Standard imports 29 | import argparse 30 | import exitstatus 31 | import fcntl 32 | import os 33 | import pathlib 34 | import pkgutil 35 | import select 36 | import subprocess 37 | import sys 38 | import traceback 39 | 40 | 41 | class Application: 42 | 43 | def __init__(self): 44 | self.executable_name = pathlib.Path(sys.argv[0]) 45 | self.real_executable_name = self.executable_name.resolve() 46 | self.basename = self.executable_name.name 47 | self.pipe_mode = False 48 | 49 | 50 | def _handle_command_line(self): 51 | parser = argparse.ArgumentParser(description='Pluggable Output Processor') 52 | parser.add_argument( 53 | '-l' 54 | , '--list-modules' 55 | , action='store_true' 56 | , help='List available modules' 57 | ) 58 | parser.add_argument( 59 | '-m' 60 | , '--module' 61 | , metavar='NAME' 62 | , help='Choose module to process input from STDIN' 63 | ) 64 | args = parser.parse_args() 65 | 66 | self.list_modules = args.list_modules 67 | 68 | # Override module name if running as `outproc`. I.e. in a command like this: 69 | # $ /usr/bin/make 2>&1 | outproc -m make 70 | if args.module: 71 | self.basename = args.module 72 | self.pipe_mode = True 73 | 74 | 75 | def _find_wrapped_binary(self): 76 | # Try to find a wrapped executable 77 | self.binary = None 78 | for path in map(lambda p: pathlib.Path(p), os.environ['PATH'].split(os.pathsep)): 79 | binary = path / self.basename 80 | # If given binary exists and is not the same executable as the current one 81 | if binary.exists() and binary.resolve() != self.real_executable_name and 'outproc' not in binary.parts: 82 | self.binary = binary 83 | break 84 | 85 | if self.binary is None: 86 | raise RuntimeError('Command not found: {}'.format(self.basename)) 87 | 88 | 89 | def _list_pp_modules(self): 90 | modules = [name for importer, name, ispkg in pkgutil.iter_modules(outproc.pp.__path__) if ispkg == False] 91 | 92 | print('List of available modules:') 93 | for m in modules: 94 | print(' {}'.format(m)) 95 | 96 | 97 | def _load_pp_module(self): 98 | # Look for a plugin to post-process an output of the given command 99 | try: 100 | self.pp_mod = __import__( 101 | 'outproc.pp.{}'.format(self.basename) 102 | , globals() 103 | , locals() 104 | , ['outproc.pp'] 105 | ) 106 | except: 107 | raise RuntimeError('Failed to import module {}'.format(self.basename)) 108 | 109 | # Make sure the module found has a Processor class 110 | if not hasattr(self.pp_mod, 'Processor') or not issubclass(self.pp_mod.Processor, Processor): 111 | raise RuntimeError('Module {} does not provide class `Processor`'.format(self.pp_mod.__name__)) 112 | 113 | 114 | def _load_config(self, config_file_name): 115 | # Try user config file first 116 | config_file_name_full = None 117 | if 'HOME' in os.environ: 118 | config_file_name_full = pathlib.Path.home() / '.outproc' / config_file_name 119 | # If no user config, then will try a system-wide 120 | if not config_file_name_full.exists(): 121 | config_file_name_full = None 122 | 123 | # Set full config file name to the system-wide if still not inilialized 124 | if config_file_name_full is None: 125 | config_file_name_full = pathlib.Path(SYSCONFDIR) / config_file_name 126 | 127 | # Try to load configuration for selected plugin 128 | try: 129 | return Config(config_file_name_full) 130 | except: 131 | raise RuntimeError('Unable to load configuration data') 132 | 133 | 134 | def _create_output_processor(self, config): 135 | try: 136 | # Make an instance of an output processor 137 | return self.pp_mod.Processor(config, str(self.binary)) 138 | except: 139 | raise RuntimeError('Unable to make a preprocessor instance') 140 | 141 | 142 | def _make_async(self, fd): 143 | '''Switch given file descriptor to asynchronous mode''' 144 | fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK) 145 | 146 | 147 | def _start_wrapped_binary(self): 148 | try: 149 | # Execute wrapped (and found) binary 150 | return subprocess.Popen( 151 | [str(self.binary)] + sys.argv[1:] 152 | , bufsize=1 # Per line buffering 153 | , stdin=sys.stdin # TODO Need to pass input to subprocess as well 154 | , stdout=subprocess.PIPE 155 | , stderr=subprocess.STDOUT # NOTE Redirect STDERR to STDOUT 156 | , shell=False # No shell needed 157 | ) 158 | except: 159 | raise RuntimeError('Unable to start wrapped executable ({})'.format(self.binary)) 160 | 161 | 162 | def _out_lines_list(self, lines): 163 | if lines: 164 | sys.stdout.write('\n'.join(lines) + '\n') 165 | sys.stdout.flush() 166 | 167 | 168 | def run(self): 169 | # Check the binary name 170 | if self.executable_name == self.real_executable_name: 171 | self._handle_command_line() 172 | if self.list_modules: 173 | self._list_pp_modules() 174 | return exitstatus.ExitStatus.success 175 | elif self.pipe_mode: 176 | # TODO 177 | log.eerror('Pipe mode not implemented') 178 | return exitstatus.ExitStatus.failure 179 | 180 | self._find_wrapped_binary() 181 | self._load_pp_module() 182 | if not self.pp_mod.Processor.want_to_handle_current_command(): 183 | # Ok, replace self w/ wrapped executable 184 | os.execv(str(self.binary), [str(self.binary)] + sys.argv[1:]) 185 | return exitstatus.ExitStatus.failure 186 | 187 | config = self._load_config(self.pp_mod.Processor.config_file_name(self.basename)) 188 | processor = self._create_output_processor(config) 189 | process = self._start_wrapped_binary() 190 | 191 | po = select.epoll() # Make a poll object 192 | self._make_async(process.stdout) # Switch STDOUT descriptor to asynchronous mode 193 | # Register descriptor for polling 194 | po.register(process.stdout, select.EPOLLIN | select.EPOLLHUP) 195 | 196 | eof = False 197 | while not eof: 198 | # Wait for data to become available 199 | events = None 200 | while events is None: 201 | try: 202 | events = po.poll() 203 | break 204 | except InterruptedError: # Handle EAGAIN: 205 | continue # just try to poll() once again ;) 206 | 207 | # Analyze event 208 | for fileno, event in events: 209 | # Check if input available 210 | if event & select.EPOLLIN: 211 | block = process.stdout.read() # Read collected data 212 | while block is not None and block: 213 | self._out_lines_list(processor.handle_block(block)) 214 | block = process.stdout.read() # Try to read more data 215 | elif event & select.EPOLLHUP: 216 | eof = True 217 | self._out_lines_list(processor.eof()) # Notify processor about EOF 218 | else: 219 | assert False, 'Unexpected event {}'.format(event) 220 | 221 | result = None 222 | while result is None: 223 | result = process.poll() # Try to get child exit status 224 | 225 | return result 226 | 227 | 228 | def main(): 229 | try: 230 | a = Application() 231 | return a.run() 232 | 233 | except KeyboardInterrupt: 234 | return exitstatus.ExitStatus.failure 235 | 236 | except RuntimeError as ex: 237 | report_error_with_backtrace('Error: {}'.format(ex)) 238 | return exitstatus.ExitStatus.failure 239 | 240 | return exitstatus.ExitStatus.success 241 | -------------------------------------------------------------------------------- /outproc/config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is a part of Pluggable Output Processor 4 | # 5 | # Copyright (c) 2013-2017 Alex Turbov 6 | # 7 | # Pluggable Output Processor is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by the 9 | # Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # Pluggable Output Processor is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 | # See the GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License along 18 | # with this program. If not, see . 19 | 20 | import os 21 | import pathlib 22 | import re 23 | import termcolor 24 | 25 | 26 | class Config: 27 | ''' Simple configuration data accessor 28 | 29 | Every plugin may (and actually is) have a configuration data stored 30 | in a simple text file at ${prefix}/etc/outproc/. 31 | This class can read and give an access to that data in a easy to use way. 32 | ''' 33 | 34 | # TODO Use gamed groups 35 | _RGB_COLOR_SPEC_RE = re.compile('rgb\s*\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)') 36 | _RGB_HEX_COLOR_SPEC_RE = re.compile('rgb\s*\(\s*([0-9]{6})\s*\)') 37 | _GRAYSCALE_SPEC_RE = re.compile('gray\s*\(\s*([0-9]+)\s*\)') 38 | 39 | def __init__(self, filename): 40 | ''' Read configuration data from a given file ''' 41 | 42 | assert isinstance(filename, pathlib.Path) 43 | 44 | # Remember filename for future references (to show errors) 45 | self.filename = filename 46 | # Make an empty dict for configuration data 47 | self.data = {} 48 | 49 | # Set some predefined values 50 | # TODO Replace w/ `enum` 51 | class dummy: 52 | pass 53 | self.color = dummy 54 | setattr(self.color, 'normal', '\x1b[38m') 55 | setattr(self.color, 'normal_bg', '\x1b[48m') 56 | setattr(self.color, 'reset', termcolor.RESET) 57 | 58 | # NOTE Konsole terminal from KDE supports itallic font style 59 | termcolor.ATTRIBUTES['itallic'] = 3 60 | 61 | if not filename.exists(): 62 | return 63 | 64 | # Read the file line by line, and collect keys and values into an internal dict 65 | # TODO Use configparser 66 | with filename.open() as ifs: 67 | for l in ifs.readlines(): 68 | # Strip possible comment lines 69 | line_str = l.strip() 70 | if not line_str or line_str.startswith('#'): 71 | continue 72 | # Split by first '=' char 73 | key, value = [item.strip() for item in line_str.split('=', 1)] 74 | # TODO Check for duplicate keys? 75 | self.data[key] = value 76 | 77 | 78 | def get_string(self, key, default=None): 79 | ''' Get string key value or default if absent ''' 80 | assert isinstance(key, str) 81 | assert isinstance(default, str) or default is None 82 | 83 | return self.data[key] if key in self.data else default 84 | 85 | 86 | def get_int(self, key, default=None): 87 | ''' Get int key value or default if absent. 88 | Throw ValueError if not an integer. 89 | ''' 90 | assert isinstance(key, str) 91 | assert isinstance(default, int) or default is None 92 | 93 | try: 94 | return int(self.data[key]) if key in self.data else default 95 | except: 96 | raise ValueError( 97 | 'Invalid value of key `{}`: expected integer, got "{}" [{}]'. 98 | format(key, self.data[key], self.filename) 99 | ) 100 | 101 | 102 | def get_bool(self, key, default=None): 103 | ''' Get int key value or default if absent. 104 | Throw ValueError if not an integer. 105 | ''' 106 | assert isinstance(key, str) 107 | assert isinstance(default, bool) or default is None 108 | 109 | if key in self.data: 110 | value = self.data[key] 111 | if value == 'true' or value == '1': 112 | return True 113 | if value == 'false' or value == '0': 114 | return False 115 | raise ValueError( 116 | 'Invalid value of key `{}`: expected boolean, got "{}" [{}]'. 117 | format(key, value, self.filename) 118 | ) 119 | return default 120 | 121 | 122 | def get_color(self, key, default, with_reset=True): 123 | '''Get color key value or default if absent. 124 | Throw ValueError if not an integer. 125 | ''' 126 | assert isinstance(key, str) 127 | assert isinstance(default, str) or default is not None 128 | 129 | colors = [c.strip() for c in (self.data[key] if key in self.data else default).split('+')] 130 | result = '' 131 | 132 | # Handle special value 'none' as color inhibitor 133 | if 'none' in colors: 134 | return result 135 | 136 | if with_reset: 137 | result = '\x1b[0m' 138 | 139 | for c in colors: 140 | # 141 | result += '\x1b[' 142 | # 143 | if c == 'reset': 144 | result += '0' 145 | elif c == 'normal': 146 | result += '38' 147 | elif c in termcolor.COLORS: 148 | result += str(termcolor.COLORS[c]) 149 | elif c in termcolor.ATTRIBUTES: 150 | result += str(termcolor.ATTRIBUTES[c]) 151 | elif c in termcolor.HIGHLIGHTS: 152 | result += str(termcolor.HIGHLIGHTS[c]) 153 | elif self._RGB_COLOR_SPEC_RE.match(c): 154 | # BUG Fucking Python! Why not to assign and check a variable inside of `if` 155 | # TODO Avoid double regex match 156 | match = self._RGB_COLOR_SPEC_RE.search(c) 157 | try: 158 | r = self._validate_rgb_component(int(match.group(1))) 159 | g = self._validate_rgb_component(int(match.group(2))) 160 | b = self._validate_rgb_component(int(match.group(3))) 161 | if r <= 5 and g <= 5 and b <= 5: 162 | index = self._rgb_to_index(r, g, b) 163 | result += '38;5;' + str(index) 164 | else: 165 | result += '38;2;{};{};{}'.format(r, g, b) 166 | except ValueError: 167 | raise RuntimeError( 168 | 'Invalid value of key `{}`: invalid RGB color specification "{}" [{}]'. 169 | format(key, c, self.filename) 170 | ) 171 | elif self._GRAYSCALE_SPEC_RE.match(c): 172 | # BUG Fucking Python! Why not to assign and check a variable inside of `if` 173 | # TODO Avoid double regex match 174 | match = self._GRAYSCALE_SPEC_RE.search(c) 175 | try: 176 | g = self._validate_grayscale(int(match.group(1))) 177 | index = self._grayscale_to_index(g) 178 | result += '38;5;' + str(index) 179 | except ValueError: 180 | raise RuntimeError( 181 | 'Invalid value of key `{}`: invalid grayscale color specification "{}" [{}]'. 182 | format(key, c, self.filename) 183 | ) 184 | else: 185 | try: 186 | index = int(c) 187 | if 15 < index and index < 256: 188 | result += '38;5;' + c 189 | except ValueError: 190 | raise RuntimeError( 191 | 'Invalid value of key `{}`: expected color specification, got "{}" [{}]'. 192 | format(key, c, self.filename) 193 | ) 194 | # Form the partial result 195 | result += 'm' 196 | return result 197 | 198 | 199 | def _validate_rgb_component(self, c): 200 | assert isinstance(c, int) 201 | if c < 0 or 255 < c: 202 | raise ValueError('RGB component is out of range') 203 | return c 204 | 205 | 206 | def _rgb_to_index(self, r, g, b): 207 | return r * 36 + g * 6 + b + 16 208 | 209 | 210 | def _validate_grayscale(self, c): 211 | assert isinstance(c, int) 212 | if c < 0 or 24 < c: 213 | raise ValueError('Grayscale index is out of range') 214 | return c 215 | 216 | 217 | def _grayscale_to_index(self, g): 218 | assert (232 + g) < 256 219 | return 232 + g 220 | -------------------------------------------------------------------------------- /outproc/cpp_helpers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is a part of Pluggable Output Processor 4 | # 5 | # Copyright (c) 2013-2017 Alex Turbov 6 | # 7 | # Pluggable Output Processor is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by the 9 | # Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # Pluggable Output Processor is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 | # See the GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License along 18 | # with this program. If not, see . 19 | 20 | import collections 21 | import re 22 | import os 23 | import termcolor 24 | 25 | 26 | class SimpleCppLexer(object): 27 | ''' Helper class to get C++ lexems to be highlighted''' 28 | 29 | _IDENTIFIER_RE = re.compile('[A-Za-z_][A-Za-z_0-9]*') 30 | # TODO A real expression to match numbers is much more complicated! 31 | # (and not so naive/stupid) Do we really need it? This one covers 32 | # most seen cases... 33 | _NUMBER_RE = re.compile('^(\d+(\.\d*)?(f|[uU]?[lL]{0,2})?)$') 34 | _STRING_RE = re.compile('(.*?)(("[^"]*)("(.*))?)') 35 | 36 | _KEYWORDS = [ 37 | 'alignof' 38 | , 'alignas' 39 | , 'asm' 40 | , 'auto' 41 | , 'break' 42 | , 'case' 43 | , 'catch' 44 | , 'class' 45 | , 'const_cast' 46 | , 'constexpr' 47 | , 'continue' 48 | , 'decltype' 49 | , 'default' 50 | , 'delete' 51 | , 'do' 52 | , 'dynamic_cast' 53 | , 'else' 54 | , 'enum' 55 | , 'explicit' 56 | , 'export' 57 | , 'false' 58 | , 'final' 59 | , 'for' 60 | , 'friend' 61 | , 'goto' 62 | , 'if' 63 | , 'inline' 64 | , 'namespace' 65 | , 'new' 66 | , 'noexcept' 67 | , 'nullptr' 68 | , 'operator' 69 | , 'override' 70 | , 'private' 71 | , 'protected' 72 | , 'public' 73 | , 'register' 74 | , 'reinterpret_cast' 75 | , 'return' 76 | , 'sizeof' 77 | , 'static_assert' 78 | , 'static_cast' 79 | , 'struct' 80 | , 'switch' 81 | , 'template' 82 | , 'this' 83 | , 'throw' 84 | , 'true' 85 | , 'try' 86 | , 'typedef' 87 | , 'typeid' 88 | , 'typename' 89 | , 'union' 90 | , 'using' 91 | , 'virtual' 92 | , 'while' 93 | ] 94 | 95 | _MODIFIERS = [ 96 | 'static' 97 | , 'thread_local' 98 | , 'extern' 99 | , 'const' 100 | , 'volatile' 101 | , 'mutable' 102 | ] 103 | 104 | _DATA_TYPES = [ 105 | 'bool' 106 | , 'char' 107 | , 'short' 108 | , 'int' 109 | , 'unsigned' 110 | , 'signed' 111 | , 'long' 112 | , 'float' 113 | , 'double' 114 | , 'char16_t' 115 | , 'char32_t' 116 | , 'wchar_t' 117 | , 'void' 118 | ] 119 | 120 | _STRING_PREFIXES = ['u', 'U', 'L', 'u8', 'R', 'uR', 'UR', 'u8R', 'LR'] 121 | 122 | class Token: 123 | BUILTIN_TYPE = 0 124 | IDENTIFIER = 1 125 | KEYWORD = 2 126 | MODIFIER = 3 127 | PREPROCESSOR = 4 128 | STRING_LITERAL = 5 129 | NUMERIC_LITERAL = 6 130 | COMMENT = 7 131 | UNCATEGORIZED = -1 132 | 133 | __KIND_STRINGS = { 134 | BUILTIN_TYPE: 'BT' 135 | , IDENTIFIER: 'ID' 136 | , KEYWORD: 'KW' 137 | , MODIFIER: 'MOD' 138 | , PREPROCESSOR: '#' 139 | , STRING_LITERAL: 'ST' 140 | , NUMERIC_LITERAL: 'NUM' 141 | , COMMENT: 'CMNT' 142 | , UNCATEGORIZED: 'UC' 143 | } 144 | 145 | def __init__(self, token, kind): 146 | self.token = token 147 | self.kind = kind 148 | 149 | def __repr__(self): 150 | return "{}('{}')".format(self.__KIND_STRINGS[self.kind], self.token) 151 | 152 | 153 | @staticmethod 154 | def _categorize_token(tok, prev_token): 155 | #print('tok={}'.format(repr(tok))) 156 | token = None 157 | replace_prev = False 158 | # Handle keywords 159 | if tok in SimpleCppLexer._KEYWORDS: 160 | token = SimpleCppLexer.Token(tok, SimpleCppLexer.Token.KEYWORD) 161 | # Handle type modifiers 162 | elif tok in SimpleCppLexer._MODIFIERS: 163 | token = SimpleCppLexer.Token(tok, SimpleCppLexer.Token.MODIFIER) 164 | # Handle builtin data types 165 | elif tok in SimpleCppLexer._DATA_TYPES: 166 | token = SimpleCppLexer.Token(tok, SimpleCppLexer.Token.BUILTIN_TYPE) 167 | # Join scope access to a previous token if latter is identifier 168 | elif tok == '::' and prev_token and prev_token.kind == SimpleCppLexer.Token.IDENTIFIER: 169 | token = prev_token 170 | token.token += tok 171 | replace_prev = True 172 | elif SimpleCppLexer._NUMBER_RE.match(tok): 173 | token = SimpleCppLexer.Token(tok, SimpleCppLexer.Token.NUMERIC_LITERAL) 174 | elif SimpleCppLexer._IDENTIFIER_RE.match(tok): 175 | if prev_token and prev_token.kind == SimpleCppLexer.Token.IDENTIFIER: 176 | token = prev_token 177 | token.token += tok 178 | replace_prev = True 179 | elif prev_token and prev_token.kind == SimpleCppLexer.Token.STRING_LITERAL: 180 | token = prev_token 181 | token.token += tok 182 | replace_prev = True 183 | else: 184 | token = SimpleCppLexer.Token(tok, SimpleCppLexer.Token.IDENTIFIER) 185 | else: 186 | token = SimpleCppLexer.Token(tok, SimpleCppLexer.Token.UNCATEGORIZED) 187 | return (token, replace_prev) 188 | 189 | 190 | @staticmethod 191 | def tokenize_string(snippet): 192 | tokens = [] 193 | 194 | # If first char on a line is '#' -- whole string is a preprocessor 195 | if snippet.lstrip().startswith('#'): 196 | tokens.append(SimpleCppLexer.Token(snippet, SimpleCppLexer.Token.PREPROCESSOR)) 197 | return tokens 198 | 199 | in_string = False 200 | in_block_comment = False 201 | in_cpp_comment = False 202 | string_char = None 203 | #print("tokens={}".format(repr(re.split('(\W+)', snippet)))) 204 | for tok in re.split('(\W+)', snippet): # Split the whole snippet by elementary tokens 205 | if not tok: # Last item can be empty 206 | continue # Just skip it! 207 | 208 | # If we r in a C++ style comment... 209 | if in_cpp_comment: 210 | # Just merge everything till the end to a previous token 211 | assert tokens[-1].kind == SimpleCppLexer.Token.COMMENT 212 | tokens[-1].token += tok 213 | continue 214 | 215 | # Iterate over tokenized string and look for 216 | # quotes (string literals) and comments... 217 | last_tokenized_pos = 0 218 | seen_slash = False 219 | seen_star = False 220 | seen_backslash = False 221 | want_next = False 222 | for pos, c in enumerate(tok): 223 | assert not in_cpp_comment 224 | if seen_backslash: # Go to next char after backclash 225 | seen_backslash = False # Ok, backslash was counted... 226 | continue 227 | elif in_string: 228 | assert string_char and not seen_slash and not seen_star 229 | # Ok, we r at string now... Check if current char is a quote symbol 230 | # Check if string ends... 231 | if c == string_char: 232 | assert tokens 233 | # Join chars before (including a current) to a prev token 234 | tokens[-1].token += tok[last_tokenized_pos:pos+1] 235 | in_string = False # Drop the flag! 236 | last_tokenized_pos = pos + 1 237 | elif c == '\\': 238 | seen_backslash = True 239 | elif in_block_comment: 240 | if seen_star and c == '/': # Is end of block comment? 241 | in_block_comment = False # Drop the flag! 242 | assert tokens 243 | tokens[-1].token += tok[last_tokenized_pos:pos+1] 244 | last_tokenized_pos = pos + 1 245 | seen_star = bool(c == '*') 246 | # Starting a block or C++ style comment? 247 | elif seen_slash and (c == '/' or c == '*'): 248 | if c == '/': 249 | in_cpp_comment = True 250 | else: 251 | in_block_comment = True 252 | # Append anything before it as a separate token 253 | before = None 254 | if 0 < (pos - 1): # Is this not a token start? 255 | before = tok[last_tokenized_pos:pos-1] 256 | if before: 257 | token, replace_prev = SimpleCppLexer._categorize_token( 258 | before 259 | , tokens[-1] if tokens else None 260 | ) 261 | if replace_prev: 262 | tokens[-1] = token 263 | else: 264 | tokens.append(token) 265 | if in_cpp_comment: 266 | comment_start_text = tok[pos-1:] 267 | else: 268 | comment_start_text = tok[pos-1:pos+1] 269 | last_tokenized_pos = pos+1 270 | tokens.append(SimpleCppLexer.Token(comment_start_text, SimpleCppLexer.Token.COMMENT)) 271 | if in_cpp_comment: # C++ comments do not require further parsing... 272 | want_next = True # Order to go for next token after this loop 273 | break # immediately! 274 | elif c == '"' or c == "'": 275 | in_string = True 276 | string_char = c 277 | # Append anything before it as a separate token 278 | before = None 279 | if 0 < pos: # Is this not a token start? 280 | before = tok[last_tokenized_pos:pos] 281 | if before: 282 | token, replace_prev = SimpleCppLexer._categorize_token( 283 | before 284 | , tokens[-1] if tokens else None 285 | ) 286 | if replace_prev: 287 | tokens[-1] = token 288 | else: 289 | tokens.append(token) 290 | switch_prev_token = tokens \ 291 | and tokens[-1].kind == SimpleCppLexer.Token.IDENTIFIER \ 292 | and tokens[-1].token in SimpleCppLexer._STRING_PREFIXES 293 | if switch_prev_token: 294 | tokens[-1].kind = SimpleCppLexer.Token.STRING_LITERAL 295 | tokens[-1].token += c 296 | else: 297 | tokens.append(SimpleCppLexer.Token(c, SimpleCppLexer.Token.STRING_LITERAL)) 298 | last_tokenized_pos = pos+1 299 | else: 300 | seen_slash = bool(c == '/') 301 | seen_backslash = bool(c == '\\') 302 | seen_star = bool(c == '*') 303 | 304 | if want_next: # If we are at C++ style comment 305 | continue # Go for next tokens immediately 306 | 307 | assert not in_cpp_comment 308 | if in_block_comment: 309 | assert tokens and tokens[-1].kind == SimpleCppLexer.Token.COMMENT 310 | tokens[-1].token += tok[last_tokenized_pos:len(tok)] 311 | elif in_string: 312 | assert tokens and tokens[-1].kind == SimpleCppLexer.Token.STRING_LITERAL 313 | tokens[-1].token += tok[last_tokenized_pos:len(tok)] 314 | elif tok[last_tokenized_pos:len(tok)]: 315 | token, replace_prev = SimpleCppLexer._categorize_token( 316 | tok[last_tokenized_pos:len(tok)] 317 | , tokens[-1] if tokens else None 318 | ) 319 | if replace_prev: 320 | assert tokens 321 | tokens[-1] = token 322 | else: 323 | tokens.append(token) 324 | return tokens 325 | 326 | @staticmethod 327 | def assemble_statement(tokens): 328 | return ''.join([t.token for t in tokens]) 329 | 330 | 331 | 332 | _BOOST_VARIANT_DETAILS_SNTZ_RE = re.compile('(T[0-9_]+)( = boost::detail::variant::void_);( T[0-9_]+\\2;)* (T[0-9_]+)\\2(;)?') 333 | _BOOST_TAIL_OF_SOME_DETAILS_SNTZ_RE = re.compile('(, (boost::detail::variant::void_|mpl_::na))*>') 334 | _GENERATED_TEMPLATE_PARAMS_SNTZ_RE = re.compile('((, )?((class|typename) )?(([A-Z][a-z_]*)([0-9]+)))') 335 | _STD_DEFAULT_ALLOCATORS_SNTZ_RE = re.compile('std::(deque|(forward_)?list|vector)<(.*), std::allocator<\\3>\s*>') 336 | _STD_PLACEHOLDER = 'std::_Placeholder<' 337 | _STD_PLACEHOLDERS_NS = 'std::placeholders::_' 338 | _PARAMETER_PACK = ' ...' 339 | # NOTE Order is important! 340 | _BUILTIN_DATA_TYPES_MAPPING = [ 341 | ('long unsigned int', 'unsigned long') 342 | , ('long int', 'long') 343 | , ('short int', 'short') 344 | , ('short unsigned int', 'unsigned short') 345 | , ('unsigned int', 'unsigned') 346 | , ('std::basic_string', 'std::string') 347 | ] 348 | 349 | 350 | class SnippetSanitizer(object): 351 | 352 | def _boost_variant_details_cleaner(snippet): 353 | ''' 354 | `Tn = boost::detail::variant::void_' parameters expansion inside of `[with' 355 | ''' 356 | match = _BOOST_VARIANT_DETAILS_SNTZ_RE.search(snippet) 357 | if match: 358 | snippet = snippet[:match.start()] \ 359 | + '{} to {}{}{}'.format(match.group(1), match.group(4), match.group(2), match.group(5)) \ 360 | + snippet[match.end():] 361 | return snippet 362 | 363 | 364 | def _boost_remove_tail_of_some_details(snippet): 365 | return re.sub(_BOOST_TAIL_OF_SOME_DETAILS_SNTZ_RE, '>', snippet) 366 | 367 | 368 | def _flush_collected_params(stack, start, snippet): 369 | assert 0 < len(stack) 370 | 371 | result = '' 372 | # Append leading slice 373 | result += snippet[start:stack[0].end()] 374 | 375 | if len(stack) == 1: # In case of the only item in stack 376 | return result # Nothing to do anymore 377 | 378 | if 2 < len(stack): # If there is more than 2 matches 379 | result += ', ...' 380 | 381 | # Append trail slice 382 | result += snippet[stack[-1].start():stack[-1].end()] 383 | 384 | return result 385 | 386 | 387 | def _generated_template_params_cleaner(snippet): 388 | ''' 389 | `class Tn, ..., class Tm' template parameters 390 | ''' 391 | start = 0 392 | stack = [] 393 | has_at_least_one_match = False 394 | result = '' 395 | for match in _GENERATED_TEMPLATE_PARAMS_SNTZ_RE.finditer(snippet): 396 | has_at_least_one_match = True 397 | # Check if 'flush' required 398 | flush_needed = len(stack) \ 399 | and (\ 400 | match.group(4) != stack[-1].group(4) \ 401 | or match.group(6) != stack[-1].group(6) \ 402 | or (int(match.group(7)) - int(stack[-1].group(7))) != 1 \ 403 | ) 404 | 405 | if not flush_needed: # If no flush needed, 406 | stack.append(match) # just append this item 407 | continue # and continue w/ a next match 408 | 409 | result += SnippetSanitizer._flush_collected_params(stack, start, snippet) 410 | 411 | start = stack[-1].end() 412 | stack = [match] 413 | 414 | if not has_at_least_one_match: 415 | return snippet 416 | 417 | result += SnippetSanitizer._flush_collected_params(stack, start, snippet) 418 | result += snippet[stack[-1].end():] 419 | 420 | return result 421 | 422 | 423 | def _template_decl_fixer_1(snippet): 424 | # TODO How to replace `class' w/ `typename'? All occurrences ... 425 | return snippet.replace('template', idx) 447 | assert close_pos != -1 448 | snippet = snippet[:idx] \ 449 | + _STD_PLACEHOLDERS_NS \ 450 | + snippet[idx+len(_STD_PLACEHOLDER):close_pos] \ 451 | + snippet[close_pos+1:] 452 | idx = snippet.find(_STD_PLACEHOLDER, idx + len(_STD_PLACEHOLDERS_NS)) 453 | return snippet 454 | 455 | 456 | def _squeeze_right_angle_brackets(snippet): 457 | # Squeeze closing angle brackets 458 | pos = snippet.find('> >') 459 | while pos != -1: 460 | snippet = snippet[:pos] + '>>' + snippet[pos+3:] 461 | pos = snippet.find('> >', pos + 1) 462 | return snippet 463 | 464 | 465 | def _simplify_some_data_types(snippet): 466 | for what, to in _BUILTIN_DATA_TYPES_MAPPING: 467 | snippet = snippet.replace(what, to) 468 | return snippet 469 | 470 | 471 | def _remove_defaulted_params_from_std_types(snippet): 472 | result = snippet 473 | match = _STD_DEFAULT_ALLOCATORS_SNTZ_RE.search(result) 474 | has_at_least_one_match = False 475 | while match: 476 | assert len(match.groups()) == 3 477 | has_at_least_one_match = True 478 | 479 | result = result[0:match.start()] + 'std::' + match.group(1) + '<' + match.group(3) + '>' + result[match.end():] 480 | match = _STD_DEFAULT_ALLOCATORS_SNTZ_RE.search(result) 481 | 482 | if not has_at_least_one_match: 483 | return snippet 484 | 485 | return result 486 | 487 | 488 | _SANITIZERS = [ 489 | _boost_variant_details_cleaner 490 | , _boost_remove_tail_of_some_details 491 | , _generated_template_params_cleaner 492 | , _template_decl_fixer_1 493 | , _parameters_pack_fixer 494 | , _hide_some_std_details 495 | , _squeeze_right_angle_brackets 496 | , _simplify_some_data_types 497 | , _remove_defaulted_params_from_std_types 498 | ] 499 | 500 | 501 | @staticmethod 502 | def cleanup_snippet(snippet): 503 | for sanitizer in SnippetSanitizer._SANITIZERS: 504 | snippet = sanitizer(snippet) 505 | return snippet 506 | 507 | 508 | RangeItem = collections.namedtuple('RangeItem', ['close_char', 'split_points', 'children']) 509 | 510 | class CodeFormatter(object): 511 | 512 | TAB_SIZE = 4 513 | 514 | def __init__(self, max_width): 515 | self.max_width = max_width 516 | 517 | 518 | def pretty_format(self, snippet): 519 | 520 | # NOTE Expand TABs to 4 spaces (just to be sure) 521 | snippet = snippet.replace('\t', self.TAB_SIZE * ' ') 522 | 523 | if self.max_width < len(snippet): 524 | return '\n'.join(self._format_line(snippet)) 525 | 526 | return snippet 527 | 528 | 529 | def _indent_size(self, level, **kwargs): 530 | first = None 531 | if 'first' in kwargs: 532 | first = bool(kwargs['first']) 533 | elif 'first_char' in kwargs: 534 | first = kwargs['first_char'] not in ',>)' 535 | 536 | if first is None: 537 | first = True 538 | 539 | if first: 540 | indent = self.TAB_SIZE * (level) 541 | else: 542 | if level: 543 | indent = self.TAB_SIZE * (level - 1) + int(self.TAB_SIZE / 2) 544 | else: 545 | indent = int(self.TAB_SIZE / 2) 546 | return indent 547 | 548 | 549 | def _indentation(self, level, **kwargs): 550 | return self._indent_size(level, **kwargs) * ' ' 551 | 552 | 553 | def _format_line(self, line): 554 | 555 | #print('\nline="{}"\n'.format(repr(line))) 556 | 557 | prev_char_is_space = False 558 | ranges = [] 559 | stack = [] 560 | 561 | # TODO Detect unbalanced brackets? 562 | # TODO Detect operator<< 563 | for i, c in enumerate(line): 564 | #print('{}: c={}'.format(i, repr(c))) 565 | 566 | if c == ' ': 567 | prev_char_is_space = True 568 | continue 569 | 570 | prev_char_is_space = False 571 | 572 | if c == '(': 573 | stack.append(RangeItem(')', [i + 1], [])) 574 | #print('{} open={}'.format(repr(i), c)) 575 | 576 | elif c == '<' and not prev_char_is_space: 577 | stack.append(RangeItem('>', [i + 1], [])) 578 | #print('{} open={}'.format(repr(i), c)) 579 | 580 | elif 0 < len(stack) and c == ',': 581 | stack[-1].split_points.append(i) 582 | #print('{} comma={}'.format(repr(i), c)) 583 | 584 | elif 0 < len(stack) and c == stack[-1].close_char: 585 | last_item = stack[-1] 586 | stack.pop() 587 | last_item.split_points.append(i) 588 | #print('last_item={}'.format(repr(last_item))) 589 | # No need to split anything if range is empty -- i.e. there was nothing between brackets 590 | if last_item.split_points[0] != last_item.split_points[-1]: 591 | if 0 < len(stack): 592 | stack[-1].children.append(last_item) 593 | else: 594 | ranges.append(last_item) 595 | #print('{} close={}'.format(repr(i), c)) 596 | 597 | # No way has found to format this line or unbalanced brackets 598 | if not len(ranges) or len(stack) != 0: 599 | return [line] 600 | 601 | root = RangeItem(None, [0, len(line)], ranges) 602 | #print('Ranges after analyze: {}'.format(repr(root))) 603 | #print('') 604 | 605 | result = self._tree_walk_and_slice(root, 0, line) 606 | #print('result={}'.format(repr(result))) 607 | return result 608 | 609 | 610 | def _tree_walk_and_slice(self, node, level, line): 611 | # Is there any split points? 612 | if not len(node.split_points): 613 | #print('tw{}: {}no split points -- nothing to do'.format(level, _indentation(level, first=True))) 614 | return [line] 615 | 616 | # At least 2 split points expected 617 | assert 1 < len(node.split_points) 618 | 619 | 620 | # Iterate over slices 621 | result = [] 622 | start = node.split_points[0] 623 | for pos in node.split_points[1:]: 624 | #print('tw{}: {}consider range ({}, {}): "{}"'.format(level, self._indentation(level, first=True), start, pos, line[start:pos])) 625 | # Check if current slice can fit into bounds 626 | if self.max_width < (pos - start + self._indent_size(level, firstChar=line[start])): 627 | # Huh, need to slice current range... 628 | #print('tw{}: {}range does not fit: trying subranges'.format(level, self._indentation(level, first=True))) 629 | # Is there any child node? 630 | if len(node.children): 631 | # Yep, walk through and find a suitable subrange 632 | found = None 633 | found_idx = 0 634 | for found_idx, child in enumerate(node.children): 635 | cstart = child.split_points[0] 636 | for cend in child.split_points[1:]: 637 | if start < cstart and cend < pos: 638 | found = child 639 | #assert (found.level - level) == 1 640 | assert 1 < len(found.split_points) 641 | break 642 | if found is not None: 643 | break 644 | 645 | if found is not None: 646 | #print('found_idx={}'.format(repr(found_idx))) 647 | #print('tw{}: {}found subrange: {}'.format(level, self._indentation(level, first=True), found)) 648 | #print('tw{}: {}append leading subrange ({}, {}): "{}"'.format(level, self._indentation(level, first=True), start, found.split_points[0], line[start:found.split_points[0]])) 649 | result.append(self._indentation(level, first_char=line[start]) + line[start:found.split_points[0]]) 650 | result += self._tree_walk_and_slice(found, level + 1, line) 651 | 652 | #print('tw{}: {}form a trail recursively ({}, {}): "{}"'.format(level, self._indentation(level, first=True), found.split_points[-1], pos, line[found.split_points[-1]:pos])) 653 | new_start = found.split_points[-1] 654 | new_end = pos 655 | new_level = level + 1#int(line[new_start] not in ',>)') 656 | result += self._tree_walk_and_slice(RangeItem(None, [new_start, new_end], node.children[found_idx + 1:]), new_level, line) 657 | #result.append(self._indentation(level + 1, first_char=line[]) + line[found.split_points[-1]:pos]) 658 | else: 659 | result.append(self._indentation(level, first_char=line[start]) + line[start:pos]) 660 | else: 661 | # We can do nothing if there is nothing to split by... 662 | result.append(self._indentation(level, first_char=line[start]) + line[start:pos]) 663 | #print('tw{}: {}no children'.format(level, self._indentation(level, first=True))) 664 | else: 665 | # Yes, it can 666 | result.append(self._indentation(level, first_char=line[start]) + line[start:pos]) 667 | #print('tw{}: {}range fits well'.format(level, self._indentation(level, first=True))) 668 | 669 | start = pos 670 | 671 | return result 672 | -------------------------------------------------------------------------------- /outproc/logger.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is a part of Pluggable Output Processor 4 | # 5 | # Copyright (c) 2013-2017 Alex Turbov 6 | # 7 | # Pluggable Output Processor is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by the 9 | # Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # Pluggable Output Processor is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 | # See the GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License along 18 | # with this program. If not, see . 19 | 20 | # Project specific imports 21 | 22 | # Standard imports 23 | import sys 24 | 25 | log = None 26 | try: 27 | import portage.output 28 | log = portage.output.EOutput() 29 | except ImportError: 30 | class FakeLogger(object): 31 | def einfo(self, msg): 32 | print(' \x1b[0;32;1m*\x1b[0m {}'.format(msg)) 33 | def eerror(self, msg): 34 | print(' \x1b[0;31;1m*\x1b[0m {}'.format(msg), file=sys.stderr) 35 | def ewarn(self, msg): 36 | print(' \x1b[0;33;1m*\x1b[0m {}'.format(msg)) 37 | 38 | log = FakeLogger() 39 | -------------------------------------------------------------------------------- /outproc/pp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zaufi/pluggable-output-processor/12714c66b3727126df575a55e7a7684b41f4b3bc/outproc/pp/__init__.py -------------------------------------------------------------------------------- /outproc/pp/c++.py: -------------------------------------------------------------------------------- 1 | /usr/lib64/python3.6/site-packages/outproc/pp/gcc.py -------------------------------------------------------------------------------- /outproc/pp/cc.py: -------------------------------------------------------------------------------- 1 | /usr/lib64/python3.6/site-packages/outproc/pp/gcc.py -------------------------------------------------------------------------------- /outproc/pp/cmake.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Output processor for `cmake` 4 | # 5 | # Copyright (c) 2013-2017 Alex Turbov 6 | # 7 | # Pluggable Output Processor is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by the 9 | # Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # Pluggable Output Processor is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 | # See the GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License along 18 | # with this program. If not, see . 19 | # 20 | 21 | from ..processing import Processor as ProcessorBase 22 | from ..term import move_above, get_size 23 | 24 | import os 25 | import re 26 | import shlex 27 | 28 | 29 | _SUCCESS_RE = re.compile('^-- (Check|Looking|Performing (.*)?Test|Detecting).*-{1,2} (works|done|yes|found|[Ss]uccess)$') 30 | _SUCCESS2_RE = re.compile('^-- Found .*:\s.*$') 31 | _FAILURE_RE = re.compile('^-- .* -{1,2} (no|not found|[Ff]ailed|NOTFOUND)$') 32 | _FATAL_RE = re.compile('^CMake Error.*') 33 | 34 | 35 | class Processor(ProcessorBase): 36 | 37 | def __init__(self, config, binary): 38 | super().__init__(config, binary) 39 | self.success = config.get_color('success-test', 'green+bold') 40 | self.failure = config.get_color('fail-test', 'red+bold') 41 | self.fatal = config.get_color('fatal-error', 'red+bold') 42 | self.relaxed = config.get_bool('dash-dash-is-cmake', True) 43 | self.prev_line = None 44 | 45 | 46 | def _colorize(self, color, line): 47 | return color + line + self.config.color.reset 48 | 49 | 50 | def looks_like_cmake_line(self, line): 51 | return self.relaxed and line.startswith('-- ') \ 52 | or _SUCCESS_RE.match(line) \ 53 | or _SUCCESS2_RE.match(line) \ 54 | or _FAILURE_RE.match(line) \ 55 | or _FATAL_RE.match(line) 56 | 57 | 58 | def handle_line(self, line): 59 | move_code = '' 60 | if self.prev_line is not None and line.startswith(self.prev_line): 61 | # The line above is a begining of some test and here (in the `line`) a result of it 62 | # Move cursor to one line up and override it! 63 | lines = int(len(self.prev_line) / get_size()[1]) 64 | move_code = move_above(lines) 65 | self.prev_line = line.strip() 66 | if _SUCCESS_RE.match(line) or _SUCCESS2_RE.match(line): 67 | return self._colorize(move_code + self.success, line) 68 | if _FAILURE_RE.match(line): 69 | return self._colorize(move_code + self.failure, line) 70 | if _FATAL_RE.match(line): 71 | return self._colorize(move_code + self.fatal, line) 72 | return line 73 | -------------------------------------------------------------------------------- /outproc/pp/diff.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Output processor for `diff` 4 | # 5 | # Copyright (c) 2013-2017 Alex Turbov 6 | # 7 | # Pluggable Output Processor is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by the 9 | # Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # Pluggable Output Processor is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 | # See the GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License along 18 | # with this program. If not, see . 19 | # 20 | 21 | from ..processing import Processor as ProcessorBase, force_processing, force_processing_requested 22 | 23 | import os 24 | import re 25 | import sys 26 | 27 | 28 | class Processor(ProcessorBase): 29 | 30 | @staticmethod 31 | def _remove_color_options(): 32 | if '--color=always' in sys.argv: 33 | del sys.argv[sys.argv.index('--color=always')] 34 | if '--color=no' in sys.argv: 35 | del sys.argv[sys.argv.index('--color=no')] 36 | 37 | @staticmethod 38 | def want_to_handle_current_command(): 39 | result = False 40 | if '--color=always' in sys.argv: 41 | force_processing() 42 | Processor._remove_color_options() 43 | result = True 44 | elif '--color=no' in sys.argv: 45 | Processor._remove_color_options() 46 | result = False 47 | elif sys.stdout.isatty() or force_processing_requested(): 48 | result = True 49 | return result 50 | 51 | 52 | def __init__(self, config, binary): 53 | super().__init__(config, binary) 54 | self.added = config.get_color('added', 'green') 55 | self.removed = config.get_color('removed', 'red') 56 | self.address = config.get_color('address', 'cyan') 57 | self.filename_1 = config.get_color('filename-1', 'red') 58 | self.filename_2 = config.get_color('filename-2', 'green') 59 | 60 | 61 | def _colorize(self, color, line): 62 | return color + line + self.config.color.reset 63 | 64 | 65 | def handle_line(self, line): 66 | if line.startswith('--- '): 67 | return self._colorize(self.filename_1, line) 68 | if line.startswith('+++ '): 69 | return self._colorize(self.filename_2, line) 70 | if line.startswith('@@ '): 71 | return self._colorize(self.address, line) 72 | if line.startswith('-'): 73 | return self._colorize(self.removed, line) 74 | if line.startswith('+'): 75 | return self._colorize(self.added, line) 76 | return line 77 | -------------------------------------------------------------------------------- /outproc/pp/g++.py: -------------------------------------------------------------------------------- 1 | /usr/lib64/python3.6/site-packages/outproc/pp/gcc.py -------------------------------------------------------------------------------- /outproc/pp/gcc.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Output processor for `gcc` 4 | # 5 | # Copyright (c) 2013-2017 Alex Turbov 6 | # 7 | # Pluggable Output Processor is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by the 9 | # Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # Pluggable Output Processor is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 | # See the GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License along 18 | # with this program. If not, see . 19 | # 20 | 21 | from ..cpp_helpers import CodeFormatter, SimpleCppLexer, SnippetSanitizer 22 | from ..processing import Processor as ProcessorBase 23 | from ..term import get_size, get_width, fg2bg, column_formatter, pos_to_offset 24 | 25 | import collections 26 | import functools 27 | import os 28 | import re 29 | import shlex 30 | import sys 31 | import textwrap 32 | 33 | 34 | _TERM_WIDTH = get_size()[0] 35 | _LOCATION_RE = re.compile('([^ :]+?):([0-9]+(,|:[0-9]+[:,]?)?)?') 36 | # /tmp/ccUlKMZA.o:zz.cc:function main: error: undefined reference to 'boost::iostreams::zlib::default_strategy' 37 | _LINK_ERROR_RE = re.compile(':function (vtable for )?(.*): error: ') 38 | _SKIPPING_WARN = re.compile('\[ skipping [0-9]+ instantiation contexts[^\]]+\]') 39 | _WITH_LIST_START = ' [with ' 40 | _HELP_LINE = re.compile('^ (?P